Spaces:
Running
Running
feat(companion): enhance traveling princess lore immersion, deflect technical queries, and sanitize choice suggestions
Browse filesFiles changed (42)
- algospaced-ui/dist/assets/CardManager-BEhyd34f.js → algospaced-ui/dist/assets/CardManager-BMwBGmwK.jsRenamed+1-1
- algospaced-ui/dist/assets/JourneyPath-BhAvKOiu.js → algospaced-ui/dist/assets/JourneyPath-C5zwoWvi.jsRenamed+1-1
- algospaced-ui/dist/assets/MarkdownRenderer-D8UdFpnD.js → algospaced-ui/dist/assets/MarkdownRenderer-BGUaDi8Z.jsRenamed+1-1
- algospaced-ui/dist/assets/PrincessChamber-DlL5aOl1.jsAdded+1
- algospaced-ui/dist/assets/PrincessChamber-abJShfI5.jsDeleted-1
- algospaced-ui/dist/assets/ProblemSpecPanel-BRW8UyO6.js → algospaced-ui/dist/assets/ProblemSpecPanel-C8iV6oe0.jsRenamed+1-1
- algospaced-ui/dist/assets/PythonChallenge-CQdOe4Q2.js → algospaced-ui/dist/assets/PythonChallenge-MiR95vc2.jsRenamed+1-1
- algospaced-ui/dist/assets/ReviewQueue-BRrPvJUP.jsAdded+5
- algospaced-ui/dist/assets/ReviewQueue-CltGWQpb.jsDeleted-5
- algospaced-ui/dist/assets/Settings-BVuXk3LW.jsDeleted-1
- algospaced-ui/dist/assets/Settings-Dm1_pyAR.jsAdded+1
- algospaced-ui/dist/assets/TerminalEmulator-CZed0tiA.js → algospaced-ui/dist/assets/TerminalEmulator-DeoMeHBL.jsRenamed+1-1
- algospaced-ui/dist/assets/index-BsU9BpJx.cssDeleted
- algospaced-ui/dist/assets/index-DVWZ15xt.js → algospaced-ui/dist/assets/index-Q9onQHft.jsRenamed
- algospaced-ui/dist/assets/index-kuOEkBQB.cssAdded
- algospaced-ui/dist/index.html+2-2
- algospaced-ui/dist/sw.js+1-1
- algospaced-ui/package.json+1-1
- algospaced-ui/src/components/PrincessDialoguePopup.tsx+1-1
- algospaced-ui/src/components/Settings.tsx+6-6
- algospaced-ui/src/components/desktop/DesktopWindowContainer.tsx+1-1
- algospaced-ui/src/components/review/EmptyQueueCelebration.tsx+3-3
- algospaced-ui/src/data/companionData.ts+43-43
- algospaced-ui/src/features/companion/api/companionApi.ts+5-4
- algospaced-ui/src/features/companion/components/CharacterStage.tsx+1-1
- algospaced-ui/src/features/companion/components/ChoiceChips.tsx+15-7
- algospaced-ui/src/features/companion/components/JRPGDialogueBox.tsx+14-10
- algospaced-ui/src/features/companion/components/PrincessChamber.tsx+29-11
- algospaced-ui/src/features/companion/components/PrincessToast.tsx+1-1
- algospaced-ui/src/features/companion/components/RoyalSatchelModal.tsx+4-4
- algospaced-ui/src/features/companion/components/SpireProgressModal.tsx+6-6
- algospaced-ui/src/features/companion/data/chapterWeather.ts+2-2
- algospaced-ui/src/features/companion/data/companionLore.ts+41-41
- algospaced-ui/src/features/companion/data/towerRhythms.ts+19-19
- algospaced-ui/src/features/companion/store/useCompanionStore.ts+154-16
- algospaced-ui/src/features/companion/tools/agentTools.ts+3-3
- algospaced-ui/src/features/companion/types.ts+2-2
- algospaced-ui/src/hooks/useCompanionEvents.ts+2-2
- algospaced-ui/src/utils/companionService.ts+5-5
- algospaced-ui/tests/companionChoices.test.mjsAdded+193
- routers/companion.py+259-58
- tests/unit/test_companion_story.pyAdded+366
1import{r as e}from"./rolldown-runtime-hePW80VL.js";import{$ as t,A as n,Bt as r,Dt as i,Ht as a,M as o,P as s,St as c,T as l,X as u,a as ee,b as te,h as ne,mt as re,ot as ie,p as d,q as ae,v as f,x as oe,y as se}from"./vendor-react-hnaVBnLv.js";import{s as p}from"./firebaseClient-DZobvwSx.js";import{i as ce,l as m}from"./index-DVWZ15xt.js";var h=e(a(),1);async function g(){try{let{data:{session:e}}=await p.auth.getSession();return e?e.access_token:`sandbox`}catch{return`sandbox`}}function _(e){return e.toLowerCase().replace(/\s*-\s*method.*$/i,``).replace(/[^a-z0-9]+/g,``)}function v(e){if(typeof e==`string`)try{return JSON.parse(e)}catch{return}return e??void 0}async function le(){let e=await g(),t=ce(),n=[];try{let t=await fetch(`/api/explorer/problems`,{headers:{Authorization:`Bearer ${e}`}});t.ok&&(n=await t.json())}catch{n=[]}let r=new Map,i=new Map,a=new Set;for(let e of n)e.problem_number!==void 0&&e.problem_number!==null&&r.set(e.problem_number,e),i.set(_(e.name),e);let o=new Date,s=[];for(let e of t){let t=r.get(e.problem_number)||i.get(_(e.name));if(t){a.add(t.id);let n=t.next_review!==null&&t.next_review!==void 0||t.fsrs_state!==null&&t.fsrs_state!==void 0,r=t.next_review?new Date(t.next_review):null,i=n&&r!==null?r<=o:!1,c=v(t.solutions),l=v(t.examples),u=v(t.constraints);s.push({id:t.id,problem_number:e.problem_number,name:e.name,pattern:e.pattern,difficulty:e.difficulty,description:t.description||e.description,reference_code:t.reference_code||e.reference_solution,starter_code:t.starter_code||e.starter_code,optimal_time:t.optimal_time||e.time_complexity,optimal_space:t.optimal_space||e.space_complexity,how_to_solve:t.how_to_solve||``,examples:l&&(!Array.isArray(l)||l.length>0)?l:e.examples,constraints:u&&(!Array.isArray(u)||u.length>0)?u:e.constraints,solutions:c,leetcode_url:e.leetcode_url,is_enrolled:n,is_custom:!1,fsrs_state:t.fsrs_state??(n?0:null),fsrs_step:t.fsrs_step??0,fsrs_stability:t.fsrs_stability??0,fsrs_difficulty:t.fsrs_difficulty??0,fsrs_elapsed_days:t.fsrs_elapsed_days??0,fsrs_scheduled_days:t.fsrs_scheduled_days??0,fsrs_reps:t.fsrs_reps??0,fsrs_lapses:t.fsrs_lapses??0,next_review:t.next_review??null,last_reviewed:t.last_reviewed??null,times_correct:t.times_correct??0,total_attempts:t.total_attempts??0,is_due:i,catalogProblem:e})}else s.push({id:e.id,problem_number:e.problem_number,name:e.name,pattern:e.pattern,difficulty:e.difficulty,description:e.description,reference_code:e.reference_solution,starter_code:e.starter_code,optimal_time:e.time_complexity,optimal_space:e.space_complexity,how_to_solve:``,examples:e.examples,constraints:e.constraints,leetcode_url:e.leetcode_url,is_enrolled:!1,is_custom:!1,fsrs_state:null,fsrs_step:0,fsrs_stability:0,fsrs_difficulty:0,fsrs_elapsed_days:0,fsrs_scheduled_days:0,fsrs_reps:0,fsrs_lapses:0,next_review:null,last_reviewed:null,times_correct:0,total_attempts:0,is_due:!1,catalogProblem:e})}for(let e of n)if(!a.has(e.id)){let t=e.next_review!==null&&e.next_review!==void 0||e.fsrs_state!==null&&e.fsrs_state!==void 0,n=e.next_review?new Date(e.next_review):null,r=t&&n!==null?n<=o:!1,i=v(e.solutions),a=v(e.examples)||[],c=v(e.constraints)||[];s.push({id:e.id,problem_number:e.problem_number,name:e.name,pattern:e.pattern||`General`,difficulty:e.difficulty||`Medium`,description:e.description||``,reference_code:e.reference_code||``,starter_code:e.starter_code||``,optimal_time:e.optimal_time||`O(N)`,optimal_space:e.optimal_space||`O(1)`,how_to_solve:e.how_to_solve||``,examples:a,constraints:c,solutions:i,is_enrolled:t,is_custom:!0,fsrs_state:e.fsrs_state??(t?0:null),fsrs_step:e.fsrs_step??0,fsrs_stability:e.fsrs_stability??0,fsrs_difficulty:e.fsrs_difficulty??0,fsrs_elapsed_days:e.fsrs_elapsed_days??0,fsrs_scheduled_days:e.fsrs_scheduled_days??0,fsrs_reps:e.fsrs_reps??0,fsrs_lapses:e.fsrs_lapses??0,next_review:e.next_review??null,last_reviewed:e.last_reviewed??null,times_correct:e.times_correct??0,total_attempts:e.total_attempts??0,is_due:r})}return s}async function y(e){if(e.length===0)return!0;let t=await g(),n=await fetch(`/api/reviews/reset`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${t}`},body:JSON.stringify({problem_ids:e})});if(!n.ok){let e=await n.json().catch(()=>({detail:`Failed to reset reviews`}));throw Error(e.detail||`Failed to reset reviews`)}return!0}async function b(e){let t=await g(),n=await fetch(`/api/explorer/problems/${e}`,{method:`DELETE`,headers:{Authorization:`Bearer ${t}`}});if(!n.ok){let e=await n.json().catch(()=>({detail:`Failed to delete problem`}));throw Error(e.detail||`Failed to delete problem`)}return!0}async function ue(e){let t=0;for(let n of e)try{await b(n),t++}catch{}return t}async function x(e){return e.length===0?0:(await m(e)).enrolled_count}var S=r();function C({onOpenQueue:e,onOpenCreateProblem:r,onOpenEditProblem:a,onSelectProblemForReview:p,refreshTrigger:ce,onRefreshExplorer:m}){let[g,_]=(0,h.useState)([]),[v,C]=(0,h.useState)(!0),[de,w]=(0,h.useState)(null),[T,fe]=(0,h.useState)(``),[E,D]=(0,h.useState)(`all`),[O,pe]=(0,h.useState)(`ALL`),[k,me]=(0,h.useState)(`ALL`),[A,he]=(0,h.useState)(`number`),[j,M]=(0,h.useState)(`asc`),[N,P]=(0,h.useState)(new Set),[F,I]=(0,h.useState)(null),[L,R]=(0,h.useState)(`front`),[z,B]=(0,h.useState)(!1),[V,H]=(0,h.useState)(!1),[ge,U]=(0,h.useState)(null),[W,G]=(0,h.useState)(`table`),K=(0,h.useCallback)(async()=>{C(!0),w(null);try{let e=await le();_(e),e.length>0&&!F&&I(e[0].id)}catch(e){let t=e instanceof Error?e.message:`Failed to load card database`;w(t)}finally{C(!1)}},[F]);(0,h.useEffect)(()=>{K()},[K,ce]);let q=(0,h.useMemo)(()=>{let e=0,t=0,n=0,r=0,i=0,a=0;for(let o of g)if(o.is_enrolled){t++,o.is_due&&e++;let n=o.fsrs_state??0;n===1?r++:n===2?i++:n===3&&a++}else n++;return{total:g.length,due:e,enrolled:t,newCards:n,learning:r,reviewing:i,relearning:a}},[g]),_e=(0,h.useMemo)(()=>{let e=new Map;for(let t of g)e.set(t.pattern,(e.get(t.pattern)||0)+1);let t=Array.from(e.entries()).map(([e,t])=>({pattern:e,count:t}));return t.sort((e,t)=>e.pattern.localeCompare(t.pattern)),t},[g]),ve=(0,h.useMemo)(()=>{let e=T.trim().toLowerCase();return g.filter(t=>{if(E===`due`&&!t.is_due||E===`enrolled`&&!t.is_enrolled||E===`new`&&t.is_enrolled||E===`learning`&&(!t.is_enrolled||t.fsrs_state!==1)||E===`reviewing`&&(!t.is_enrolled||t.fsrs_state!==2)||E===`relearning`&&(!t.is_enrolled||t.fsrs_state!==3)||O!==`ALL`&&t.pattern!==O||k!==`ALL`&&t.difficulty!==k)return!1;if(e){let n=t.problem_number?String(t.problem_number).includes(e):!1,r=t.name.toLowerCase().includes(e),i=t.pattern.toLowerCase().includes(e),a=t.difficulty.toLowerCase().includes(e);if(!n&&!r&&!i&&!a)return!1}return!0})},[g,E,O,k,T]),J=(0,h.useMemo)(()=>{let e=[...ve];return e.sort((e,t)=>{let n=0;switch(A){case`number`:n=(e.problem_number??999999)-(t.problem_number??999999);break;case`name`:n=e.name.localeCompare(t.name);break;case`pattern`:n=e.pattern.localeCompare(t.pattern);break;case`difficulty`:{let r={Easy:1,Medium:2,Hard:3};n=(r[e.difficulty]||2)-(r[t.difficulty]||2);break}case`state`:n=(e.fsrs_state??-1)-(t.fsrs_state??-1);break;case`due`:n=(e.next_review?new Date(e.next_review).getTime():9999999999999)-(t.next_review?new Date(t.next_review).getTime():9999999999999);break;case`retention`:n=(e.total_attempts>0?e.times_correct/e.total_attempts:0)-(t.total_attempts>0?t.times_correct/t.total_attempts:0)}return j===`asc`?n:-n}),e},[ve,A,j]),Y=(0,h.useMemo)(()=>!F&&J.length>0?J[0]:g.find(e=>e.id===F)||J[0]||null,[g,F,J]),X=e=>{A===e?M(e=>e===`asc`?`desc`:`asc`):(he(e),M(`asc`))},ye=(e,t)=>{t.stopPropagation(),P(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},be=(0,h.useMemo)(()=>J.length>0&&J.every(e=>N.has(e.id)),[J,N]),xe=()=>{P(e=>{let t=new Set(e);if(be)for(let e of J)t.delete(e.id);else for(let e of J)t.add(e.id);return t})},Z=(0,h.useMemo)(()=>g.filter(e=>N.has(e.id)&&e.is_custom),[g,N]),Se=async()=>{if(Z.length!==0&&confirm(`Are you sure you want to delete ${Z.length} custom cards?`)){H(!0);try{let e=await ue(Z.map(e=>e.id));U(`Deleted ${e} custom cards.`),P(e=>{let t=new Set(e);for(let e of Z)t.delete(e.id);return t}),await K(),m?.()}catch(e){let t=e instanceof Error?e.message:`Batch delete failed`;w(t)}finally{H(!1),setTimeout(()=>U(null),3500)}}},Ce=async()=>{let e=g.filter(e=>N.has(e.id)&&!e.is_enrolled&&e.catalogProblem);if(e.length===0){U(`No unenrolled catalog cards in current selection.`),setTimeout(()=>U(null),3e3);return}H(!0);try{let t=await x(e.map(e=>e.catalogProblem));U(`Enrolled ${t} cards into Daily Queue!`),P(new Set),await K(),m?.()}catch(e){let t=e instanceof Error?e.message:`Enrollment failed`;w(t)}finally{H(!1),setTimeout(()=>U(null),3500)}},we=async()=>{let e=g.filter(e=>N.has(e.id)&&e.is_enrolled);if(e.length===0){U(`No active cards in selection to reset.`),setTimeout(()=>U(null),3e3);return}H(!0);try{await y(e.map(e=>e.id)),U(`Reset ${e.length} cards to initial FSRS state due today!`),P(new Set),await K(),m?.()}catch(e){let t=e instanceof Error?e.message:`Reset failed`;w(t)}finally{H(!1),setTimeout(()=>U(null),3500)}},Te=async e=>{H(!0);try{await y([e.id]),U(`Reset #${e.problem_number??`—`} ${e.name} for FSRS!`),await K(),m?.()}catch(e){let t=e instanceof Error?e.message:`Reset failed`;w(t)}finally{H(!1),setTimeout(()=>U(null),3500)}},Ee=async e=>{if(e.catalogProblem){H(!0);try{await x([e.catalogProblem]),U(`Enrolled #${e.problem_number??`—`} ${e.name} into review queue!`),await K(),m?.()}catch(e){let t=e instanceof Error?e.message:`Enrollment failed`;w(t)}finally{H(!1),setTimeout(()=>U(null),3500)}}},De=async e=>{if(confirm(`Are you sure you want to delete custom card "${e.name}"?`)){H(!0);try{await b(e.id),U(`Deleted custom card "${e.name}"`),await K(),m?.()}catch(e){let t=e instanceof Error?e.message:`Delete failed`;w(t)}finally{H(!1),setTimeout(()=>U(null),3500)}}},Q=(0,h.useCallback)(t=>{p(t.id),e()},[p,e]),$=e=>{a({id:e.id,name:e.name,problem_number:e.problem_number,pattern:e.pattern,difficulty:e.difficulty,description:e.description,examples:e.examples,constraints:e.constraints,optimal_time:e.optimal_time,optimal_space:e.optimal_space,starter_code:e.starter_code,reference_code:e.reference_code,how_to_solve:e.how_to_solve,solutions:e.solutions})},Oe=()=>{Y?.reference_code&&(navigator.clipboard.writeText(Y.reference_code),B(!0),setTimeout(()=>B(!1),2e3))},ke=(e,t,n)=>{if(!n)return`Not enrolled`;if(!e)return`Due now`;if(t)return`Due today`;let r=new Date(e),i=new Date,a=Math.ceil((r.getTime()-i.getTime())/864e5);return a<=1?`Tomorrow`:`In ${a}d`};return(0,h.useEffect)(()=>{let e=e=>{let t=e.target;if(t.tagName===`INPUT`||t.tagName===`TEXTAREA`||t.tagName===`SELECT`||t.isContentEditable||J.length===0)return;let n=J.findIndex(e=>e.id===Y?.id);if(e.key===`ArrowDown`){e.preventDefault();let t=n<J.length-1?n+1:0;I(J[t].id)}else if(e.key===`ArrowUp`){e.preventDefault();let t=n>0?n-1:J.length-1;I(J[t].id)}else e.key===` `||e.code===`Space`?(e.preventDefault(),R(e=>e===`front`?`back`:`front`)):e.key===`Enter`&&Y?.is_enrolled&&(e.preventDefault(),Q(Y))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[J,Y,Q]),(0,S.jsxs)(`div`,{className:`w-full h-full flex flex-col bg-[#fdf8e1] font-sans text-ink-black select-none overflow-hidden`,children:[(0,S.jsxs)(`div`,{className:`bg-slate-900 text-white border-b-[3px] border-ink-black px-4 py-2.5 flex flex-wrap items-center justify-between gap-3 shrink-0`,children:[(0,S.jsxs)(`div`,{className:`flex items-center gap-2.5`,children:[(0,S.jsx)(`div`,{className:`w-8 h-8 rounded bg-sky-500 border-2 border-white flex items-center justify-center shadow-[2px_2px_0px_0px_rgba(0,0,0,0.5)]`,children:(0,S.jsx)(ae,{className:`w-5 h-5 text-white stroke-[2.5]`})}),(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`h1`,{className:`font-arcade text-xs sm:text-sm font-bold tracking-wider text-amber-300 uppercase flex items-center gap-1.5`,children:`MANAGE FSRS`}),(0,S.jsx)(`p`,{className:`text-[10px] text-slate-300 font-mono`,children:`Browse, filter, and reschedule spaced-repetition cards`})]})]}),(0,S.jsxs)(`div`,{className:`flex items-center gap-1.5 sm:gap-2 flex-wrap text-[10px] font-mono`,children:[(0,S.jsxs)(`button`,{onClick:()=>D(`all`),className:`px-2 py-0.5 border border-slate-700 rounded transition-colors cursor-pointer ${E===`all`?`bg-sky-500 text-white font-bold`:`bg-slate-800 text-slate-300 hover:bg-slate-700`}`,children:[`Total: `,(0,S.jsx)(`span`,{className:`font-bold`,children:q.total})]}),(0,S.jsxs)(`button`,{onClick:()=>D(`due`),className:`px-2 py-0.5 border border-slate-700 rounded transition-colors cursor-pointer ${E===`due`?`bg-rose-500 text-white font-bold`:`bg-slate-800 text-rose-300 hover:bg-slate-700`}`,children:[`Due Today: `,(0,S.jsx)(`span`,{className:`font-bold`,children:q.due})]}),(0,S.jsxs)(`button`,{onClick:()=>D(`enrolled`),className:`px-2 py-0.5 border border-slate-700 rounded transition-colors cursor-pointer ${E===`enrolled`?`bg-emerald-600 text-white font-bold`:`bg-slate-800 text-emerald-300 hover:bg-slate-700`}`,children:[`In Review: `,(0,S.jsx)(`span`,{className:`font-bold`,children:q.enrolled})]}),(0,S.jsxs)(`button`,{onClick:()=>D(`learning`),className:`px-2 py-0.5 border border-slate-700 rounded transition-colors cursor-pointer ${E===`learning`?`bg-amber-500 text-slate-900 font-bold`:`bg-slate-800 text-amber-300 hover:bg-slate-700`}`,children:[`Learning: `,(0,S.jsx)(`span`,{className:`font-bold`,children:q.learning})]}),(0,S.jsxs)(`button`,{onClick:()=>D(`reviewing`),className:`px-2 py-0.5 border border-slate-700 rounded transition-colors cursor-pointer ${E===`reviewing`?`bg-emerald-600 text-white font-bold`:`bg-slate-800 text-emerald-300 hover:bg-slate-700`}`,children:[`Review: `,(0,S.jsx)(`span`,{className:`font-bold`,children:q.reviewing})]}),(0,S.jsxs)(`button`,{onClick:()=>D(`relearning`),className:`px-2 py-0.5 border border-slate-700 rounded transition-colors cursor-pointer ${E===`relearning`?`bg-rose-600 text-white font-bold`:`bg-slate-800 text-rose-300 hover:bg-slate-700`}`,children:[`Relearning: `,(0,S.jsx)(`span`,{className:`font-bold`,children:q.relearning})]}),(0,S.jsxs)(`button`,{onClick:()=>D(`new`),className:`px-2 py-0.5 border border-slate-700 rounded transition-colors cursor-pointer ${E===`new`?`bg-indigo-600 text-white font-bold`:`bg-slate-800 text-indigo-300 hover:bg-slate-700`}`,children:[`Unenrolled: `,(0,S.jsx)(`span`,{className:`font-bold`,children:q.newCards})]})]}),(0,S.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,S.jsxs)(`button`,{onClick:r,className:`px-2.5 py-1 bg-grass-green hover:bg-emerald-400 text-ink-black border-2 border-white rounded font-arcade text-[9px] font-bold shadow-[2px_2px_0px_0px_rgba(0,0,0,0.5)] active:translate-y-0.5 cursor-pointer flex items-center gap-1`,children:[(0,S.jsx)(re,{className:`w-3.5 h-3.5`}),(0,S.jsx)(`span`,{children:`ADD CARD`})]}),(0,S.jsx)(`button`,{onClick:K,disabled:v,className:`p-1 bg-slate-800 hover:bg-slate-700 text-slate-200 border border-slate-600 rounded cursor-pointer disabled:opacity-50`,title:`Refresh Deck`,children:(0,S.jsx)(o,{className:`w-3.5 h-3.5 ${v?`animate-spin`:``}`})})]})]}),ge&&(0,S.jsxs)(`div`,{className:`bg-amber-300 border-b-2 border-ink-black px-4 py-1.5 text-xs font-bold text-ink-black flex items-center justify-between shrink-0`,children:[(0,S.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,S.jsx)(oe,{className:`w-4 h-4 text-amber-800`}),(0,S.jsx)(`span`,{children:ge})]}),(0,S.jsx)(`button`,{onClick:()=>U(null),className:`text-xs hover:opacity-75 cursor-pointer`,children:`✕`})]}),de&&(0,S.jsxs)(`div`,{className:`bg-rose-100 border-b-2 border-rose-400 px-4 py-1.5 text-xs font-semibold text-rose-800 flex items-center justify-between shrink-0`,children:[(0,S.jsx)(`span`,{children:de}),(0,S.jsx)(`button`,{onClick:()=>w(null),className:`text-xs hover:opacity-75 cursor-pointer`,children:`✕`})]}),(0,S.jsxs)(`div`,{className:`sm:hidden flex border-b-2 border-ink-black bg-white shrink-0`,children:[(0,S.jsxs)(`button`,{onClick:()=>G(`table`),className:`flex-1 py-2 font-arcade text-[10px] font-bold text-center border-r border-ink-black ${W===`table`?`bg-amber-300 text-ink-black`:`text-slate-600`}`,children:[`CARDS LIST (`,J.length,`)`]}),(0,S.jsxs)(`button`,{onClick:()=>G(`inspector`),className:`flex-1 py-2 font-arcade text-[10px] font-bold text-center ${W===`inspector`?`bg-amber-300 text-ink-black`:`text-slate-600`}`,children:[`INSPECTOR `,Y?`#${Y.problem_number??``}`:``]})]}),(0,S.jsxs)(`div`,{className:`flex-1 flex overflow-hidden`,children:[(0,S.jsxs)(`aside`,{className:`w-56 bg-[#f7f0cf] border-r-[3px] border-ink-black flex flex-col shrink-0 overflow-y-auto custom-scrollbar hidden md:flex`,children:[(0,S.jsx)(`div`,{className:`p-3 border-b-2 border-ink-black/20`,children:(0,S.jsxs)(`span`,{className:`font-arcade text-[9px] font-bold text-ink-black uppercase tracking-wider flex items-center gap-1.5`,children:[(0,S.jsx)(t,{className:`w-3.5 h-3.5 text-amber-700`}),` DECKS & STATES`]})}),(0,S.jsxs)(`div`,{className:`p-2 space-y-1 text-xs`,children:[(0,S.jsxs)(`button`,{onClick:()=>D(`all`),className:`w-full text-left px-2.5 py-1.5 rounded flex items-center justify-between cursor-pointer transition-colors ${E===`all`?`bg-ink-black text-amber-300 font-bold`:`hover:bg-amber-200/60 text-ink-black font-semibold`}`,children:[(0,S.jsx)(`span`,{children:`📁 All Cards`}),(0,S.jsx)(`span`,{className:`font-mono text-[10px] opacity-80`,children:q.total})]}),(0,S.jsxs)(`button`,{onClick:()=>D(`due`),className:`w-full text-left px-2.5 py-1.5 rounded flex items-center justify-between cursor-pointer transition-colors ${E===`due`?`bg-ink-black text-rose-300 font-bold`:`hover:bg-amber-200/60 text-rose-900 font-semibold`}`,children:[(0,S.jsx)(`span`,{className:`flex items-center gap-1`,children:`⏰ Due Today`}),(0,S.jsx)(`span`,{className:`font-mono text-[10px] font-bold text-rose-600`,children:q.due})]}),(0,S.jsxs)(`button`,{onClick:()=>D(`enrolled`),className:`w-full text-left px-2.5 py-1.5 rounded flex items-center justify-between cursor-pointer transition-colors ${E===`enrolled`?`bg-ink-black text-emerald-300 font-bold`:`hover:bg-amber-200/60 text-ink-black font-semibold`}`,children:[(0,S.jsx)(`span`,{children:`📥 In Review`}),(0,S.jsx)(`span`,{className:`font-mono text-[10px] opacity-80`,children:q.enrolled})]}),(0,S.jsxs)(`button`,{onClick:()=>D(`new`),className:`w-full text-left px-2.5 py-1.5 rounded flex items-center justify-between cursor-pointer transition-colors ${E===`new`?`bg-ink-black text-sky-300 font-bold`:`hover:bg-amber-200/60 text-ink-black font-semibold`}`,children:[(0,S.jsx)(`span`,{children:`🆕 Unenrolled (Catalog)`}),(0,S.jsx)(`span`,{className:`font-mono text-[10px] opacity-80`,children:q.newCards})]}),(0,S.jsxs)(`button`,{onClick:()=>D(`learning`),className:`w-full text-left px-2.5 py-1.5 rounded flex items-center justify-between cursor-pointer transition-colors ${E===`learning`?`bg-ink-black text-amber-300 font-bold`:`hover:bg-amber-200/60 text-ink-black font-semibold`}`,children:[(0,S.jsx)(`span`,{children:`🔄 Learning (State 1)`}),(0,S.jsx)(`span`,{className:`font-mono text-[10px] opacity-80`,children:q.learning})]}),(0,S.jsxs)(`button`,{onClick:()=>D(`reviewing`),className:`w-full text-left px-2.5 py-1.5 rounded flex items-center justify-between cursor-pointer transition-colors ${E===`reviewing`?`bg-ink-black text-emerald-300 font-bold`:`hover:bg-amber-200/60 text-ink-black font-semibold`}`,children:[(0,S.jsx)(`span`,{children:`📈 Review (State 2)`}),(0,S.jsx)(`span`,{className:`font-mono text-[10px] opacity-80`,children:q.reviewing})]}),(0,S.jsxs)(`button`,{onClick:()=>D(`relearning`),className:`w-full text-left px-2.5 py-1.5 rounded flex items-center justify-between cursor-pointer transition-colors ${E===`relearning`?`bg-ink-black text-rose-300 font-bold`:`hover:bg-amber-200/60 text-ink-black font-semibold`}`,children:[(0,S.jsx)(`span`,{children:`🔁 Relearning (State 3)`}),(0,S.jsx)(`span`,{className:`font-mono text-[10px] opacity-80`,children:q.relearning})]})]}),(0,S.jsx)(`div`,{className:`p-3 border-t-2 border-ink-black/20`,children:(0,S.jsxs)(`span`,{className:`font-arcade text-[9px] font-bold text-ink-black uppercase tracking-wider flex items-center gap-1.5`,children:[(0,S.jsx)(ne,{className:`w-3.5 h-3.5 text-purple-700`}),` PATTERNS (TAGS)`]})}),(0,S.jsxs)(`div`,{className:`p-2 space-y-0.5 text-xs flex-1`,children:[(0,S.jsxs)(`button`,{onClick:()=>pe(`ALL`),className:`w-full text-left px-2.5 py-1 rounded flex items-center justify-between cursor-pointer transition-colors ${O===`ALL`?`bg-purple-900 text-white font-bold`:`hover:bg-purple-100 text-ink-black font-semibold`}`,children:[(0,S.jsx)(`span`,{children:`All Patterns`}),(0,S.jsx)(`span`,{className:`font-mono text-[10px] opacity-80`,children:g.length})]}),_e.map(({pattern:e,count:t})=>(0,S.jsxs)(`button`,{onClick:()=>pe(e),className:`w-full text-left px-2.5 py-1 rounded flex items-center justify-between cursor-pointer transition-colors text-[11px] ${O===e?`bg-purple-900 text-white font-bold`:`hover:bg-purple-100 text-ink-black`}`,children:[(0,S.jsx)(`span`,{className:`truncate`,children:e}),(0,S.jsx)(`span`,{className:`font-mono text-[10px] opacity-80 shrink-0 ml-1`,children:t})]},e))]})]}),(0,S.jsxs)(`div`,{className:`flex-1 flex flex-col min-w-0 bg-white border-r-[3px] border-ink-black ${W===`inspector`?`hidden sm:flex`:`flex`}`,children:[(0,S.jsxs)(`div`,{className:`p-3 bg-[#fdf8e1] border-b-2 border-ink-black flex flex-wrap items-center justify-between gap-2 shrink-0`,children:[(0,S.jsxs)(`div`,{className:`relative flex-1 min-w-[200px]`,children:[(0,S.jsx)(l,{className:`w-4 h-4 absolute left-2.5 top-2.5 text-slate-500`}),(0,S.jsx)(`input`,{type:`text`,value:T,onChange:e=>fe(e.target.value),placeholder:`Search by card #, title, pattern, or keyword...`,className:`w-full pl-8 pr-3 py-1.5 bg-white border-2 border-ink-black text-xs font-semibold focus:outline-none focus:ring-2 focus:ring-sky-500 shadow-[2px_2px_0px_0px_rgba(30,41,59,1)]`}),T&&(0,S.jsx)(`button`,{onClick:()=>fe(``),className:`absolute right-2.5 top-2 text-slate-400 hover:text-ink-black text-xs cursor-pointer`,children:`✕`})]}),(0,S.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,S.jsxs)(`select`,{"aria-label":`Filter cards by difficulty`,value:k,onChange:e=>me(e.target.value),className:`px-2.5 py-1.5 bg-white border-2 border-ink-black text-xs font-bold shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] cursor-pointer`,children:[(0,S.jsx)(`option`,{value:`ALL`,children:`All Difficulties`}),(0,S.jsx)(`option`,{value:`Easy`,children:`Easy`}),(0,S.jsx)(`option`,{value:`Medium`,children:`Medium`}),(0,S.jsx)(`option`,{value:`Hard`,children:`Hard`})]}),(0,S.jsxs)(`span`,{className:`text-[11px] font-mono text-slate-600 font-semibold hidden lg:inline`,children:[J.length,` matching cards`]})]})]}),N.size>0&&(0,S.jsxs)(`div`,{className:`bg-sky-100 border-b-2 border-ink-black px-3 py-2 flex items-center justify-between gap-2 shrink-0 animate-in fade-in flex-wrap`,children:[(0,S.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,S.jsxs)(`span`,{className:`font-arcade text-[10px] font-bold text-sky-900 uppercase`,children:[N.size,` SELECTED`,Z.length>0&&` (${Z.length} custom)`]}),(0,S.jsx)(`button`,{onClick:()=>P(new Set),className:`text-xs text-sky-800 underline hover:text-sky-950 cursor-pointer`,children:`Clear`})]}),(0,S.jsxs)(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[(0,S.jsxs)(`button`,{onClick:Ce,disabled:V,className:`px-3 py-1 bg-grass-green hover:bg-emerald-400 text-ink-black font-arcade text-[9px] font-bold border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 cursor-pointer flex items-center gap-1 disabled:opacity-50`,children:[(0,S.jsx)(ee,{className:`w-3.5 h-3.5 text-amber-900`}),(0,S.jsx)(`span`,{children:`ADD TO QUEUE`})]}),(0,S.jsxs)(`button`,{onClick:we,disabled:V,className:`px-3 py-1 bg-amber-300 hover:bg-amber-400 text-ink-black font-arcade text-[9px] font-bold border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 cursor-pointer flex items-center gap-1 disabled:opacity-50`,children:[(0,S.jsx)(n,{className:`w-3.5 h-3.5`}),(0,S.jsx)(`span`,{children:`RESET PROGRESS`})]}),Z.length>0&&(0,S.jsxs)(`button`,{onClick:Se,disabled:V,className:`px-3 py-1 bg-rose-200 hover:bg-rose-300 text-rose-950 font-arcade text-[9px] font-bold border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 cursor-pointer flex items-center gap-1 disabled:opacity-50`,children:[(0,S.jsx)(d,{className:`w-3.5 h-3.5 text-rose-700`}),(0,S.jsxs)(`span`,{children:[`DELETE CUSTOM (`,Z.length,`)`]})]})]})]}),(0,S.jsx)(`div`,{className:`flex-1 overflow-y-auto custom-scrollbar`,children:(0,S.jsxs)(`table`,{className:`w-full text-left border-collapse text-xs`,children:[(0,S.jsx)(`thead`,{className:`sticky top-0 bg-[#f4ebd0] border-b-2 border-ink-black font-arcade text-[9px] font-bold text-ink-black z-10 select-none`,children:(0,S.jsxs)(`tr`,{children:[(0,S.jsx)(`th`,{className:`p-2 w-8 text-center border-r border-ink-black/20`,children:(0,S.jsx)(`button`,{onClick:xe,className:`cursor-pointer flex items-center justify-center mx-auto text-ink-black`,title:`Select all matching cards`,children:be?(0,S.jsx)(te,{className:`w-4 h-4 text-sky-700`}):(0,S.jsx)(f,{className:`w-4 h-4`})})}),(0,S.jsx)(`th`,{onClick:()=>X(`number`),className:`p-2 w-16 cursor-pointer hover:bg-amber-200/50 border-r border-ink-black/20`,children:(0,S.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,S.jsx)(`span`,{children:`#`}),(0,S.jsx)(i,{className:`w-3 h-3 opacity-60`})]})}),(0,S.jsx)(`th`,{onClick:()=>X(`name`),className:`p-2 cursor-pointer hover:bg-amber-200/50 border-r border-ink-black/20`,children:(0,S.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,S.jsx)(`span`,{children:`CARD TITLE`}),(0,S.jsx)(i,{className:`w-3 h-3 opacity-60`})]})}),(0,S.jsx)(`th`,{onClick:()=>X(`pattern`),className:`p-2 hidden md:table-cell cursor-pointer hover:bg-amber-200/50 border-r border-ink-black/20`,children:(0,S.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,S.jsx)(`span`,{children:`DECK / PATTERN`}),(0,S.jsx)(i,{className:`w-3 h-3 opacity-60`})]})}),(0,S.jsx)(`th`,{onClick:()=>X(`difficulty`),className:`p-2 w-20 cursor-pointer hover:bg-amber-200/50 border-r border-ink-black/20`,children:(0,S.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,S.jsx)(`span`,{children:`DIFF`}),(0,S.jsx)(i,{className:`w-3 h-3 opacity-60`})]})}),(0,S.jsx)(`th`,{onClick:()=>X(`state`),className:`p-2 w-24 cursor-pointer hover:bg-amber-200/50 border-r border-ink-black/20`,children:(0,S.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,S.jsx)(`span`,{children:`FSRS STATE`}),(0,S.jsx)(i,{className:`w-3 h-3 opacity-60`})]})}),(0,S.jsx)(`th`,{onClick:()=>X(`due`),className:`p-2 w-24 cursor-pointer hover:bg-amber-200/50 border-r border-ink-black/20`,children:(0,S.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,S.jsx)(`span`,{children:`DUE`}),(0,S.jsx)(i,{className:`w-3 h-3 opacity-60`})]})}),(0,S.jsx)(`th`,{onClick:()=>X(`retention`),className:`p-2 w-20 hidden lg:table-cell cursor-pointer hover:bg-amber-200/50`,children:(0,S.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,S.jsx)(`span`,{children:`RETENTION`}),(0,S.jsx)(i,{className:`w-3 h-3 opacity-60`})]})})]})}),(0,S.jsx)(`tbody`,{className:`divide-y divide-slate-200`,children:J.length===0?(0,S.jsx)(`tr`,{children:(0,S.jsx)(`td`,{colSpan:8,className:`p-8 text-center text-trash-gray font-mono`,children:`No cards match current filter criteria.`})}):J.map(e=>{let t=N.has(e.id),n=Y?.id===e.id;return(0,S.jsxs)(`tr`,{onClick:()=>{I(e.id),G(`inspector`)},onDoubleClick:()=>{e.is_enrolled?Q(e):$(e)},className:`cursor-pointer transition-colors ${n?`bg-sky-100 font-semibold`:t?`bg-amber-50`:`hover:bg-slate-50`}`,children:[(0,S.jsx)(`td`,{className:`p-2 text-center`,onClick:t=>ye(e.id,t),children:t?(0,S.jsx)(te,{className:`w-4 h-4 text-sky-600 mx-auto`}):(0,S.jsx)(f,{className:`w-4 h-4 text-slate-400 mx-auto`})}),(0,S.jsx)(`td`,{className:`p-2 font-mono text-[11px] font-bold text-slate-700`,children:e.problem_number?`#${e.problem_number}`:`—`}),(0,S.jsx)(`td`,{className:`p-2`,children:(0,S.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,S.jsx)(`span`,{className:`font-semibold text-ink-black truncate`,children:e.name}),e.is_custom&&(0,S.jsx)(`span`,{className:`px-1.5 py-0.2 rounded bg-purple-100 text-purple-800 border border-purple-300 text-[8px] font-bold uppercase shrink-0`,children:`CUSTOM`})]})}),(0,S.jsx)(`td`,{className:`p-2 hidden md:table-cell text-slate-600 text-[11px] truncate`,children:e.pattern}),(0,S.jsx)(`td`,{className:`p-2`,children:(0,S.jsx)(`span`,{className:`px-1.5 py-0.5 rounded font-arcade text-[8px] font-bold uppercase text-white ${e.difficulty===`Easy`?`bg-emerald-600`:e.difficulty===`Medium`?`bg-amber-600`:`bg-rose-600`}`,children:e.difficulty})}),(0,S.jsx)(`td`,{className:`p-2`,children:e.is_enrolled?(0,S.jsxs)(`span`,{className:`inline-flex items-center gap-1 font-mono text-[10px] font-bold text-slate-800`,children:[(0,S.jsx)(`span`,{className:`w-2 h-2 rounded-full ${(e.fsrs_state??0)===2?`bg-emerald-500`:(e.fsrs_state??0)===1?`bg-amber-500`:(e.fsrs_state??0)===3?`bg-rose-500`:`bg-blue-500`}`}),(e.fsrs_state??0)===0?`New`:(e.fsrs_state??0)===1?`Learning`:(e.fsrs_state??0)===2?`Review`:`Relearning`]}):(0,S.jsx)(`span`,{className:`text-[10px] font-mono text-slate-400 uppercase font-semibold`,children:`Unenrolled`})}),(0,S.jsx)(`td`,{className:`p-2 font-mono text-[10px]`,children:(0,S.jsx)(`span`,{className:e.is_due?`text-rose-600 font-bold bg-rose-50 px-1 py-0.5 rounded border border-rose-200`:`text-slate-600`,children:ke(e.next_review,e.is_due,e.is_enrolled)})}),(0,S.jsx)(`td`,{className:`p-2 hidden lg:table-cell font-mono text-[10px] text-slate-600`,children:e.total_attempts>0?(0,S.jsxs)(`span`,{children:[e.times_correct,`/`,e.total_attempts,` `,(0,S.jsxs)(`span`,{className:`text-[9px] text-slate-400`,children:[`(`,Math.round(e.times_correct/e.total_attempts*100),`%)`]})]}):(0,S.jsx)(`span`,{className:`text-slate-400`,children:`—`})})]},e.id)})})]})})]}),(0,S.jsx)(`aside`,{className:`w-full sm:w-80 lg:w-96 bg-[#fdf8e1] flex flex-col shrink-0 overflow-hidden ${W===`table`?`hidden sm:flex`:`flex`}`,children:Y?(0,S.jsxs)(`div`,{className:`flex-1 flex flex-col h-full overflow-hidden`,children:[(0,S.jsxs)(`div`,{className:`p-4 bg-[#f8efcd] border-b-2 border-ink-black space-y-2 shrink-0`,children:[(0,S.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,S.jsxs)(`span`,{className:`font-arcade text-[9px] font-bold text-amber-900 uppercase flex items-center gap-1`,children:[(0,S.jsx)(u,{className:`w-3.5 h-3.5 text-amber-700`}),` CARD INSPECTOR`]}),(0,S.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,S.jsx)(`span`,{className:`px-1.5 py-0.5 rounded font-arcade text-[8px] font-bold uppercase text-white ${Y.difficulty===`Easy`?`bg-emerald-600`:Y.difficulty===`Medium`?`bg-amber-600`:`bg-rose-600`}`,children:Y.difficulty}),(0,S.jsx)(`span`,{className:`font-mono text-[10px] font-bold px-1.5 py-0.5 bg-white border border-ink-black rounded`,children:Y.problem_number?`#${Y.problem_number}`:`Custom`})]})]}),(0,S.jsx)(`h3`,{className:`font-headline-md text-base font-extrabold text-ink-black leading-tight`,children:Y.name}),(0,S.jsxs)(`div`,{className:`flex items-center gap-1.5 flex-wrap text-[10px] font-mono text-slate-700`,children:[(0,S.jsx)(`span`,{className:`bg-purple-100 text-purple-900 px-2 py-0.5 rounded border border-purple-200 font-semibold`,children:Y.pattern}),Y.optimal_time&&(0,S.jsxs)(`span`,{className:`bg-slate-100 px-1.5 py-0.5 rounded border border-slate-300`,children:[`T: `,Y.optimal_time]}),Y.optimal_space&&(0,S.jsxs)(`span`,{className:`bg-slate-100 px-1.5 py-0.5 rounded border border-slate-300`,children:[`S: `,Y.optimal_space]})]}),(0,S.jsxs)(`div`,{className:`flex items-center gap-1.5 pt-2 flex-wrap`,children:[Y.is_enrolled?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)(`button`,{onClick:()=>Q(Y),className:`px-2.5 py-1 bg-grass-green hover:bg-emerald-400 text-ink-black font-arcade text-[9px] font-bold border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 cursor-pointer flex items-center gap-1`,children:[(0,S.jsx)(s,{className:`w-3 h-3 fill-ink-black`}),(0,S.jsx)(`span`,{children:`REVIEW NOW`})]}),(0,S.jsxs)(`button`,{onClick:()=>Te(Y),disabled:V,className:`px-2 py-1 bg-amber-200 hover:bg-amber-300 text-ink-black font-arcade text-[9px] font-bold border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 cursor-pointer flex items-center gap-1 disabled:opacity-50`,title:`Reset interval to initial FSRS state due today`,children:[(0,S.jsx)(n,{className:`w-3 h-3`}),(0,S.jsx)(`span`,{children:`RESET`})]})]}):(0,S.jsxs)(`button`,{onClick:()=>Ee(Y),disabled:V||!Y.catalogProblem,className:`px-2.5 py-1 bg-sky-400 hover:bg-sky-300 text-ink-black font-arcade text-[9px] font-bold border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 cursor-pointer flex items-center gap-1 disabled:opacity-50`,children:[(0,S.jsx)(re,{className:`w-3 h-3`}),(0,S.jsx)(`span`,{children:`ENROLL CARD`})]}),(0,S.jsxs)(`button`,{onClick:()=>$(Y),className:`px-2 py-1 bg-white hover:bg-slate-100 text-ink-black font-arcade text-[9px] font-bold border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 cursor-pointer flex items-center gap-1`,children:[(0,S.jsx)(se,{className:`w-3 h-3`}),(0,S.jsx)(`span`,{children:`EDIT`})]}),Y.is_custom&&(0,S.jsxs)(`button`,{onClick:()=>De(Y),disabled:V,className:`px-2 py-1 bg-rose-200 hover:bg-rose-300 text-rose-950 font-arcade text-[9px] font-bold border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 cursor-pointer flex items-center gap-1 disabled:opacity-50`,children:[(0,S.jsx)(d,{className:`w-3 h-3 text-rose-700`}),(0,S.jsx)(`span`,{children:`DELETE`})]})]})]}),(0,S.jsxs)(`div`,{className:`flex border-b-2 border-ink-black bg-white shrink-0`,children:[(0,S.jsx)(`button`,{onClick:()=>R(`front`),className:`flex-1 py-1.5 font-arcade text-[9px] font-bold text-center border-r border-ink-black/20 cursor-pointer ${L===`front`?`bg-amber-300 text-ink-black`:`text-slate-600 hover:bg-slate-50`}`,children:`QUESTION`}),(0,S.jsx)(`button`,{onClick:()=>R(`back`),className:`flex-1 py-1.5 font-arcade text-[9px] font-bold text-center border-r border-ink-black/20 cursor-pointer ${L===`back`?`bg-amber-300 text-ink-black`:`text-slate-600 hover:bg-slate-50`}`,children:`SHOW ANSWER`}),(0,S.jsx)(`button`,{onClick:()=>R(`stats`),className:`flex-1 py-1.5 font-arcade text-[9px] font-bold text-center cursor-pointer ${L===`stats`?`bg-amber-300 text-ink-black`:`text-slate-600 hover:bg-slate-50`}`,children:`SRS INFO`})]}),(0,S.jsxs)(`div`,{className:`flex-1 p-4 overflow-y-auto custom-scrollbar space-y-4`,children:[L===`front`&&(0,S.jsxs)(`div`,{className:`space-y-3`,children:[(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`span`,{className:`font-arcade text-[8px] font-bold text-trash-gray uppercase block mb-1`,children:`PROBLEM DESCRIPTION`}),(0,S.jsx)(`div`,{className:`p-3 bg-white border-2 border-ink-black text-xs font-semibold leading-relaxed shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] whitespace-pre-wrap`,children:Y.description||`No description provided.`})]}),Y.examples&&(!Array.isArray(Y.examples)||Y.examples.length>0)&&(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`span`,{className:`font-arcade text-[8px] font-bold text-trash-gray uppercase block mb-1`,children:`EXAMPLES`}),(0,S.jsx)(`div`,{className:`space-y-1.5`,children:Array.isArray(Y.examples)?Y.examples.map((e,t)=>typeof e==`string`?(0,S.jsx)(`div`,{className:`p-2 bg-white border border-slate-300 text-[11px] font-mono`,children:e},t):(0,S.jsxs)(`div`,{className:`p-2 bg-white border border-slate-300 text-[11px] font-mono space-y-0.5`,children:[e.input&&(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`span`,{className:`font-bold text-slate-700`,children:`Input:`}),` `,e.input]}),e.output&&(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`span`,{className:`font-bold text-slate-700`,children:`Output:`}),` `,e.output]}),e.explanation&&(0,S.jsx)(`div`,{className:`text-slate-500 italic text-[10px]`,children:e.explanation})]},t)):(0,S.jsx)(`div`,{className:`p-2 bg-white border border-slate-300 text-[11px] font-mono`,children:String(Y.examples)})})]}),Y.constraints&&(!Array.isArray(Y.constraints)||Y.constraints.length>0)&&(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`span`,{className:`font-arcade text-[8px] font-bold text-trash-gray uppercase block mb-1`,children:`CONSTRAINTS`}),(0,S.jsx)(`div`,{className:`p-2.5 bg-slate-50 border border-slate-300 text-[11px] font-mono space-y-1 text-slate-700`,children:Array.isArray(Y.constraints)?Y.constraints.map((e,t)=>(0,S.jsxs)(`div`,{children:[`• `,e]},t)):(0,S.jsxs)(`div`,{children:[`• `,String(Y.constraints)]})})]})]}),L===`back`&&(0,S.jsxs)(`div`,{className:`space-y-3`,children:[(0,S.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,S.jsx)(`span`,{className:`font-arcade text-[8px] font-bold text-trash-gray uppercase`,children:`REFERENCE SOLUTION (PYTHON)`}),Y.reference_code&&(0,S.jsxs)(`button`,{onClick:Oe,className:`px-2 py-0.5 bg-white hover:bg-slate-100 text-ink-black border border-ink-black text-[9px] font-bold rounded flex items-center gap-1 cursor-pointer`,children:[z?(0,S.jsx)(c,{className:`w-3 h-3 text-emerald-600`}):(0,S.jsx)(ie,{className:`w-3 h-3`}),(0,S.jsx)(`span`,{children:z?`COPIED!`:`COPY`})]})]}),(0,S.jsx)(`div`,{className:`relative`,children:(0,S.jsx)(`pre`,{className:`p-3 bg-slate-900 text-emerald-400 font-mono text-[11px] rounded border-2 border-ink-black overflow-x-auto shadow-[2px_2px_0px_0px_rgba(30,41,59,1)]`,children:(0,S.jsx)(`code`,{children:Y.reference_code||`# No reference code available.`})})}),Y.how_to_solve&&(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`span`,{className:`font-arcade text-[8px] font-bold text-trash-gray uppercase block mb-1`,children:`HOW TO SOLVE & STRATEGY`}),(0,S.jsx)(`div`,{className:`p-2.5 bg-white border border-slate-300 text-xs font-semibold leading-relaxed`,children:Y.how_to_solve})]})]}),L===`stats`&&(0,S.jsxs)(`div`,{className:`space-y-3`,children:[(0,S.jsxs)(`div`,{className:`p-3 bg-white border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] space-y-2`,children:[(0,S.jsx)(`span`,{className:`font-arcade text-[9px] font-bold text-ink-black uppercase block border-b pb-1`,children:`FSRS REVIEW STATE`}),(0,S.jsxs)(`div`,{className:`grid grid-cols-2 gap-2 text-xs`,children:[(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`div`,{className:`text-[10px] text-trash-gray font-semibold`,children:`Current State`}),(0,S.jsx)(`div`,{className:`font-arcade text-base font-bold text-sky-700`,children:Y.is_enrolled?(Y.fsrs_state??0)===0?`New (0)`:(Y.fsrs_state??0)===1?`Learning (1)`:(Y.fsrs_state??0)===2?`Review (2)`:`Relearning (3)`:`Unenrolled`})]}),(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`div`,{className:`text-[10px] text-trash-gray font-semibold`,children:`Status`}),(0,S.jsx)(`div`,{className:`font-arcade text-xs font-bold text-emerald-700`,children:Y.is_due?`Due Today`:Y.is_enrolled?`Scheduled`:`Catalog New`})]}),(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`div`,{className:`text-[10px] text-trash-gray font-semibold`,children:`Stability`}),(0,S.jsx)(`div`,{className:`font-mono text-sm font-bold text-slate-800`,children:Y.fsrs_stability===void 0?`0.0d`:`${Y.fsrs_stability.toFixed(1)}d`})]}),(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`div`,{className:`text-[10px] text-trash-gray font-semibold`,children:`Difficulty`}),(0,S.jsx)(`div`,{className:`font-mono text-sm font-bold text-amber-700`,children:Y.fsrs_difficulty===void 0?`0.0/10`:`${Y.fsrs_difficulty.toFixed(1)}/10`})]}),(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`div`,{className:`text-[10px] text-trash-gray font-semibold`,children:`Total Attempts`}),(0,S.jsx)(`div`,{className:`font-mono text-sm font-bold text-slate-800`,children:Y.total_attempts})]}),(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`div`,{className:`text-[10px] text-trash-gray font-semibold`,children:`Times Correct`}),(0,S.jsx)(`div`,{className:`font-mono text-sm font-bold text-emerald-600`,children:Y.times_correct})]}),(0,S.jsxs)(`div`,{className:`col-span-2 pt-1 border-t border-slate-200`,children:[(0,S.jsx)(`div`,{className:`text-[10px] text-trash-gray font-semibold`,children:`Retention Success Rate`}),(0,S.jsxs)(`div`,{className:`flex items-center gap-2 mt-1`,children:[(0,S.jsx)(`div`,{className:`flex-1 h-3 bg-slate-200 rounded-full overflow-hidden border border-slate-300`,children:(0,S.jsx)(`div`,{className:`h-full bg-emerald-500 rounded-full`,style:{width:`${Y.total_attempts>0?Math.round(Y.times_correct/Y.total_attempts*100):0}%`}})}),(0,S.jsx)(`span`,{className:`font-mono text-xs font-bold text-slate-800`,children:Y.total_attempts>0?`${Math.round(Y.times_correct/Y.total_attempts*100)}%`:`0%`})]})]})]})]}),(0,S.jsxs)(`div`,{className:`p-3 bg-white border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] space-y-1.5 text-xs`,children:[(0,S.jsx)(`span`,{className:`font-arcade text-[9px] font-bold text-ink-black uppercase block border-b pb-1`,children:`TIMESTAMPS`}),(0,S.jsxs)(`div`,{className:`flex items-center justify-between text-slate-700`,children:[(0,S.jsx)(`span`,{className:`text-[11px] font-semibold`,children:`Next Review:`}),(0,S.jsx)(`span`,{className:`font-mono text-[10px]`,children:Y.next_review?new Date(Y.next_review).toLocaleString():`Not scheduled`})]}),(0,S.jsxs)(`div`,{className:`flex items-center justify-between text-slate-700`,children:[(0,S.jsx)(`span`,{className:`text-[11px] font-semibold`,children:`Last Reviewed:`}),(0,S.jsx)(`span`,{className:`font-mono text-[10px]`,children:Y.last_reviewed?new Date(Y.last_reviewed).toLocaleString():`Never`})]})]})]})]})]}):(0,S.jsx)(`div`,{className:`flex-1 flex items-center justify-center p-6 text-center text-trash-gray font-mono text-xs`,children:`Select a card to view its Front, Back, and SRS details.`})})]})]})}export{C as default};1import{r as e}from"./rolldown-runtime-hePW80VL.js";import{$ as t,A as n,Bt as r,Dt as i,Ht as a,M as o,P as s,St as c,T as l,X as u,a as ee,b as te,h as ne,mt as re,ot as ie,p as d,q as ae,v as f,x as oe,y as se}from"./vendor-react-hnaVBnLv.js";import{s as p}from"./firebaseClient-DZobvwSx.js";import{i as ce,l as m}from"./index-Q9onQHft.js";var h=e(a(),1);async function g(){try{let{data:{session:e}}=await p.auth.getSession();return e?e.access_token:`sandbox`}catch{return`sandbox`}}function _(e){return e.toLowerCase().replace(/\s*-\s*method.*$/i,``).replace(/[^a-z0-9]+/g,``)}function v(e){if(typeof e==`string`)try{return JSON.parse(e)}catch{return}return e??void 0}async function le(){let e=await g(),t=ce(),n=[];try{let t=await fetch(`/api/explorer/problems`,{headers:{Authorization:`Bearer ${e}`}});t.ok&&(n=await t.json())}catch{n=[]}let r=new Map,i=new Map,a=new Set;for(let e of n)e.problem_number!==void 0&&e.problem_number!==null&&r.set(e.problem_number,e),i.set(_(e.name),e);let o=new Date,s=[];for(let e of t){let t=r.get(e.problem_number)||i.get(_(e.name));if(t){a.add(t.id);let n=t.next_review!==null&&t.next_review!==void 0||t.fsrs_state!==null&&t.fsrs_state!==void 0,r=t.next_review?new Date(t.next_review):null,i=n&&r!==null?r<=o:!1,c=v(t.solutions),l=v(t.examples),u=v(t.constraints);s.push({id:t.id,problem_number:e.problem_number,name:e.name,pattern:e.pattern,difficulty:e.difficulty,description:t.description||e.description,reference_code:t.reference_code||e.reference_solution,starter_code:t.starter_code||e.starter_code,optimal_time:t.optimal_time||e.time_complexity,optimal_space:t.optimal_space||e.space_complexity,how_to_solve:t.how_to_solve||``,examples:l&&(!Array.isArray(l)||l.length>0)?l:e.examples,constraints:u&&(!Array.isArray(u)||u.length>0)?u:e.constraints,solutions:c,leetcode_url:e.leetcode_url,is_enrolled:n,is_custom:!1,fsrs_state:t.fsrs_state??(n?0:null),fsrs_step:t.fsrs_step??0,fsrs_stability:t.fsrs_stability??0,fsrs_difficulty:t.fsrs_difficulty??0,fsrs_elapsed_days:t.fsrs_elapsed_days??0,fsrs_scheduled_days:t.fsrs_scheduled_days??0,fsrs_reps:t.fsrs_reps??0,fsrs_lapses:t.fsrs_lapses??0,next_review:t.next_review??null,last_reviewed:t.last_reviewed??null,times_correct:t.times_correct??0,total_attempts:t.total_attempts??0,is_due:i,catalogProblem:e})}else s.push({id:e.id,problem_number:e.problem_number,name:e.name,pattern:e.pattern,difficulty:e.difficulty,description:e.description,reference_code:e.reference_solution,starter_code:e.starter_code,optimal_time:e.time_complexity,optimal_space:e.space_complexity,how_to_solve:``,examples:e.examples,constraints:e.constraints,leetcode_url:e.leetcode_url,is_enrolled:!1,is_custom:!1,fsrs_state:null,fsrs_step:0,fsrs_stability:0,fsrs_difficulty:0,fsrs_elapsed_days:0,fsrs_scheduled_days:0,fsrs_reps:0,fsrs_lapses:0,next_review:null,last_reviewed:null,times_correct:0,total_attempts:0,is_due:!1,catalogProblem:e})}for(let e of n)if(!a.has(e.id)){let t=e.next_review!==null&&e.next_review!==void 0||e.fsrs_state!==null&&e.fsrs_state!==void 0,n=e.next_review?new Date(e.next_review):null,r=t&&n!==null?n<=o:!1,i=v(e.solutions),a=v(e.examples)||[],c=v(e.constraints)||[];s.push({id:e.id,problem_number:e.problem_number,name:e.name,pattern:e.pattern||`General`,difficulty:e.difficulty||`Medium`,description:e.description||``,reference_code:e.reference_code||``,starter_code:e.starter_code||``,optimal_time:e.optimal_time||`O(N)`,optimal_space:e.optimal_space||`O(1)`,how_to_solve:e.how_to_solve||``,examples:a,constraints:c,solutions:i,is_enrolled:t,is_custom:!0,fsrs_state:e.fsrs_state??(t?0:null),fsrs_step:e.fsrs_step??0,fsrs_stability:e.fsrs_stability??0,fsrs_difficulty:e.fsrs_difficulty??0,fsrs_elapsed_days:e.fsrs_elapsed_days??0,fsrs_scheduled_days:e.fsrs_scheduled_days??0,fsrs_reps:e.fsrs_reps??0,fsrs_lapses:e.fsrs_lapses??0,next_review:e.next_review??null,last_reviewed:e.last_reviewed??null,times_correct:e.times_correct??0,total_attempts:e.total_attempts??0,is_due:r})}return s}async function y(e){if(e.length===0)return!0;let t=await g(),n=await fetch(`/api/reviews/reset`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${t}`},body:JSON.stringify({problem_ids:e})});if(!n.ok){let e=await n.json().catch(()=>({detail:`Failed to reset reviews`}));throw Error(e.detail||`Failed to reset reviews`)}return!0}async function b(e){let t=await g(),n=await fetch(`/api/explorer/problems/${e}`,{method:`DELETE`,headers:{Authorization:`Bearer ${t}`}});if(!n.ok){let e=await n.json().catch(()=>({detail:`Failed to delete problem`}));throw Error(e.detail||`Failed to delete problem`)}return!0}async function ue(e){let t=0;for(let n of e)try{await b(n),t++}catch{}return t}async function x(e){return e.length===0?0:(await m(e)).enrolled_count}var S=r();function C({onOpenQueue:e,onOpenCreateProblem:r,onOpenEditProblem:a,onSelectProblemForReview:p,refreshTrigger:ce,onRefreshExplorer:m}){let[g,_]=(0,h.useState)([]),[v,C]=(0,h.useState)(!0),[de,w]=(0,h.useState)(null),[T,fe]=(0,h.useState)(``),[E,D]=(0,h.useState)(`all`),[O,pe]=(0,h.useState)(`ALL`),[k,me]=(0,h.useState)(`ALL`),[A,he]=(0,h.useState)(`number`),[j,M]=(0,h.useState)(`asc`),[N,P]=(0,h.useState)(new Set),[F,I]=(0,h.useState)(null),[L,R]=(0,h.useState)(`front`),[z,B]=(0,h.useState)(!1),[V,H]=(0,h.useState)(!1),[ge,U]=(0,h.useState)(null),[W,G]=(0,h.useState)(`table`),K=(0,h.useCallback)(async()=>{C(!0),w(null);try{let e=await le();_(e),e.length>0&&!F&&I(e[0].id)}catch(e){let t=e instanceof Error?e.message:`Failed to load card database`;w(t)}finally{C(!1)}},[F]);(0,h.useEffect)(()=>{K()},[K,ce]);let q=(0,h.useMemo)(()=>{let e=0,t=0,n=0,r=0,i=0,a=0;for(let o of g)if(o.is_enrolled){t++,o.is_due&&e++;let n=o.fsrs_state??0;n===1?r++:n===2?i++:n===3&&a++}else n++;return{total:g.length,due:e,enrolled:t,newCards:n,learning:r,reviewing:i,relearning:a}},[g]),_e=(0,h.useMemo)(()=>{let e=new Map;for(let t of g)e.set(t.pattern,(e.get(t.pattern)||0)+1);let t=Array.from(e.entries()).map(([e,t])=>({pattern:e,count:t}));return t.sort((e,t)=>e.pattern.localeCompare(t.pattern)),t},[g]),ve=(0,h.useMemo)(()=>{let e=T.trim().toLowerCase();return g.filter(t=>{if(E===`due`&&!t.is_due||E===`enrolled`&&!t.is_enrolled||E===`new`&&t.is_enrolled||E===`learning`&&(!t.is_enrolled||t.fsrs_state!==1)||E===`reviewing`&&(!t.is_enrolled||t.fsrs_state!==2)||E===`relearning`&&(!t.is_enrolled||t.fsrs_state!==3)||O!==`ALL`&&t.pattern!==O||k!==`ALL`&&t.difficulty!==k)return!1;if(e){let n=t.problem_number?String(t.problem_number).includes(e):!1,r=t.name.toLowerCase().includes(e),i=t.pattern.toLowerCase().includes(e),a=t.difficulty.toLowerCase().includes(e);if(!n&&!r&&!i&&!a)return!1}return!0})},[g,E,O,k,T]),J=(0,h.useMemo)(()=>{let e=[...ve];return e.sort((e,t)=>{let n=0;switch(A){case`number`:n=(e.problem_number??999999)-(t.problem_number??999999);break;case`name`:n=e.name.localeCompare(t.name);break;case`pattern`:n=e.pattern.localeCompare(t.pattern);break;case`difficulty`:{let r={Easy:1,Medium:2,Hard:3};n=(r[e.difficulty]||2)-(r[t.difficulty]||2);break}case`state`:n=(e.fsrs_state??-1)-(t.fsrs_state??-1);break;case`due`:n=(e.next_review?new Date(e.next_review).getTime():9999999999999)-(t.next_review?new Date(t.next_review).getTime():9999999999999);break;case`retention`:n=(e.total_attempts>0?e.times_correct/e.total_attempts:0)-(t.total_attempts>0?t.times_correct/t.total_attempts:0)}return j===`asc`?n:-n}),e},[ve,A,j]),Y=(0,h.useMemo)(()=>!F&&J.length>0?J[0]:g.find(e=>e.id===F)||J[0]||null,[g,F,J]),X=e=>{A===e?M(e=>e===`asc`?`desc`:`asc`):(he(e),M(`asc`))},ye=(e,t)=>{t.stopPropagation(),P(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},be=(0,h.useMemo)(()=>J.length>0&&J.every(e=>N.has(e.id)),[J,N]),xe=()=>{P(e=>{let t=new Set(e);if(be)for(let e of J)t.delete(e.id);else for(let e of J)t.add(e.id);return t})},Z=(0,h.useMemo)(()=>g.filter(e=>N.has(e.id)&&e.is_custom),[g,N]),Se=async()=>{if(Z.length!==0&&confirm(`Are you sure you want to delete ${Z.length} custom cards?`)){H(!0);try{let e=await ue(Z.map(e=>e.id));U(`Deleted ${e} custom cards.`),P(e=>{let t=new Set(e);for(let e of Z)t.delete(e.id);return t}),await K(),m?.()}catch(e){let t=e instanceof Error?e.message:`Batch delete failed`;w(t)}finally{H(!1),setTimeout(()=>U(null),3500)}}},Ce=async()=>{let e=g.filter(e=>N.has(e.id)&&!e.is_enrolled&&e.catalogProblem);if(e.length===0){U(`No unenrolled catalog cards in current selection.`),setTimeout(()=>U(null),3e3);return}H(!0);try{let t=await x(e.map(e=>e.catalogProblem));U(`Enrolled ${t} cards into Daily Queue!`),P(new Set),await K(),m?.()}catch(e){let t=e instanceof Error?e.message:`Enrollment failed`;w(t)}finally{H(!1),setTimeout(()=>U(null),3500)}},we=async()=>{let e=g.filter(e=>N.has(e.id)&&e.is_enrolled);if(e.length===0){U(`No active cards in selection to reset.`),setTimeout(()=>U(null),3e3);return}H(!0);try{await y(e.map(e=>e.id)),U(`Reset ${e.length} cards to initial FSRS state due today!`),P(new Set),await K(),m?.()}catch(e){let t=e instanceof Error?e.message:`Reset failed`;w(t)}finally{H(!1),setTimeout(()=>U(null),3500)}},Te=async e=>{H(!0);try{await y([e.id]),U(`Reset #${e.problem_number??`—`} ${e.name} for FSRS!`),await K(),m?.()}catch(e){let t=e instanceof Error?e.message:`Reset failed`;w(t)}finally{H(!1),setTimeout(()=>U(null),3500)}},Ee=async e=>{if(e.catalogProblem){H(!0);try{await x([e.catalogProblem]),U(`Enrolled #${e.problem_number??`—`} ${e.name} into review queue!`),await K(),m?.()}catch(e){let t=e instanceof Error?e.message:`Enrollment failed`;w(t)}finally{H(!1),setTimeout(()=>U(null),3500)}}},De=async e=>{if(confirm(`Are you sure you want to delete custom card "${e.name}"?`)){H(!0);try{await b(e.id),U(`Deleted custom card "${e.name}"`),await K(),m?.()}catch(e){let t=e instanceof Error?e.message:`Delete failed`;w(t)}finally{H(!1),setTimeout(()=>U(null),3500)}}},Q=(0,h.useCallback)(t=>{p(t.id),e()},[p,e]),$=e=>{a({id:e.id,name:e.name,problem_number:e.problem_number,pattern:e.pattern,difficulty:e.difficulty,description:e.description,examples:e.examples,constraints:e.constraints,optimal_time:e.optimal_time,optimal_space:e.optimal_space,starter_code:e.starter_code,reference_code:e.reference_code,how_to_solve:e.how_to_solve,solutions:e.solutions})},Oe=()=>{Y?.reference_code&&(navigator.clipboard.writeText(Y.reference_code),B(!0),setTimeout(()=>B(!1),2e3))},ke=(e,t,n)=>{if(!n)return`Not enrolled`;if(!e)return`Due now`;if(t)return`Due today`;let r=new Date(e),i=new Date,a=Math.ceil((r.getTime()-i.getTime())/864e5);return a<=1?`Tomorrow`:`In ${a}d`};return(0,h.useEffect)(()=>{let e=e=>{let t=e.target;if(t.tagName===`INPUT`||t.tagName===`TEXTAREA`||t.tagName===`SELECT`||t.isContentEditable||J.length===0)return;let n=J.findIndex(e=>e.id===Y?.id);if(e.key===`ArrowDown`){e.preventDefault();let t=n<J.length-1?n+1:0;I(J[t].id)}else if(e.key===`ArrowUp`){e.preventDefault();let t=n>0?n-1:J.length-1;I(J[t].id)}else e.key===` `||e.code===`Space`?(e.preventDefault(),R(e=>e===`front`?`back`:`front`)):e.key===`Enter`&&Y?.is_enrolled&&(e.preventDefault(),Q(Y))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[J,Y,Q]),(0,S.jsxs)(`div`,{className:`w-full h-full flex flex-col bg-[#fdf8e1] font-sans text-ink-black select-none overflow-hidden`,children:[(0,S.jsxs)(`div`,{className:`bg-slate-900 text-white border-b-[3px] border-ink-black px-4 py-2.5 flex flex-wrap items-center justify-between gap-3 shrink-0`,children:[(0,S.jsxs)(`div`,{className:`flex items-center gap-2.5`,children:[(0,S.jsx)(`div`,{className:`w-8 h-8 rounded bg-sky-500 border-2 border-white flex items-center justify-center shadow-[2px_2px_0px_0px_rgba(0,0,0,0.5)]`,children:(0,S.jsx)(ae,{className:`w-5 h-5 text-white stroke-[2.5]`})}),(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`h1`,{className:`font-arcade text-xs sm:text-sm font-bold tracking-wider text-amber-300 uppercase flex items-center gap-1.5`,children:`MANAGE FSRS`}),(0,S.jsx)(`p`,{className:`text-[10px] text-slate-300 font-mono`,children:`Browse, filter, and reschedule spaced-repetition cards`})]})]}),(0,S.jsxs)(`div`,{className:`flex items-center gap-1.5 sm:gap-2 flex-wrap text-[10px] font-mono`,children:[(0,S.jsxs)(`button`,{onClick:()=>D(`all`),className:`px-2 py-0.5 border border-slate-700 rounded transition-colors cursor-pointer ${E===`all`?`bg-sky-500 text-white font-bold`:`bg-slate-800 text-slate-300 hover:bg-slate-700`}`,children:[`Total: `,(0,S.jsx)(`span`,{className:`font-bold`,children:q.total})]}),(0,S.jsxs)(`button`,{onClick:()=>D(`due`),className:`px-2 py-0.5 border border-slate-700 rounded transition-colors cursor-pointer ${E===`due`?`bg-rose-500 text-white font-bold`:`bg-slate-800 text-rose-300 hover:bg-slate-700`}`,children:[`Due Today: `,(0,S.jsx)(`span`,{className:`font-bold`,children:q.due})]}),(0,S.jsxs)(`button`,{onClick:()=>D(`enrolled`),className:`px-2 py-0.5 border border-slate-700 rounded transition-colors cursor-pointer ${E===`enrolled`?`bg-emerald-600 text-white font-bold`:`bg-slate-800 text-emerald-300 hover:bg-slate-700`}`,children:[`In Review: `,(0,S.jsx)(`span`,{className:`font-bold`,children:q.enrolled})]}),(0,S.jsxs)(`button`,{onClick:()=>D(`learning`),className:`px-2 py-0.5 border border-slate-700 rounded transition-colors cursor-pointer ${E===`learning`?`bg-amber-500 text-slate-900 font-bold`:`bg-slate-800 text-amber-300 hover:bg-slate-700`}`,children:[`Learning: `,(0,S.jsx)(`span`,{className:`font-bold`,children:q.learning})]}),(0,S.jsxs)(`button`,{onClick:()=>D(`reviewing`),className:`px-2 py-0.5 border border-slate-700 rounded transition-colors cursor-pointer ${E===`reviewing`?`bg-emerald-600 text-white font-bold`:`bg-slate-800 text-emerald-300 hover:bg-slate-700`}`,children:[`Review: `,(0,S.jsx)(`span`,{className:`font-bold`,children:q.reviewing})]}),(0,S.jsxs)(`button`,{onClick:()=>D(`relearning`),className:`px-2 py-0.5 border border-slate-700 rounded transition-colors cursor-pointer ${E===`relearning`?`bg-rose-600 text-white font-bold`:`bg-slate-800 text-rose-300 hover:bg-slate-700`}`,children:[`Relearning: `,(0,S.jsx)(`span`,{className:`font-bold`,children:q.relearning})]}),(0,S.jsxs)(`button`,{onClick:()=>D(`new`),className:`px-2 py-0.5 border border-slate-700 rounded transition-colors cursor-pointer ${E===`new`?`bg-indigo-600 text-white font-bold`:`bg-slate-800 text-indigo-300 hover:bg-slate-700`}`,children:[`Unenrolled: `,(0,S.jsx)(`span`,{className:`font-bold`,children:q.newCards})]})]}),(0,S.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,S.jsxs)(`button`,{onClick:r,className:`px-2.5 py-1 bg-grass-green hover:bg-emerald-400 text-ink-black border-2 border-white rounded font-arcade text-[9px] font-bold shadow-[2px_2px_0px_0px_rgba(0,0,0,0.5)] active:translate-y-0.5 cursor-pointer flex items-center gap-1`,children:[(0,S.jsx)(re,{className:`w-3.5 h-3.5`}),(0,S.jsx)(`span`,{children:`ADD CARD`})]}),(0,S.jsx)(`button`,{onClick:K,disabled:v,className:`p-1 bg-slate-800 hover:bg-slate-700 text-slate-200 border border-slate-600 rounded cursor-pointer disabled:opacity-50`,title:`Refresh Deck`,children:(0,S.jsx)(o,{className:`w-3.5 h-3.5 ${v?`animate-spin`:``}`})})]})]}),ge&&(0,S.jsxs)(`div`,{className:`bg-amber-300 border-b-2 border-ink-black px-4 py-1.5 text-xs font-bold text-ink-black flex items-center justify-between shrink-0`,children:[(0,S.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,S.jsx)(oe,{className:`w-4 h-4 text-amber-800`}),(0,S.jsx)(`span`,{children:ge})]}),(0,S.jsx)(`button`,{onClick:()=>U(null),className:`text-xs hover:opacity-75 cursor-pointer`,children:`✕`})]}),de&&(0,S.jsxs)(`div`,{className:`bg-rose-100 border-b-2 border-rose-400 px-4 py-1.5 text-xs font-semibold text-rose-800 flex items-center justify-between shrink-0`,children:[(0,S.jsx)(`span`,{children:de}),(0,S.jsx)(`button`,{onClick:()=>w(null),className:`text-xs hover:opacity-75 cursor-pointer`,children:`✕`})]}),(0,S.jsxs)(`div`,{className:`sm:hidden flex border-b-2 border-ink-black bg-white shrink-0`,children:[(0,S.jsxs)(`button`,{onClick:()=>G(`table`),className:`flex-1 py-2 font-arcade text-[10px] font-bold text-center border-r border-ink-black ${W===`table`?`bg-amber-300 text-ink-black`:`text-slate-600`}`,children:[`CARDS LIST (`,J.length,`)`]}),(0,S.jsxs)(`button`,{onClick:()=>G(`inspector`),className:`flex-1 py-2 font-arcade text-[10px] font-bold text-center ${W===`inspector`?`bg-amber-300 text-ink-black`:`text-slate-600`}`,children:[`INSPECTOR `,Y?`#${Y.problem_number??``}`:``]})]}),(0,S.jsxs)(`div`,{className:`flex-1 flex overflow-hidden`,children:[(0,S.jsxs)(`aside`,{className:`w-56 bg-[#f7f0cf] border-r-[3px] border-ink-black flex flex-col shrink-0 overflow-y-auto custom-scrollbar hidden md:flex`,children:[(0,S.jsx)(`div`,{className:`p-3 border-b-2 border-ink-black/20`,children:(0,S.jsxs)(`span`,{className:`font-arcade text-[9px] font-bold text-ink-black uppercase tracking-wider flex items-center gap-1.5`,children:[(0,S.jsx)(t,{className:`w-3.5 h-3.5 text-amber-700`}),` DECKS & STATES`]})}),(0,S.jsxs)(`div`,{className:`p-2 space-y-1 text-xs`,children:[(0,S.jsxs)(`button`,{onClick:()=>D(`all`),className:`w-full text-left px-2.5 py-1.5 rounded flex items-center justify-between cursor-pointer transition-colors ${E===`all`?`bg-ink-black text-amber-300 font-bold`:`hover:bg-amber-200/60 text-ink-black font-semibold`}`,children:[(0,S.jsx)(`span`,{children:`📁 All Cards`}),(0,S.jsx)(`span`,{className:`font-mono text-[10px] opacity-80`,children:q.total})]}),(0,S.jsxs)(`button`,{onClick:()=>D(`due`),className:`w-full text-left px-2.5 py-1.5 rounded flex items-center justify-between cursor-pointer transition-colors ${E===`due`?`bg-ink-black text-rose-300 font-bold`:`hover:bg-amber-200/60 text-rose-900 font-semibold`}`,children:[(0,S.jsx)(`span`,{className:`flex items-center gap-1`,children:`⏰ Due Today`}),(0,S.jsx)(`span`,{className:`font-mono text-[10px] font-bold text-rose-600`,children:q.due})]}),(0,S.jsxs)(`button`,{onClick:()=>D(`enrolled`),className:`w-full text-left px-2.5 py-1.5 rounded flex items-center justify-between cursor-pointer transition-colors ${E===`enrolled`?`bg-ink-black text-emerald-300 font-bold`:`hover:bg-amber-200/60 text-ink-black font-semibold`}`,children:[(0,S.jsx)(`span`,{children:`📥 In Review`}),(0,S.jsx)(`span`,{className:`font-mono text-[10px] opacity-80`,children:q.enrolled})]}),(0,S.jsxs)(`button`,{onClick:()=>D(`new`),className:`w-full text-left px-2.5 py-1.5 rounded flex items-center justify-between cursor-pointer transition-colors ${E===`new`?`bg-ink-black text-sky-300 font-bold`:`hover:bg-amber-200/60 text-ink-black font-semibold`}`,children:[(0,S.jsx)(`span`,{children:`🆕 Unenrolled (Catalog)`}),(0,S.jsx)(`span`,{className:`font-mono text-[10px] opacity-80`,children:q.newCards})]}),(0,S.jsxs)(`button`,{onClick:()=>D(`learning`),className:`w-full text-left px-2.5 py-1.5 rounded flex items-center justify-between cursor-pointer transition-colors ${E===`learning`?`bg-ink-black text-amber-300 font-bold`:`hover:bg-amber-200/60 text-ink-black font-semibold`}`,children:[(0,S.jsx)(`span`,{children:`🔄 Learning (State 1)`}),(0,S.jsx)(`span`,{className:`font-mono text-[10px] opacity-80`,children:q.learning})]}),(0,S.jsxs)(`button`,{onClick:()=>D(`reviewing`),className:`w-full text-left px-2.5 py-1.5 rounded flex items-center justify-between cursor-pointer transition-colors ${E===`reviewing`?`bg-ink-black text-emerald-300 font-bold`:`hover:bg-amber-200/60 text-ink-black font-semibold`}`,children:[(0,S.jsx)(`span`,{children:`📈 Review (State 2)`}),(0,S.jsx)(`span`,{className:`font-mono text-[10px] opacity-80`,children:q.reviewing})]}),(0,S.jsxs)(`button`,{onClick:()=>D(`relearning`),className:`w-full text-left px-2.5 py-1.5 rounded flex items-center justify-between cursor-pointer transition-colors ${E===`relearning`?`bg-ink-black text-rose-300 font-bold`:`hover:bg-amber-200/60 text-ink-black font-semibold`}`,children:[(0,S.jsx)(`span`,{children:`🔁 Relearning (State 3)`}),(0,S.jsx)(`span`,{className:`font-mono text-[10px] opacity-80`,children:q.relearning})]})]}),(0,S.jsx)(`div`,{className:`p-3 border-t-2 border-ink-black/20`,children:(0,S.jsxs)(`span`,{className:`font-arcade text-[9px] font-bold text-ink-black uppercase tracking-wider flex items-center gap-1.5`,children:[(0,S.jsx)(ne,{className:`w-3.5 h-3.5 text-purple-700`}),` PATTERNS (TAGS)`]})}),(0,S.jsxs)(`div`,{className:`p-2 space-y-0.5 text-xs flex-1`,children:[(0,S.jsxs)(`button`,{onClick:()=>pe(`ALL`),className:`w-full text-left px-2.5 py-1 rounded flex items-center justify-between cursor-pointer transition-colors ${O===`ALL`?`bg-purple-900 text-white font-bold`:`hover:bg-purple-100 text-ink-black font-semibold`}`,children:[(0,S.jsx)(`span`,{children:`All Patterns`}),(0,S.jsx)(`span`,{className:`font-mono text-[10px] opacity-80`,children:g.length})]}),_e.map(({pattern:e,count:t})=>(0,S.jsxs)(`button`,{onClick:()=>pe(e),className:`w-full text-left px-2.5 py-1 rounded flex items-center justify-between cursor-pointer transition-colors text-[11px] ${O===e?`bg-purple-900 text-white font-bold`:`hover:bg-purple-100 text-ink-black`}`,children:[(0,S.jsx)(`span`,{className:`truncate`,children:e}),(0,S.jsx)(`span`,{className:`font-mono text-[10px] opacity-80 shrink-0 ml-1`,children:t})]},e))]})]}),(0,S.jsxs)(`div`,{className:`flex-1 flex flex-col min-w-0 bg-white border-r-[3px] border-ink-black ${W===`inspector`?`hidden sm:flex`:`flex`}`,children:[(0,S.jsxs)(`div`,{className:`p-3 bg-[#fdf8e1] border-b-2 border-ink-black flex flex-wrap items-center justify-between gap-2 shrink-0`,children:[(0,S.jsxs)(`div`,{className:`relative flex-1 min-w-[200px]`,children:[(0,S.jsx)(l,{className:`w-4 h-4 absolute left-2.5 top-2.5 text-slate-500`}),(0,S.jsx)(`input`,{type:`text`,value:T,onChange:e=>fe(e.target.value),placeholder:`Search by card #, title, pattern, or keyword...`,className:`w-full pl-8 pr-3 py-1.5 bg-white border-2 border-ink-black text-xs font-semibold focus:outline-none focus:ring-2 focus:ring-sky-500 shadow-[2px_2px_0px_0px_rgba(30,41,59,1)]`}),T&&(0,S.jsx)(`button`,{onClick:()=>fe(``),className:`absolute right-2.5 top-2 text-slate-400 hover:text-ink-black text-xs cursor-pointer`,children:`✕`})]}),(0,S.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,S.jsxs)(`select`,{"aria-label":`Filter cards by difficulty`,value:k,onChange:e=>me(e.target.value),className:`px-2.5 py-1.5 bg-white border-2 border-ink-black text-xs font-bold shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] cursor-pointer`,children:[(0,S.jsx)(`option`,{value:`ALL`,children:`All Difficulties`}),(0,S.jsx)(`option`,{value:`Easy`,children:`Easy`}),(0,S.jsx)(`option`,{value:`Medium`,children:`Medium`}),(0,S.jsx)(`option`,{value:`Hard`,children:`Hard`})]}),(0,S.jsxs)(`span`,{className:`text-[11px] font-mono text-slate-600 font-semibold hidden lg:inline`,children:[J.length,` matching cards`]})]})]}),N.size>0&&(0,S.jsxs)(`div`,{className:`bg-sky-100 border-b-2 border-ink-black px-3 py-2 flex items-center justify-between gap-2 shrink-0 animate-in fade-in flex-wrap`,children:[(0,S.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,S.jsxs)(`span`,{className:`font-arcade text-[10px] font-bold text-sky-900 uppercase`,children:[N.size,` SELECTED`,Z.length>0&&` (${Z.length} custom)`]}),(0,S.jsx)(`button`,{onClick:()=>P(new Set),className:`text-xs text-sky-800 underline hover:text-sky-950 cursor-pointer`,children:`Clear`})]}),(0,S.jsxs)(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[(0,S.jsxs)(`button`,{onClick:Ce,disabled:V,className:`px-3 py-1 bg-grass-green hover:bg-emerald-400 text-ink-black font-arcade text-[9px] font-bold border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 cursor-pointer flex items-center gap-1 disabled:opacity-50`,children:[(0,S.jsx)(ee,{className:`w-3.5 h-3.5 text-amber-900`}),(0,S.jsx)(`span`,{children:`ADD TO QUEUE`})]}),(0,S.jsxs)(`button`,{onClick:we,disabled:V,className:`px-3 py-1 bg-amber-300 hover:bg-amber-400 text-ink-black font-arcade text-[9px] font-bold border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 cursor-pointer flex items-center gap-1 disabled:opacity-50`,children:[(0,S.jsx)(n,{className:`w-3.5 h-3.5`}),(0,S.jsx)(`span`,{children:`RESET PROGRESS`})]}),Z.length>0&&(0,S.jsxs)(`button`,{onClick:Se,disabled:V,className:`px-3 py-1 bg-rose-200 hover:bg-rose-300 text-rose-950 font-arcade text-[9px] font-bold border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 cursor-pointer flex items-center gap-1 disabled:opacity-50`,children:[(0,S.jsx)(d,{className:`w-3.5 h-3.5 text-rose-700`}),(0,S.jsxs)(`span`,{children:[`DELETE CUSTOM (`,Z.length,`)`]})]})]})]}),(0,S.jsx)(`div`,{className:`flex-1 overflow-y-auto custom-scrollbar`,children:(0,S.jsxs)(`table`,{className:`w-full text-left border-collapse text-xs`,children:[(0,S.jsx)(`thead`,{className:`sticky top-0 bg-[#f4ebd0] border-b-2 border-ink-black font-arcade text-[9px] font-bold text-ink-black z-10 select-none`,children:(0,S.jsxs)(`tr`,{children:[(0,S.jsx)(`th`,{className:`p-2 w-8 text-center border-r border-ink-black/20`,children:(0,S.jsx)(`button`,{onClick:xe,className:`cursor-pointer flex items-center justify-center mx-auto text-ink-black`,title:`Select all matching cards`,children:be?(0,S.jsx)(te,{className:`w-4 h-4 text-sky-700`}):(0,S.jsx)(f,{className:`w-4 h-4`})})}),(0,S.jsx)(`th`,{onClick:()=>X(`number`),className:`p-2 w-16 cursor-pointer hover:bg-amber-200/50 border-r border-ink-black/20`,children:(0,S.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,S.jsx)(`span`,{children:`#`}),(0,S.jsx)(i,{className:`w-3 h-3 opacity-60`})]})}),(0,S.jsx)(`th`,{onClick:()=>X(`name`),className:`p-2 cursor-pointer hover:bg-amber-200/50 border-r border-ink-black/20`,children:(0,S.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,S.jsx)(`span`,{children:`CARD TITLE`}),(0,S.jsx)(i,{className:`w-3 h-3 opacity-60`})]})}),(0,S.jsx)(`th`,{onClick:()=>X(`pattern`),className:`p-2 hidden md:table-cell cursor-pointer hover:bg-amber-200/50 border-r border-ink-black/20`,children:(0,S.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,S.jsx)(`span`,{children:`DECK / PATTERN`}),(0,S.jsx)(i,{className:`w-3 h-3 opacity-60`})]})}),(0,S.jsx)(`th`,{onClick:()=>X(`difficulty`),className:`p-2 w-20 cursor-pointer hover:bg-amber-200/50 border-r border-ink-black/20`,children:(0,S.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,S.jsx)(`span`,{children:`DIFF`}),(0,S.jsx)(i,{className:`w-3 h-3 opacity-60`})]})}),(0,S.jsx)(`th`,{onClick:()=>X(`state`),className:`p-2 w-24 cursor-pointer hover:bg-amber-200/50 border-r border-ink-black/20`,children:(0,S.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,S.jsx)(`span`,{children:`FSRS STATE`}),(0,S.jsx)(i,{className:`w-3 h-3 opacity-60`})]})}),(0,S.jsx)(`th`,{onClick:()=>X(`due`),className:`p-2 w-24 cursor-pointer hover:bg-amber-200/50 border-r border-ink-black/20`,children:(0,S.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,S.jsx)(`span`,{children:`DUE`}),(0,S.jsx)(i,{className:`w-3 h-3 opacity-60`})]})}),(0,S.jsx)(`th`,{onClick:()=>X(`retention`),className:`p-2 w-20 hidden lg:table-cell cursor-pointer hover:bg-amber-200/50`,children:(0,S.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,S.jsx)(`span`,{children:`RETENTION`}),(0,S.jsx)(i,{className:`w-3 h-3 opacity-60`})]})})]})}),(0,S.jsx)(`tbody`,{className:`divide-y divide-slate-200`,children:J.length===0?(0,S.jsx)(`tr`,{children:(0,S.jsx)(`td`,{colSpan:8,className:`p-8 text-center text-trash-gray font-mono`,children:`No cards match current filter criteria.`})}):J.map(e=>{let t=N.has(e.id),n=Y?.id===e.id;return(0,S.jsxs)(`tr`,{onClick:()=>{I(e.id),G(`inspector`)},onDoubleClick:()=>{e.is_enrolled?Q(e):$(e)},className:`cursor-pointer transition-colors ${n?`bg-sky-100 font-semibold`:t?`bg-amber-50`:`hover:bg-slate-50`}`,children:[(0,S.jsx)(`td`,{className:`p-2 text-center`,onClick:t=>ye(e.id,t),children:t?(0,S.jsx)(te,{className:`w-4 h-4 text-sky-600 mx-auto`}):(0,S.jsx)(f,{className:`w-4 h-4 text-slate-400 mx-auto`})}),(0,S.jsx)(`td`,{className:`p-2 font-mono text-[11px] font-bold text-slate-700`,children:e.problem_number?`#${e.problem_number}`:`—`}),(0,S.jsx)(`td`,{className:`p-2`,children:(0,S.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,S.jsx)(`span`,{className:`font-semibold text-ink-black truncate`,children:e.name}),e.is_custom&&(0,S.jsx)(`span`,{className:`px-1.5 py-0.2 rounded bg-purple-100 text-purple-800 border border-purple-300 text-[8px] font-bold uppercase shrink-0`,children:`CUSTOM`})]})}),(0,S.jsx)(`td`,{className:`p-2 hidden md:table-cell text-slate-600 text-[11px] truncate`,children:e.pattern}),(0,S.jsx)(`td`,{className:`p-2`,children:(0,S.jsx)(`span`,{className:`px-1.5 py-0.5 rounded font-arcade text-[8px] font-bold uppercase text-white ${e.difficulty===`Easy`?`bg-emerald-600`:e.difficulty===`Medium`?`bg-amber-600`:`bg-rose-600`}`,children:e.difficulty})}),(0,S.jsx)(`td`,{className:`p-2`,children:e.is_enrolled?(0,S.jsxs)(`span`,{className:`inline-flex items-center gap-1 font-mono text-[10px] font-bold text-slate-800`,children:[(0,S.jsx)(`span`,{className:`w-2 h-2 rounded-full ${(e.fsrs_state??0)===2?`bg-emerald-500`:(e.fsrs_state??0)===1?`bg-amber-500`:(e.fsrs_state??0)===3?`bg-rose-500`:`bg-blue-500`}`}),(e.fsrs_state??0)===0?`New`:(e.fsrs_state??0)===1?`Learning`:(e.fsrs_state??0)===2?`Review`:`Relearning`]}):(0,S.jsx)(`span`,{className:`text-[10px] font-mono text-slate-400 uppercase font-semibold`,children:`Unenrolled`})}),(0,S.jsx)(`td`,{className:`p-2 font-mono text-[10px]`,children:(0,S.jsx)(`span`,{className:e.is_due?`text-rose-600 font-bold bg-rose-50 px-1 py-0.5 rounded border border-rose-200`:`text-slate-600`,children:ke(e.next_review,e.is_due,e.is_enrolled)})}),(0,S.jsx)(`td`,{className:`p-2 hidden lg:table-cell font-mono text-[10px] text-slate-600`,children:e.total_attempts>0?(0,S.jsxs)(`span`,{children:[e.times_correct,`/`,e.total_attempts,` `,(0,S.jsxs)(`span`,{className:`text-[9px] text-slate-400`,children:[`(`,Math.round(e.times_correct/e.total_attempts*100),`%)`]})]}):(0,S.jsx)(`span`,{className:`text-slate-400`,children:`—`})})]},e.id)})})]})})]}),(0,S.jsx)(`aside`,{className:`w-full sm:w-80 lg:w-96 bg-[#fdf8e1] flex flex-col shrink-0 overflow-hidden ${W===`table`?`hidden sm:flex`:`flex`}`,children:Y?(0,S.jsxs)(`div`,{className:`flex-1 flex flex-col h-full overflow-hidden`,children:[(0,S.jsxs)(`div`,{className:`p-4 bg-[#f8efcd] border-b-2 border-ink-black space-y-2 shrink-0`,children:[(0,S.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,S.jsxs)(`span`,{className:`font-arcade text-[9px] font-bold text-amber-900 uppercase flex items-center gap-1`,children:[(0,S.jsx)(u,{className:`w-3.5 h-3.5 text-amber-700`}),` CARD INSPECTOR`]}),(0,S.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,S.jsx)(`span`,{className:`px-1.5 py-0.5 rounded font-arcade text-[8px] font-bold uppercase text-white ${Y.difficulty===`Easy`?`bg-emerald-600`:Y.difficulty===`Medium`?`bg-amber-600`:`bg-rose-600`}`,children:Y.difficulty}),(0,S.jsx)(`span`,{className:`font-mono text-[10px] font-bold px-1.5 py-0.5 bg-white border border-ink-black rounded`,children:Y.problem_number?`#${Y.problem_number}`:`Custom`})]})]}),(0,S.jsx)(`h3`,{className:`font-headline-md text-base font-extrabold text-ink-black leading-tight`,children:Y.name}),(0,S.jsxs)(`div`,{className:`flex items-center gap-1.5 flex-wrap text-[10px] font-mono text-slate-700`,children:[(0,S.jsx)(`span`,{className:`bg-purple-100 text-purple-900 px-2 py-0.5 rounded border border-purple-200 font-semibold`,children:Y.pattern}),Y.optimal_time&&(0,S.jsxs)(`span`,{className:`bg-slate-100 px-1.5 py-0.5 rounded border border-slate-300`,children:[`T: `,Y.optimal_time]}),Y.optimal_space&&(0,S.jsxs)(`span`,{className:`bg-slate-100 px-1.5 py-0.5 rounded border border-slate-300`,children:[`S: `,Y.optimal_space]})]}),(0,S.jsxs)(`div`,{className:`flex items-center gap-1.5 pt-2 flex-wrap`,children:[Y.is_enrolled?(0,S.jsxs)(S.Fragment,{children:[(0,S.jsxs)(`button`,{onClick:()=>Q(Y),className:`px-2.5 py-1 bg-grass-green hover:bg-emerald-400 text-ink-black font-arcade text-[9px] font-bold border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 cursor-pointer flex items-center gap-1`,children:[(0,S.jsx)(s,{className:`w-3 h-3 fill-ink-black`}),(0,S.jsx)(`span`,{children:`REVIEW NOW`})]}),(0,S.jsxs)(`button`,{onClick:()=>Te(Y),disabled:V,className:`px-2 py-1 bg-amber-200 hover:bg-amber-300 text-ink-black font-arcade text-[9px] font-bold border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 cursor-pointer flex items-center gap-1 disabled:opacity-50`,title:`Reset interval to initial FSRS state due today`,children:[(0,S.jsx)(n,{className:`w-3 h-3`}),(0,S.jsx)(`span`,{children:`RESET`})]})]}):(0,S.jsxs)(`button`,{onClick:()=>Ee(Y),disabled:V||!Y.catalogProblem,className:`px-2.5 py-1 bg-sky-400 hover:bg-sky-300 text-ink-black font-arcade text-[9px] font-bold border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 cursor-pointer flex items-center gap-1 disabled:opacity-50`,children:[(0,S.jsx)(re,{className:`w-3 h-3`}),(0,S.jsx)(`span`,{children:`ENROLL CARD`})]}),(0,S.jsxs)(`button`,{onClick:()=>$(Y),className:`px-2 py-1 bg-white hover:bg-slate-100 text-ink-black font-arcade text-[9px] font-bold border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 cursor-pointer flex items-center gap-1`,children:[(0,S.jsx)(se,{className:`w-3 h-3`}),(0,S.jsx)(`span`,{children:`EDIT`})]}),Y.is_custom&&(0,S.jsxs)(`button`,{onClick:()=>De(Y),disabled:V,className:`px-2 py-1 bg-rose-200 hover:bg-rose-300 text-rose-950 font-arcade text-[9px] font-bold border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 cursor-pointer flex items-center gap-1 disabled:opacity-50`,children:[(0,S.jsx)(d,{className:`w-3 h-3 text-rose-700`}),(0,S.jsx)(`span`,{children:`DELETE`})]})]})]}),(0,S.jsxs)(`div`,{className:`flex border-b-2 border-ink-black bg-white shrink-0`,children:[(0,S.jsx)(`button`,{onClick:()=>R(`front`),className:`flex-1 py-1.5 font-arcade text-[9px] font-bold text-center border-r border-ink-black/20 cursor-pointer ${L===`front`?`bg-amber-300 text-ink-black`:`text-slate-600 hover:bg-slate-50`}`,children:`QUESTION`}),(0,S.jsx)(`button`,{onClick:()=>R(`back`),className:`flex-1 py-1.5 font-arcade text-[9px] font-bold text-center border-r border-ink-black/20 cursor-pointer ${L===`back`?`bg-amber-300 text-ink-black`:`text-slate-600 hover:bg-slate-50`}`,children:`SHOW ANSWER`}),(0,S.jsx)(`button`,{onClick:()=>R(`stats`),className:`flex-1 py-1.5 font-arcade text-[9px] font-bold text-center cursor-pointer ${L===`stats`?`bg-amber-300 text-ink-black`:`text-slate-600 hover:bg-slate-50`}`,children:`SRS INFO`})]}),(0,S.jsxs)(`div`,{className:`flex-1 p-4 overflow-y-auto custom-scrollbar space-y-4`,children:[L===`front`&&(0,S.jsxs)(`div`,{className:`space-y-3`,children:[(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`span`,{className:`font-arcade text-[8px] font-bold text-trash-gray uppercase block mb-1`,children:`PROBLEM DESCRIPTION`}),(0,S.jsx)(`div`,{className:`p-3 bg-white border-2 border-ink-black text-xs font-semibold leading-relaxed shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] whitespace-pre-wrap`,children:Y.description||`No description provided.`})]}),Y.examples&&(!Array.isArray(Y.examples)||Y.examples.length>0)&&(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`span`,{className:`font-arcade text-[8px] font-bold text-trash-gray uppercase block mb-1`,children:`EXAMPLES`}),(0,S.jsx)(`div`,{className:`space-y-1.5`,children:Array.isArray(Y.examples)?Y.examples.map((e,t)=>typeof e==`string`?(0,S.jsx)(`div`,{className:`p-2 bg-white border border-slate-300 text-[11px] font-mono`,children:e},t):(0,S.jsxs)(`div`,{className:`p-2 bg-white border border-slate-300 text-[11px] font-mono space-y-0.5`,children:[e.input&&(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`span`,{className:`font-bold text-slate-700`,children:`Input:`}),` `,e.input]}),e.output&&(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`span`,{className:`font-bold text-slate-700`,children:`Output:`}),` `,e.output]}),e.explanation&&(0,S.jsx)(`div`,{className:`text-slate-500 italic text-[10px]`,children:e.explanation})]},t)):(0,S.jsx)(`div`,{className:`p-2 bg-white border border-slate-300 text-[11px] font-mono`,children:String(Y.examples)})})]}),Y.constraints&&(!Array.isArray(Y.constraints)||Y.constraints.length>0)&&(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`span`,{className:`font-arcade text-[8px] font-bold text-trash-gray uppercase block mb-1`,children:`CONSTRAINTS`}),(0,S.jsx)(`div`,{className:`p-2.5 bg-slate-50 border border-slate-300 text-[11px] font-mono space-y-1 text-slate-700`,children:Array.isArray(Y.constraints)?Y.constraints.map((e,t)=>(0,S.jsxs)(`div`,{children:[`• `,e]},t)):(0,S.jsxs)(`div`,{children:[`• `,String(Y.constraints)]})})]})]}),L===`back`&&(0,S.jsxs)(`div`,{className:`space-y-3`,children:[(0,S.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,S.jsx)(`span`,{className:`font-arcade text-[8px] font-bold text-trash-gray uppercase`,children:`REFERENCE SOLUTION (PYTHON)`}),Y.reference_code&&(0,S.jsxs)(`button`,{onClick:Oe,className:`px-2 py-0.5 bg-white hover:bg-slate-100 text-ink-black border border-ink-black text-[9px] font-bold rounded flex items-center gap-1 cursor-pointer`,children:[z?(0,S.jsx)(c,{className:`w-3 h-3 text-emerald-600`}):(0,S.jsx)(ie,{className:`w-3 h-3`}),(0,S.jsx)(`span`,{children:z?`COPIED!`:`COPY`})]})]}),(0,S.jsx)(`div`,{className:`relative`,children:(0,S.jsx)(`pre`,{className:`p-3 bg-slate-900 text-emerald-400 font-mono text-[11px] rounded border-2 border-ink-black overflow-x-auto shadow-[2px_2px_0px_0px_rgba(30,41,59,1)]`,children:(0,S.jsx)(`code`,{children:Y.reference_code||`# No reference code available.`})})}),Y.how_to_solve&&(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`span`,{className:`font-arcade text-[8px] font-bold text-trash-gray uppercase block mb-1`,children:`HOW TO SOLVE & STRATEGY`}),(0,S.jsx)(`div`,{className:`p-2.5 bg-white border border-slate-300 text-xs font-semibold leading-relaxed`,children:Y.how_to_solve})]})]}),L===`stats`&&(0,S.jsxs)(`div`,{className:`space-y-3`,children:[(0,S.jsxs)(`div`,{className:`p-3 bg-white border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] space-y-2`,children:[(0,S.jsx)(`span`,{className:`font-arcade text-[9px] font-bold text-ink-black uppercase block border-b pb-1`,children:`FSRS REVIEW STATE`}),(0,S.jsxs)(`div`,{className:`grid grid-cols-2 gap-2 text-xs`,children:[(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`div`,{className:`text-[10px] text-trash-gray font-semibold`,children:`Current State`}),(0,S.jsx)(`div`,{className:`font-arcade text-base font-bold text-sky-700`,children:Y.is_enrolled?(Y.fsrs_state??0)===0?`New (0)`:(Y.fsrs_state??0)===1?`Learning (1)`:(Y.fsrs_state??0)===2?`Review (2)`:`Relearning (3)`:`Unenrolled`})]}),(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`div`,{className:`text-[10px] text-trash-gray font-semibold`,children:`Status`}),(0,S.jsx)(`div`,{className:`font-arcade text-xs font-bold text-emerald-700`,children:Y.is_due?`Due Today`:Y.is_enrolled?`Scheduled`:`Catalog New`})]}),(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`div`,{className:`text-[10px] text-trash-gray font-semibold`,children:`Stability`}),(0,S.jsx)(`div`,{className:`font-mono text-sm font-bold text-slate-800`,children:Y.fsrs_stability===void 0?`0.0d`:`${Y.fsrs_stability.toFixed(1)}d`})]}),(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`div`,{className:`text-[10px] text-trash-gray font-semibold`,children:`Difficulty`}),(0,S.jsx)(`div`,{className:`font-mono text-sm font-bold text-amber-700`,children:Y.fsrs_difficulty===void 0?`0.0/10`:`${Y.fsrs_difficulty.toFixed(1)}/10`})]}),(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`div`,{className:`text-[10px] text-trash-gray font-semibold`,children:`Total Attempts`}),(0,S.jsx)(`div`,{className:`font-mono text-sm font-bold text-slate-800`,children:Y.total_attempts})]}),(0,S.jsxs)(`div`,{children:[(0,S.jsx)(`div`,{className:`text-[10px] text-trash-gray font-semibold`,children:`Times Correct`}),(0,S.jsx)(`div`,{className:`font-mono text-sm font-bold text-emerald-600`,children:Y.times_correct})]}),(0,S.jsxs)(`div`,{className:`col-span-2 pt-1 border-t border-slate-200`,children:[(0,S.jsx)(`div`,{className:`text-[10px] text-trash-gray font-semibold`,children:`Retention Success Rate`}),(0,S.jsxs)(`div`,{className:`flex items-center gap-2 mt-1`,children:[(0,S.jsx)(`div`,{className:`flex-1 h-3 bg-slate-200 rounded-full overflow-hidden border border-slate-300`,children:(0,S.jsx)(`div`,{className:`h-full bg-emerald-500 rounded-full`,style:{width:`${Y.total_attempts>0?Math.round(Y.times_correct/Y.total_attempts*100):0}%`}})}),(0,S.jsx)(`span`,{className:`font-mono text-xs font-bold text-slate-800`,children:Y.total_attempts>0?`${Math.round(Y.times_correct/Y.total_attempts*100)}%`:`0%`})]})]})]})]}),(0,S.jsxs)(`div`,{className:`p-3 bg-white border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] space-y-1.5 text-xs`,children:[(0,S.jsx)(`span`,{className:`font-arcade text-[9px] font-bold text-ink-black uppercase block border-b pb-1`,children:`TIMESTAMPS`}),(0,S.jsxs)(`div`,{className:`flex items-center justify-between text-slate-700`,children:[(0,S.jsx)(`span`,{className:`text-[11px] font-semibold`,children:`Next Review:`}),(0,S.jsx)(`span`,{className:`font-mono text-[10px]`,children:Y.next_review?new Date(Y.next_review).toLocaleString():`Not scheduled`})]}),(0,S.jsxs)(`div`,{className:`flex items-center justify-between text-slate-700`,children:[(0,S.jsx)(`span`,{className:`text-[11px] font-semibold`,children:`Last Reviewed:`}),(0,S.jsx)(`span`,{className:`font-mono text-[10px]`,children:Y.last_reviewed?new Date(Y.last_reviewed).toLocaleString():`Never`})]})]})]})]})]}):(0,S.jsx)(`div`,{className:`flex-1 flex items-center justify-center p-6 text-center text-trash-gray font-mono text-xs`,children:`Select a card to view its Front, Back, and SRS details.`})})]})]})}export{C as default};
1234import{r as e}from"./rolldown-runtime-hePW80VL.js";import{A as t,B as n,Bt as r,Dt as i,E as a,H as o,Ht as s,K as c,L as l,M as u,S as d,St as f,T as p,V as m,X as h,_ as g,a as _,bt as v,c as y,ft as b,g as x,gt as S,ht as C,i as w,it as T,k as E,l as D,m as O,o as k,pt as A,q as j,r as M,st as ee,tt as te,u as ne,vt as re,x as ie,xt as ae,yt as N}from"./vendor-react-hnaVBnLv.js";import{s as P}from"./firebaseClient-DZobvwSx.js";import{a as oe,c as se,o as F}from"./index-DVWZ15xt.js";import{t as ce}from"./confetti.module-Uxh4CK4s.js";var I=e(s(),1),L=2600,R=1500,z=[{tMax:.15,name:`The Whispering Coast & Lowlands`,biome:`coast`},{tMax:.32,name:`The Elderwood Deep Forest`,biome:`forest`},{tMax:.48,name:`River Elden & The Twin Fords`,biome:`river`},{tMax:.68,name:`The Dragon Tooth Mountains & Passes`,biome:`mountain`},{tMax:.83,name:`The Misty Glade & Highland Woods`,biome:`forest`},{tMax:.93,name:`The Roaring Gorge & Cataracts`,biome:`river`},{tMax:1,name:`The Sunstone Peaks & Ancient Citadel`,biome:`ancient_ruins`}],B=[`Pencil marks still visible from the cartographer’s first survey.`,`A calm breeze sweeps through the grass, carrying the scent of pine.`,`Wooden planks creak underfoot as the river roars below.`,`Craggy pencil hatchings reveal steep, unforgiving granite slopes.`,`Ancient roots break through the worn gravel pathway.`,`The sound of rushing water echoes across the canyon walls.`,`A solitary stone marker inscribed with early explorer symbols.`,`Golden light filters softly through the sketched canopy.`,`Distant mountain ridges frame the expanding horizon.`,`A tranquil haven where wanderers rest before the mountain climb.`];function le(e=[],t={}){let n=[],r=e.length>0?e.length:150,i=[{t:0,x:220,y:1320,elev:10},{t:.08,x:380,y:1140,elev:45},{t:.16,x:580,y:980,elev:120},{t:.24,x:820,y:1120,elev:90},{t:.32,x:940,y:860,elev:180},{t:.4,x:720,y:640,elev:320},{t:.48,x:1050,y:520,elev:580},{t:.56,x:1320,y:720,elev:890},{t:.64,x:1540,y:480,elev:1250},{t:.72,x:1780,y:680,elev:920},{t:.8,x:1980,y:920,elev:460},{t:.88,x:2220,y:760,elev:750},{t:.94,x:2180,y:480,elev:1180},{t:1,x:2420,y:240,elev:1620}];for(let a=0;a<r;a++){let o=r>1?a/(r-1):0,s=0;for(;s<i.length-2&&i[s+1].t<o;)s++;let c=i[Math.max(0,s-1)],l=i[s],u=i[Math.min(i.length-1,s+1)],d=i[Math.min(i.length-1,s+2)],f=u.t-l.t||.001,p=(o-l.t)/f,m=p,h=m*m,g=h*m,_=-.5*g+h-.5*m,v=1.5*g-2.5*h+1,y=-1.5*g+2*h+.5*m,b=.5*g-.5*h,x=_*c.x+v*l.x+y*u.x+b*d.x,S=_*c.y+v*l.y+y*u.y+b*d.y,C=Math.sin(a*.45)*14+Math.cos(a*.9)*8,w=Math.cos(a*.4)*14+Math.sin(a*.85)*8;x=Math.round(x+C),S=Math.round(S+w);let T=Math.round(l.elev+p*(u.elev-l.elev)+Math.sin(a*.5)*15),E=z.find(e=>o<=e.tMax)||z[z.length-1],D=e.length>0?e[a]:a+1,O=t[D]||(D<0?`Custom Challenge ${a+1}`:`LeetCode #${D}`),k=B[a%B.length];n.push({id:D,sequenceIndex:a,x,y:S,name:O,biome:E.biome,regionName:E.name,elevation:Math.max(10,T),lore:k})}return n}var V=[{id:`wm-bg1`,x:380,y:310,size:70,height:85,ridgeShift:-4,hasSnow:!1,layer:0,elevation:840,rangeName:`Western Crags`},{id:`wm-bg2`,x:490,y:280,size:85,height:105,ridgeShift:6,hasSnow:!0,layer:0,elevation:1120,name:`Peak of the North Wind`,rangeName:`Western Crags`},{id:`wm-bg3`,x:620,y:300,size:75,height:95,ridgeShift:-3,hasSnow:!1,layer:0,elevation:960,rangeName:`Western Crags`},{id:`wm-bg4`,x:730,y:320,size:65,height:80,ridgeShift:4,hasSnow:!1,layer:0,elevation:780,rangeName:`Western Crags`},{id:`m1`,x:430,y:375,size:80,height:105,ridgeShift:5,hasSnow:!0,elevation:1240,name:`Crag of the Mist`,rangeName:`Western Crags`},{id:`m2`,x:530,y:345,size:95,height:125,ridgeShift:-7,hasSnow:!0,elevation:1480,name:`Peak of Solitude`,rangeName:`Western Crags`},{id:`m3`,x:630,y:365,size:85,height:110,ridgeShift:3,hasSnow:!0,elevation:1310,name:`Shadowhorn`,rangeName:`Western Crags`},{id:`m4`,x:720,y:385,size:70,height:90,ridgeShift:-4,hasSnow:!1,elevation:990,rangeName:`Western Crags`},{id:`m5`,x:370,y:430,size:55,height:65,ridgeShift:4,hasSnow:!1,layer:2,elevation:620,rangeName:`Western Crags`},{id:`m6`,x:470,y:425,size:68,height:80,ridgeShift:-3,hasSnow:!1,layer:2,elevation:760,name:`Gullwing Bluff`,rangeName:`Western Crags`},{id:`m6b`,x:575,y:420,size:72,height:88,ridgeShift:3,hasSnow:!1,layer:2,elevation:850,rangeName:`Western Crags`},{id:`m6c`,x:670,y:435,size:58,height:70,ridgeShift:-2,hasSnow:!1,layer:2,elevation:680,rangeName:`Western Crags`},{id:`dt-bg1`,x:1130,y:260,size:90,height:120,ridgeShift:-6,hasSnow:!0,layer:0,elevation:1850,rangeName:`Dragon's Tooth Range`},{id:`dt-bg2`,x:1250,y:225,size:115,height:150,ridgeShift:8,hasSnow:!0,layer:0,elevation:2180,name:`Crown of the North`,rangeName:`Dragon's Tooth Range`},{id:`dt-bg3`,x:1380,y:210,size:130,height:175,ridgeShift:-10,hasSnow:!0,layer:0,elevation:2450,name:`Apex of Clouds`,rangeName:`Dragon's Tooth Range`},{id:`dt-bg4`,x:1510,y:240,size:110,height:145,ridgeShift:7,hasSnow:!0,layer:0,elevation:2020,rangeName:`Dragon's Tooth Range`},{id:`dt-bg5`,x:1640,y:280,size:90,height:115,ridgeShift:-5,hasSnow:!0,layer:0,elevation:1690,rangeName:`Dragon's Tooth Range`},{id:`m7`,x:1190,y:325,size:105,height:140,ridgeShift:-8,hasSnow:!0,elevation:1980,name:`The Dragon's Crest`,rangeName:`Dragon's Tooth Range`},{id:`m8`,x:1310,y:295,size:125,height:165,ridgeShift:10,hasSnow:!0,elevation:2360,name:`Frostcrag Pinnacle`,rangeName:`Dragon's Tooth Range`},{id:`m9`,x:1435,y:320,size:115,height:150,ridgeShift:-6,hasSnow:!0,elevation:2120,name:`Thunderhorn Peak`,rangeName:`Dragon's Tooth Range`},{id:`m10`,x:1560,y:355,size:98,height:125,ridgeShift:7,hasSnow:!0,elevation:1780,name:`Screaming Ridge`,rangeName:`Dragon's Tooth Range`},{id:`m10b`,x:1680,y:375,size:85,height:105,ridgeShift:-4,hasSnow:!1,elevation:1420,rangeName:`Dragon's Tooth Range`},{id:`m11`,x:1260,y:415,size:90,height:115,ridgeShift:-5,hasSnow:!0,elevation:1560,name:`Ironhorn Needle`,rangeName:`Dragon's Tooth Range`},{id:`m12`,x:1375,y:405,size:100,height:130,ridgeShift:6,hasSnow:!0,elevation:1720,name:`Shadowcrevasse Crag`,rangeName:`Dragon's Tooth Range`},{id:`m13`,x:1490,y:440,size:88,height:110,ridgeShift:-4,hasSnow:!0,elevation:1490,rangeName:`Dragon's Tooth Range`},{id:`m14`,x:1610,y:435,size:82,height:100,ridgeShift:5,hasSnow:!1,elevation:1320,rangeName:`Dragon's Tooth Range`},{id:`m15`,x:1160,y:590,size:80,height:100,ridgeShift:5,hasSnow:!1,elevation:1180,name:`Wanderer's Bluff`,rangeName:`Mid-Pass Gorge`},{id:`m16`,x:1390,y:610,size:90,height:115,ridgeShift:-6,hasSnow:!0,elevation:1390,name:`Eagle Eye Ridge`,rangeName:`Mid-Pass Gorge`},{id:`m17`,x:1510,y:585,size:95,height:120,ridgeShift:5,hasSnow:!0,elevation:1520,name:`Razorback Spine`,rangeName:`Mid-Pass Gorge`},{id:`m18`,x:1630,y:565,size:85,height:105,ridgeShift:-4,hasSnow:!1,elevation:1280,rangeName:`Mid-Pass Gorge`},{id:`m18b`,x:1740,y:580,size:75,height:90,ridgeShift:3,hasSnow:!1,elevation:1050,rangeName:`Mid-Pass Gorge`},{id:`es-bg1`,x:1980,y:310,size:88,height:115,ridgeShift:-5,hasSnow:!0,layer:0,elevation:1650,rangeName:`Sunstone Highlands`},{id:`es-bg2`,x:2110,y:245,size:105,height:140,ridgeShift:6,hasSnow:!0,layer:0,elevation:1980,name:`Sun Pillar`,rangeName:`Sunstone Highlands`},{id:`es-bg3`,x:2260,y:160,size:135,height:180,ridgeShift:-8,hasSnow:!0,layer:0,elevation:2580,name:`Crown of the Heavens`,rangeName:`Sunstone Highlands`},{id:`es-bg4`,x:2410,y:210,size:115,height:150,ridgeShift:7,hasSnow:!0,layer:0,elevation:2240,rangeName:`Sunstone Highlands`},{id:`m19`,x:2040,y:375,size:98,height:128,ridgeShift:6,hasSnow:!0,elevation:1720,name:`Sunstone Spire`,rangeName:`Sunstone Highlands`},{id:`m20`,x:2170,y:315,size:115,height:150,ridgeShift:-7,hasSnow:!0,elevation:2080,name:`Sanctuary Peak`,rangeName:`Sunstone Highlands`},{id:`m21`,x:2310,y:220,size:130,height:170,ridgeShift:8,hasSnow:!0,elevation:2390,name:`Pinnacle of the Ancients`,rangeName:`Sunstone Highlands`},{id:`m22`,x:2440,y:360,size:90,height:115,ridgeShift:-5,hasSnow:!0,elevation:1610,name:`Falcon Perch`,rangeName:`Sunstone Highlands`},{id:`m23`,x:2260,y:405,size:82,height:98,ridgeShift:4,hasSnow:!1,elevation:1250,name:`Altar Crag`,rangeName:`Sunstone Highlands`},{id:`m24`,x:2380,y:420,size:76,height:88,ridgeShift:-3,hasSnow:!1,elevation:1120,rangeName:`Sunstone Highlands`},{id:`m25`,x:2140,y:450,size:70,height:80,ridgeShift:3,hasSnow:!1,elevation:980,rangeName:`Sunstone Highlands`}],H=[{id:`river-elden`,name:`River Elden`,d:`M 1340,290 C 1310,380 1260,460 1210,540 C 1140,640 1020,700 960,820 C 900,940 930,1060 880,1180 C 840,1280 760,1360 690,1480`,width:14,hasBridges:[{x:945,y:855,angle:-35},{x:890,y:1160,angle:25}]},{id:`river-silver`,name:`Silver Meander`,d:`M 580,410 C 650,490 730,550 780,660 C 830,760 910,810 960,820`,width:8,hasBridges:[{x:740,y:620,angle:45}]},{id:`river-cataract`,name:`Highland Torrent`,d:`M 2150,320 C 2100,450 2050,600 2020,760 C 1990,920 1920,1050 1840,1180 C 1760,1310 1710,1420 1660,1500`,width:11,hasBridges:[{x:2010,y:810,angle:-20}]}],U=[{id:`f1`,name:`The Whispering Pines`,cx:580,cy:1040,rx:230,ry:160,treeCount:42,trees:W(580,1040,210,140,42,`pines`)},{id:`f2`,name:`Elderwood Deep`,cx:820,cy:1140,rx:250,ry:180,treeCount:52,trees:W(820,1140,230,160,52,`oaks`)},{id:`f3`,name:`Mistwood Valley`,cx:860,cy:620,rx:190,ry:140,treeCount:36,trees:W(860,620,170,120,36,`willows`)},{id:`f4`,name:`Highland Spruces`,cx:1760,cy:740,rx:210,ry:155,treeCount:38,trees:W(1760,740,190,135,38,`highland_spruce`)},{id:`f5`,name:`Verdant Basin`,cx:1960,cy:980,rx:200,ry:150,treeCount:38,trees:W(1960,980,180,130,38,`mixed`)},{id:`f6`,name:`Shadowglen Copse`,cx:390,cy:690,rx:140,ry:100,treeCount:22,trees:W(390,690,120,80,22,`pines`)},{id:`f7`,name:`Sunstone Grove`,cx:2360,cy:580,rx:150,ry:110,treeCount:24,trees:W(2360,580,130,90,24,`mixed`)}];function W(e,t,n,r,i,a){let o=[];for(let s=0;s<i;s++){let c=s*2.399963+Math.sin(s*1.7)*.4,l=((s+.5)/i)**.65,u=Math.sin(s*4.3+e)*14,d=Math.cos(s*3.9+t)*12,f=Math.round(e+n*l*Math.cos(c)+u),p=Math.round(t+r*l*Math.sin(c)+d),m=.85+s%4*.1;s===0||s===5?m=1.35:s%7==0&&(m=.68);let h=`pine`;if(a===`pines`)h=s%6==0?`birch`:`pine`;else if(a===`oaks`)h=s===0||s===5?`ancient_oak`:s%5==0?`birch`:`oak`;else if(a===`willows`)h=s%3==0?`willow`:s%4==0?`birch`:`oak`;else if(a===`highland_spruce`)h=s%5==0?`pine`:`spruce`;else{let e=s%5;h=e===0?`ancient_oak`:e===1?`pine`:e===2?`oak`:e===3?`spruce`:`birch`}o.push({x:f,y:p,scale:m,type:h,seed:Math.round(e*7+t*11+s*31)})}return o}function G(e){if(e.length===0)return``;if(e.length===1)return`M ${e[0].x},${e[0].y}`;let t=`M ${e[0].x},${e[0].y}`;for(let n=0;n<e.length-1;n++){let r=e[n],i=e[n+1],a=(r.x+i.x)/2,o=(r.y+i.y)/2;if(n===0)t+=` Q ${r.x},${r.y} ${a},${o}`;else{let a=e[n-1],o=r.x+(i.x-a.x)*.18,s=r.y+(i.y-a.y)*.18;t+=` S ${o},${s} ${i.x},${i.y}`}}return t}function K(e,t){return t<=0||e.length===0?``:G(e.slice(0,t+1))}var ue={parchment:{id:`parchment`,name:`Daylight Parchment`,bgClass:`parchment-bg`,textColor:`#2c221a`,pencilColor:`#382e25`,pencilShade:`#8c765c`,riverColor:`#96afbe`,glowColor:`#f59e0b`,glowSubtle:`#fbbf24`,nodeUnlit:`#f0e5ce`,nodeLit:`#fbbf24`,nodeLitStroke:`#ffffff`},dark_parchment:{id:`dark_parchment`,name:`Midnight Cartography`,bgClass:`parchment-dark-bg`,textColor:`#f3e9d2`,pencilColor:`#8a7761`,pencilShade:`#4a3f33`,riverColor:`#365163`,glowColor:`#fbbf24`,glowSubtle:`#f59e0b`,nodeUnlit:`#231e17`,nodeLit:`#f59e0b`,nodeLitStroke:`#fffbeb`}},q=new class{ctx=null;enabled=!0;initCtx(){if(!this.ctx&&typeof window<`u`){let e=window.AudioContext||window.webkitAudioContext;e&&(this.ctx=new e)}this.ctx&&this.ctx.state===`suspended`&&this.ctx.resume()}setEnabled(e){this.enabled=e,e&&this.initCtx()}isEnabled(){return this.enabled}playNodeLightUp(e,t=150){if(this.enabled&&(this.initCtx(),this.ctx))try{let n=this.ctx.currentTime,r=[261.63,293.66,329.63,392,440,523.25,587.33,659.25,783.99,880],i=Math.floor(e/Math.max(1,t)*20),a=1+Math.floor(i/r.length)*.5,o=r[i%r.length]*a,s=this.ctx.createOscillator(),c=this.ctx.createOscillator(),l=this.ctx.createGain();s.type=`sine`,s.frequency.setValueAtTime(o,n),c.type=`triangle`,c.frequency.setValueAtTime(o*2.01,n),l.gain.setValueAtTime(.001,n),l.gain.linearRampToValueAtTime(.12,n+.02),l.gain.exponentialRampToValueAtTime(1e-4,n+.55),s.connect(l),c.connect(l),l.connect(this.ctx.destination),s.start(n),c.start(n),s.stop(n+.6),c.stop(n+.6)}catch{}}playPencilScratch(){if(this.enabled&&(this.initCtx(),this.ctx))try{let e=this.ctx.currentTime,t=Math.floor(this.ctx.sampleRate*.06),n=this.ctx.createBuffer(1,t,this.ctx.sampleRate),r=n.getChannelData(0);for(let e=0;e<t;e++)r[e]=(Math.random()*2-1)*Math.exp(-e/(t*.4));let i=this.ctx.createBufferSource();i.buffer=n;let a=this.ctx.createBiquadFilter();a.type=`bandpass`,a.frequency.setValueAtTime(1400+Math.random()*800,e),a.Q.setValueAtTime(3.5,e);let o=this.ctx.createGain();o.gain.setValueAtTime(.04,e),o.gain.exponentialRampToValueAtTime(.001,e+.05),i.connect(a),a.connect(o),o.connect(this.ctx.destination),i.start(e)}catch{}}playVictoryChime(){this.enabled&&(this.initCtx(),this.ctx&&[523.25,659.25,783.99,1046.5].forEach((e,t)=>{setTimeout(()=>{if(!this.ctx)return;let t=this.ctx.currentTime,n=this.ctx.createOscillator(),r=this.ctx.createGain();n.type=`sine`,n.frequency.setValueAtTime(e,t),r.gain.setValueAtTime(.001,t),r.gain.linearRampToValueAtTime(.15,t+.05),r.gain.exponentialRampToValueAtTime(1e-4,t+1.2),n.connect(r),r.connect(this.ctx.destination),n.start(t),n.stop(t+1.3)},t*120)}))}},J=r();function Y(e){let t=Math.sin(e*12.9898+78.233)*43758.5453;return t-Math.floor(t)}var de=({mountain:e,theme:t})=>{let n=t.id!==`parchment`,r=t.pencilColor,i=t.pencilShade,{id:a,x:o,y:s,size:c,height:l,ridgeShift:u=0,hasSnow:d=l>95}=e,f=(0,I.useMemo)(()=>{let e=0;for(let t=0;t<a.length;t++)e+=a.charCodeAt(t)*(t+1);e+=Math.round(o+s);let t=o+u,n=s-l,r=o-c,i=o+c,f=[{x:t,y:n}];for(let i=1;i<=6;i++){let a=i/6,o=t-(t-r)*a**.92,s=n+l*a,u=(Y(e+i*17)-.48)*(c*.14)*Math.sin(a*Math.PI),d=Y(e+i*31)>.65?l*.035:0;f.push({x:Math.round(o+u),y:Math.round(s+d)})}let p=[{x:t,y:n}];for(let r=1;r<=6;r++){let a=r/6,o=t+(i-t)*a**.92,s=n+l*a,u=(Y(e+r*43)-.48)*(c*.14)*Math.sin(a*Math.PI),d=Y(e+r*59)>.65?l*.035:0;p.push({x:Math.round(o+u),y:Math.round(s+d)})}let m=[{x:t,y:n}];for(let r=1;r<=7;r++){let i=r/7,a=t+(o+u*.25+(Y(e+101)-.5)*(c*.18)-t)*i**1.15,s=n+l*i,d=Math.sin(i*Math.PI*2.2+Y(e+113))*(c*.09);m.push({x:Math.round(a+d),y:Math.round(s)})}let h=[],g=m[2];if(g){let t=o+c*.52+(Y(e+201)-.5)*14,n=s-l*.16,r=(g.x+t)/2+10,i=(g.y+n)/2-5;h.push({d:`M ${g.x},${g.y} Q ${r},${i} ${t},${n}`,side:`right`})}let _=m[3];if(_){let t=o-c*.55+(Y(e+301)-.5)*14,n=s-l*.14,r=(_.x+t)/2-8,i=(_.y+n)/2-4;h.push({d:`M ${_.x},${_.y} Q ${r},${i} ${t},${n}`,side:`left`})}let v=[],y=Math.max(12,Math.round(l/5.2));for(let r=1;r<=y;r++){let a=r/(y+1),o=m[Math.min(m.length-1,Math.max(0,Math.round(a*(m.length-1))))],c=n+l*a,u=p[Math.min(p.length-1,Math.max(0,Math.round(a*(p.length-1))))]||{x:t+(i-t)*a,y:c},d=o.x+(u.x-o.x)*.05,f=c+(Y(e+r*71)-.5)*2,h=r%3==0?.88:r%2==0?.68:.48,g=d+(u.x-d)*h,_=(c-n)*.18+(u.y-c)*.3,b=Math.min(s+2,f+_+(Y(e+r*83)-.5)*3);v.push({x1:Math.round(d),y1:Math.round(f),x2:Math.round(g),y2:Math.round(b),width:r<4?.85:1.15,opacity:(1-a*.35)*.8})}let b=[],x=Math.max(4,Math.round(l/20));for(let i=1;i<=x;i++){let a=(i+.25)/(x+1),o=n+l*a,s=m[Math.min(m.length-1,Math.round(a*(m.length-1)))],c=f[Math.min(f.length-1,Math.round(a*(f.length-1)))]||{x:t-(t-r)*a,y:o},u=s.x-(s.x-c.x)*.12,d=o+1,p=s.x-(s.x-c.x)*(.45+Y(e+i*97)*.25),h=o+6+Y(e+i*103)*5,g=(u+p)/2-3,_=(d+h)/2+2;b.push({d:`M ${Math.round(u)},${Math.round(d)} Q ${Math.round(g)},${Math.round(_)} ${Math.round(p)},${Math.round(h)}`,width:.85})}let S=``;if(d){let e=f[2]||f[1],r=m[2]||m[1],i=p[2]||p[1];S=`M ${t},${n}L ${f[1].x},${f[1].y}L ${e.x},${e.y}Q ${(e.x+r.x)/2},${e.y-5} ${r.x},${r.y+3}1234import{r as e}from"./rolldown-runtime-hePW80VL.js";import{A as t,B as n,Bt as r,Dt as i,E as a,H as o,Ht as s,K as c,L as l,M as u,S as d,St as f,T as p,V as m,X as h,_ as g,a as _,bt as v,c as y,ft as b,g as x,gt as S,ht as C,i as w,it as T,k as E,l as D,m as O,o as k,pt as A,q as j,r as M,st as ee,tt as te,u as ne,vt as re,x as ie,xt as ae,yt as N}from"./vendor-react-hnaVBnLv.js";import{s as P}from"./firebaseClient-DZobvwSx.js";import{a as oe,c as se,o as F}from"./index-Q9onQHft.js";import{t as ce}from"./confetti.module-Uxh4CK4s.js";var I=e(s(),1),L=2600,R=1500,z=[{tMax:.15,name:`The Whispering Coast & Lowlands`,biome:`coast`},{tMax:.32,name:`The Elderwood Deep Forest`,biome:`forest`},{tMax:.48,name:`River Elden & The Twin Fords`,biome:`river`},{tMax:.68,name:`The Dragon Tooth Mountains & Passes`,biome:`mountain`},{tMax:.83,name:`The Misty Glade & Highland Woods`,biome:`forest`},{tMax:.93,name:`The Roaring Gorge & Cataracts`,biome:`river`},{tMax:1,name:`The Sunstone Peaks & Ancient Citadel`,biome:`ancient_ruins`}],B=[`Pencil marks still visible from the cartographer’s first survey.`,`A calm breeze sweeps through the grass, carrying the scent of pine.`,`Wooden planks creak underfoot as the river roars below.`,`Craggy pencil hatchings reveal steep, unforgiving granite slopes.`,`Ancient roots break through the worn gravel pathway.`,`The sound of rushing water echoes across the canyon walls.`,`A solitary stone marker inscribed with early explorer symbols.`,`Golden light filters softly through the sketched canopy.`,`Distant mountain ridges frame the expanding horizon.`,`A tranquil haven where wanderers rest before the mountain climb.`];function le(e=[],t={}){let n=[],r=e.length>0?e.length:150,i=[{t:0,x:220,y:1320,elev:10},{t:.08,x:380,y:1140,elev:45},{t:.16,x:580,y:980,elev:120},{t:.24,x:820,y:1120,elev:90},{t:.32,x:940,y:860,elev:180},{t:.4,x:720,y:640,elev:320},{t:.48,x:1050,y:520,elev:580},{t:.56,x:1320,y:720,elev:890},{t:.64,x:1540,y:480,elev:1250},{t:.72,x:1780,y:680,elev:920},{t:.8,x:1980,y:920,elev:460},{t:.88,x:2220,y:760,elev:750},{t:.94,x:2180,y:480,elev:1180},{t:1,x:2420,y:240,elev:1620}];for(let a=0;a<r;a++){let o=r>1?a/(r-1):0,s=0;for(;s<i.length-2&&i[s+1].t<o;)s++;let c=i[Math.max(0,s-1)],l=i[s],u=i[Math.min(i.length-1,s+1)],d=i[Math.min(i.length-1,s+2)],f=u.t-l.t||.001,p=(o-l.t)/f,m=p,h=m*m,g=h*m,_=-.5*g+h-.5*m,v=1.5*g-2.5*h+1,y=-1.5*g+2*h+.5*m,b=.5*g-.5*h,x=_*c.x+v*l.x+y*u.x+b*d.x,S=_*c.y+v*l.y+y*u.y+b*d.y,C=Math.sin(a*.45)*14+Math.cos(a*.9)*8,w=Math.cos(a*.4)*14+Math.sin(a*.85)*8;x=Math.round(x+C),S=Math.round(S+w);let T=Math.round(l.elev+p*(u.elev-l.elev)+Math.sin(a*.5)*15),E=z.find(e=>o<=e.tMax)||z[z.length-1],D=e.length>0?e[a]:a+1,O=t[D]||(D<0?`Custom Challenge ${a+1}`:`LeetCode #${D}`),k=B[a%B.length];n.push({id:D,sequenceIndex:a,x,y:S,name:O,biome:E.biome,regionName:E.name,elevation:Math.max(10,T),lore:k})}return n}var V=[{id:`wm-bg1`,x:380,y:310,size:70,height:85,ridgeShift:-4,hasSnow:!1,layer:0,elevation:840,rangeName:`Western Crags`},{id:`wm-bg2`,x:490,y:280,size:85,height:105,ridgeShift:6,hasSnow:!0,layer:0,elevation:1120,name:`Peak of the North Wind`,rangeName:`Western Crags`},{id:`wm-bg3`,x:620,y:300,size:75,height:95,ridgeShift:-3,hasSnow:!1,layer:0,elevation:960,rangeName:`Western Crags`},{id:`wm-bg4`,x:730,y:320,size:65,height:80,ridgeShift:4,hasSnow:!1,layer:0,elevation:780,rangeName:`Western Crags`},{id:`m1`,x:430,y:375,size:80,height:105,ridgeShift:5,hasSnow:!0,elevation:1240,name:`Crag of the Mist`,rangeName:`Western Crags`},{id:`m2`,x:530,y:345,size:95,height:125,ridgeShift:-7,hasSnow:!0,elevation:1480,name:`Peak of Solitude`,rangeName:`Western Crags`},{id:`m3`,x:630,y:365,size:85,height:110,ridgeShift:3,hasSnow:!0,elevation:1310,name:`Shadowhorn`,rangeName:`Western Crags`},{id:`m4`,x:720,y:385,size:70,height:90,ridgeShift:-4,hasSnow:!1,elevation:990,rangeName:`Western Crags`},{id:`m5`,x:370,y:430,size:55,height:65,ridgeShift:4,hasSnow:!1,layer:2,elevation:620,rangeName:`Western Crags`},{id:`m6`,x:470,y:425,size:68,height:80,ridgeShift:-3,hasSnow:!1,layer:2,elevation:760,name:`Gullwing Bluff`,rangeName:`Western Crags`},{id:`m6b`,x:575,y:420,size:72,height:88,ridgeShift:3,hasSnow:!1,layer:2,elevation:850,rangeName:`Western Crags`},{id:`m6c`,x:670,y:435,size:58,height:70,ridgeShift:-2,hasSnow:!1,layer:2,elevation:680,rangeName:`Western Crags`},{id:`dt-bg1`,x:1130,y:260,size:90,height:120,ridgeShift:-6,hasSnow:!0,layer:0,elevation:1850,rangeName:`Dragon's Tooth Range`},{id:`dt-bg2`,x:1250,y:225,size:115,height:150,ridgeShift:8,hasSnow:!0,layer:0,elevation:2180,name:`Crown of the North`,rangeName:`Dragon's Tooth Range`},{id:`dt-bg3`,x:1380,y:210,size:130,height:175,ridgeShift:-10,hasSnow:!0,layer:0,elevation:2450,name:`Apex of Clouds`,rangeName:`Dragon's Tooth Range`},{id:`dt-bg4`,x:1510,y:240,size:110,height:145,ridgeShift:7,hasSnow:!0,layer:0,elevation:2020,rangeName:`Dragon's Tooth Range`},{id:`dt-bg5`,x:1640,y:280,size:90,height:115,ridgeShift:-5,hasSnow:!0,layer:0,elevation:1690,rangeName:`Dragon's Tooth Range`},{id:`m7`,x:1190,y:325,size:105,height:140,ridgeShift:-8,hasSnow:!0,elevation:1980,name:`The Dragon's Crest`,rangeName:`Dragon's Tooth Range`},{id:`m8`,x:1310,y:295,size:125,height:165,ridgeShift:10,hasSnow:!0,elevation:2360,name:`Frostcrag Pinnacle`,rangeName:`Dragon's Tooth Range`},{id:`m9`,x:1435,y:320,size:115,height:150,ridgeShift:-6,hasSnow:!0,elevation:2120,name:`Thunderhorn Peak`,rangeName:`Dragon's Tooth Range`},{id:`m10`,x:1560,y:355,size:98,height:125,ridgeShift:7,hasSnow:!0,elevation:1780,name:`Screaming Ridge`,rangeName:`Dragon's Tooth Range`},{id:`m10b`,x:1680,y:375,size:85,height:105,ridgeShift:-4,hasSnow:!1,elevation:1420,rangeName:`Dragon's Tooth Range`},{id:`m11`,x:1260,y:415,size:90,height:115,ridgeShift:-5,hasSnow:!0,elevation:1560,name:`Ironhorn Needle`,rangeName:`Dragon's Tooth Range`},{id:`m12`,x:1375,y:405,size:100,height:130,ridgeShift:6,hasSnow:!0,elevation:1720,name:`Shadowcrevasse Crag`,rangeName:`Dragon's Tooth Range`},{id:`m13`,x:1490,y:440,size:88,height:110,ridgeShift:-4,hasSnow:!0,elevation:1490,rangeName:`Dragon's Tooth Range`},{id:`m14`,x:1610,y:435,size:82,height:100,ridgeShift:5,hasSnow:!1,elevation:1320,rangeName:`Dragon's Tooth Range`},{id:`m15`,x:1160,y:590,size:80,height:100,ridgeShift:5,hasSnow:!1,elevation:1180,name:`Wanderer's Bluff`,rangeName:`Mid-Pass Gorge`},{id:`m16`,x:1390,y:610,size:90,height:115,ridgeShift:-6,hasSnow:!0,elevation:1390,name:`Eagle Eye Ridge`,rangeName:`Mid-Pass Gorge`},{id:`m17`,x:1510,y:585,size:95,height:120,ridgeShift:5,hasSnow:!0,elevation:1520,name:`Razorback Spine`,rangeName:`Mid-Pass Gorge`},{id:`m18`,x:1630,y:565,size:85,height:105,ridgeShift:-4,hasSnow:!1,elevation:1280,rangeName:`Mid-Pass Gorge`},{id:`m18b`,x:1740,y:580,size:75,height:90,ridgeShift:3,hasSnow:!1,elevation:1050,rangeName:`Mid-Pass Gorge`},{id:`es-bg1`,x:1980,y:310,size:88,height:115,ridgeShift:-5,hasSnow:!0,layer:0,elevation:1650,rangeName:`Sunstone Highlands`},{id:`es-bg2`,x:2110,y:245,size:105,height:140,ridgeShift:6,hasSnow:!0,layer:0,elevation:1980,name:`Sun Pillar`,rangeName:`Sunstone Highlands`},{id:`es-bg3`,x:2260,y:160,size:135,height:180,ridgeShift:-8,hasSnow:!0,layer:0,elevation:2580,name:`Crown of the Heavens`,rangeName:`Sunstone Highlands`},{id:`es-bg4`,x:2410,y:210,size:115,height:150,ridgeShift:7,hasSnow:!0,layer:0,elevation:2240,rangeName:`Sunstone Highlands`},{id:`m19`,x:2040,y:375,size:98,height:128,ridgeShift:6,hasSnow:!0,elevation:1720,name:`Sunstone Spire`,rangeName:`Sunstone Highlands`},{id:`m20`,x:2170,y:315,size:115,height:150,ridgeShift:-7,hasSnow:!0,elevation:2080,name:`Sanctuary Peak`,rangeName:`Sunstone Highlands`},{id:`m21`,x:2310,y:220,size:130,height:170,ridgeShift:8,hasSnow:!0,elevation:2390,name:`Pinnacle of the Ancients`,rangeName:`Sunstone Highlands`},{id:`m22`,x:2440,y:360,size:90,height:115,ridgeShift:-5,hasSnow:!0,elevation:1610,name:`Falcon Perch`,rangeName:`Sunstone Highlands`},{id:`m23`,x:2260,y:405,size:82,height:98,ridgeShift:4,hasSnow:!1,elevation:1250,name:`Altar Crag`,rangeName:`Sunstone Highlands`},{id:`m24`,x:2380,y:420,size:76,height:88,ridgeShift:-3,hasSnow:!1,elevation:1120,rangeName:`Sunstone Highlands`},{id:`m25`,x:2140,y:450,size:70,height:80,ridgeShift:3,hasSnow:!1,elevation:980,rangeName:`Sunstone Highlands`}],H=[{id:`river-elden`,name:`River Elden`,d:`M 1340,290 C 1310,380 1260,460 1210,540 C 1140,640 1020,700 960,820 C 900,940 930,1060 880,1180 C 840,1280 760,1360 690,1480`,width:14,hasBridges:[{x:945,y:855,angle:-35},{x:890,y:1160,angle:25}]},{id:`river-silver`,name:`Silver Meander`,d:`M 580,410 C 650,490 730,550 780,660 C 830,760 910,810 960,820`,width:8,hasBridges:[{x:740,y:620,angle:45}]},{id:`river-cataract`,name:`Highland Torrent`,d:`M 2150,320 C 2100,450 2050,600 2020,760 C 1990,920 1920,1050 1840,1180 C 1760,1310 1710,1420 1660,1500`,width:11,hasBridges:[{x:2010,y:810,angle:-20}]}],U=[{id:`f1`,name:`The Whispering Pines`,cx:580,cy:1040,rx:230,ry:160,treeCount:42,trees:W(580,1040,210,140,42,`pines`)},{id:`f2`,name:`Elderwood Deep`,cx:820,cy:1140,rx:250,ry:180,treeCount:52,trees:W(820,1140,230,160,52,`oaks`)},{id:`f3`,name:`Mistwood Valley`,cx:860,cy:620,rx:190,ry:140,treeCount:36,trees:W(860,620,170,120,36,`willows`)},{id:`f4`,name:`Highland Spruces`,cx:1760,cy:740,rx:210,ry:155,treeCount:38,trees:W(1760,740,190,135,38,`highland_spruce`)},{id:`f5`,name:`Verdant Basin`,cx:1960,cy:980,rx:200,ry:150,treeCount:38,trees:W(1960,980,180,130,38,`mixed`)},{id:`f6`,name:`Shadowglen Copse`,cx:390,cy:690,rx:140,ry:100,treeCount:22,trees:W(390,690,120,80,22,`pines`)},{id:`f7`,name:`Sunstone Grove`,cx:2360,cy:580,rx:150,ry:110,treeCount:24,trees:W(2360,580,130,90,24,`mixed`)}];function W(e,t,n,r,i,a){let o=[];for(let s=0;s<i;s++){let c=s*2.399963+Math.sin(s*1.7)*.4,l=((s+.5)/i)**.65,u=Math.sin(s*4.3+e)*14,d=Math.cos(s*3.9+t)*12,f=Math.round(e+n*l*Math.cos(c)+u),p=Math.round(t+r*l*Math.sin(c)+d),m=.85+s%4*.1;s===0||s===5?m=1.35:s%7==0&&(m=.68);let h=`pine`;if(a===`pines`)h=s%6==0?`birch`:`pine`;else if(a===`oaks`)h=s===0||s===5?`ancient_oak`:s%5==0?`birch`:`oak`;else if(a===`willows`)h=s%3==0?`willow`:s%4==0?`birch`:`oak`;else if(a===`highland_spruce`)h=s%5==0?`pine`:`spruce`;else{let e=s%5;h=e===0?`ancient_oak`:e===1?`pine`:e===2?`oak`:e===3?`spruce`:`birch`}o.push({x:f,y:p,scale:m,type:h,seed:Math.round(e*7+t*11+s*31)})}return o}function G(e){if(e.length===0)return``;if(e.length===1)return`M ${e[0].x},${e[0].y}`;let t=`M ${e[0].x},${e[0].y}`;for(let n=0;n<e.length-1;n++){let r=e[n],i=e[n+1],a=(r.x+i.x)/2,o=(r.y+i.y)/2;if(n===0)t+=` Q ${r.x},${r.y} ${a},${o}`;else{let a=e[n-1],o=r.x+(i.x-a.x)*.18,s=r.y+(i.y-a.y)*.18;t+=` S ${o},${s} ${i.x},${i.y}`}}return t}function K(e,t){return t<=0||e.length===0?``:G(e.slice(0,t+1))}var ue={parchment:{id:`parchment`,name:`Daylight Parchment`,bgClass:`parchment-bg`,textColor:`#2c221a`,pencilColor:`#382e25`,pencilShade:`#8c765c`,riverColor:`#96afbe`,glowColor:`#f59e0b`,glowSubtle:`#fbbf24`,nodeUnlit:`#f0e5ce`,nodeLit:`#fbbf24`,nodeLitStroke:`#ffffff`},dark_parchment:{id:`dark_parchment`,name:`Midnight Cartography`,bgClass:`parchment-dark-bg`,textColor:`#f3e9d2`,pencilColor:`#8a7761`,pencilShade:`#4a3f33`,riverColor:`#365163`,glowColor:`#fbbf24`,glowSubtle:`#f59e0b`,nodeUnlit:`#231e17`,nodeLit:`#f59e0b`,nodeLitStroke:`#fffbeb`}},q=new class{ctx=null;enabled=!0;initCtx(){if(!this.ctx&&typeof window<`u`){let e=window.AudioContext||window.webkitAudioContext;e&&(this.ctx=new e)}this.ctx&&this.ctx.state===`suspended`&&this.ctx.resume()}setEnabled(e){this.enabled=e,e&&this.initCtx()}isEnabled(){return this.enabled}playNodeLightUp(e,t=150){if(this.enabled&&(this.initCtx(),this.ctx))try{let n=this.ctx.currentTime,r=[261.63,293.66,329.63,392,440,523.25,587.33,659.25,783.99,880],i=Math.floor(e/Math.max(1,t)*20),a=1+Math.floor(i/r.length)*.5,o=r[i%r.length]*a,s=this.ctx.createOscillator(),c=this.ctx.createOscillator(),l=this.ctx.createGain();s.type=`sine`,s.frequency.setValueAtTime(o,n),c.type=`triangle`,c.frequency.setValueAtTime(o*2.01,n),l.gain.setValueAtTime(.001,n),l.gain.linearRampToValueAtTime(.12,n+.02),l.gain.exponentialRampToValueAtTime(1e-4,n+.55),s.connect(l),c.connect(l),l.connect(this.ctx.destination),s.start(n),c.start(n),s.stop(n+.6),c.stop(n+.6)}catch{}}playPencilScratch(){if(this.enabled&&(this.initCtx(),this.ctx))try{let e=this.ctx.currentTime,t=Math.floor(this.ctx.sampleRate*.06),n=this.ctx.createBuffer(1,t,this.ctx.sampleRate),r=n.getChannelData(0);for(let e=0;e<t;e++)r[e]=(Math.random()*2-1)*Math.exp(-e/(t*.4));let i=this.ctx.createBufferSource();i.buffer=n;let a=this.ctx.createBiquadFilter();a.type=`bandpass`,a.frequency.setValueAtTime(1400+Math.random()*800,e),a.Q.setValueAtTime(3.5,e);let o=this.ctx.createGain();o.gain.setValueAtTime(.04,e),o.gain.exponentialRampToValueAtTime(.001,e+.05),i.connect(a),a.connect(o),o.connect(this.ctx.destination),i.start(e)}catch{}}playVictoryChime(){this.enabled&&(this.initCtx(),this.ctx&&[523.25,659.25,783.99,1046.5].forEach((e,t)=>{setTimeout(()=>{if(!this.ctx)return;let t=this.ctx.currentTime,n=this.ctx.createOscillator(),r=this.ctx.createGain();n.type=`sine`,n.frequency.setValueAtTime(e,t),r.gain.setValueAtTime(.001,t),r.gain.linearRampToValueAtTime(.15,t+.05),r.gain.exponentialRampToValueAtTime(1e-4,t+1.2),n.connect(r),r.connect(this.ctx.destination),n.start(t),n.stop(t+1.3)},t*120)}))}},J=r();function Y(e){let t=Math.sin(e*12.9898+78.233)*43758.5453;return t-Math.floor(t)}var de=({mountain:e,theme:t})=>{let n=t.id!==`parchment`,r=t.pencilColor,i=t.pencilShade,{id:a,x:o,y:s,size:c,height:l,ridgeShift:u=0,hasSnow:d=l>95}=e,f=(0,I.useMemo)(()=>{let e=0;for(let t=0;t<a.length;t++)e+=a.charCodeAt(t)*(t+1);e+=Math.round(o+s);let t=o+u,n=s-l,r=o-c,i=o+c,f=[{x:t,y:n}];for(let i=1;i<=6;i++){let a=i/6,o=t-(t-r)*a**.92,s=n+l*a,u=(Y(e+i*17)-.48)*(c*.14)*Math.sin(a*Math.PI),d=Y(e+i*31)>.65?l*.035:0;f.push({x:Math.round(o+u),y:Math.round(s+d)})}let p=[{x:t,y:n}];for(let r=1;r<=6;r++){let a=r/6,o=t+(i-t)*a**.92,s=n+l*a,u=(Y(e+r*43)-.48)*(c*.14)*Math.sin(a*Math.PI),d=Y(e+r*59)>.65?l*.035:0;p.push({x:Math.round(o+u),y:Math.round(s+d)})}let m=[{x:t,y:n}];for(let r=1;r<=7;r++){let i=r/7,a=t+(o+u*.25+(Y(e+101)-.5)*(c*.18)-t)*i**1.15,s=n+l*i,d=Math.sin(i*Math.PI*2.2+Y(e+113))*(c*.09);m.push({x:Math.round(a+d),y:Math.round(s)})}let h=[],g=m[2];if(g){let t=o+c*.52+(Y(e+201)-.5)*14,n=s-l*.16,r=(g.x+t)/2+10,i=(g.y+n)/2-5;h.push({d:`M ${g.x},${g.y} Q ${r},${i} ${t},${n}`,side:`right`})}let _=m[3];if(_){let t=o-c*.55+(Y(e+301)-.5)*14,n=s-l*.14,r=(_.x+t)/2-8,i=(_.y+n)/2-4;h.push({d:`M ${_.x},${_.y} Q ${r},${i} ${t},${n}`,side:`left`})}let v=[],y=Math.max(12,Math.round(l/5.2));for(let r=1;r<=y;r++){let a=r/(y+1),o=m[Math.min(m.length-1,Math.max(0,Math.round(a*(m.length-1))))],c=n+l*a,u=p[Math.min(p.length-1,Math.max(0,Math.round(a*(p.length-1))))]||{x:t+(i-t)*a,y:c},d=o.x+(u.x-o.x)*.05,f=c+(Y(e+r*71)-.5)*2,h=r%3==0?.88:r%2==0?.68:.48,g=d+(u.x-d)*h,_=(c-n)*.18+(u.y-c)*.3,b=Math.min(s+2,f+_+(Y(e+r*83)-.5)*3);v.push({x1:Math.round(d),y1:Math.round(f),x2:Math.round(g),y2:Math.round(b),width:r<4?.85:1.15,opacity:(1-a*.35)*.8})}let b=[],x=Math.max(4,Math.round(l/20));for(let i=1;i<=x;i++){let a=(i+.25)/(x+1),o=n+l*a,s=m[Math.min(m.length-1,Math.round(a*(m.length-1)))],c=f[Math.min(f.length-1,Math.round(a*(f.length-1)))]||{x:t-(t-r)*a,y:o},u=s.x-(s.x-c.x)*.12,d=o+1,p=s.x-(s.x-c.x)*(.45+Y(e+i*97)*.25),h=o+6+Y(e+i*103)*5,g=(u+p)/2-3,_=(d+h)/2+2;b.push({d:`M ${Math.round(u)},${Math.round(d)} Q ${Math.round(g)},${Math.round(_)} ${Math.round(p)},${Math.round(h)}`,width:.85})}let S=``;if(d){let e=f[2]||f[1],r=m[2]||m[1],i=p[2]||p[1];S=`M ${t},${n}L ${f[1].x},${f[1].y}L ${e.x},${e.y}Q ${(e.x+r.x)/2},${e.y-5} ${r.x},${r.y+3}
1234const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/KatexRenderer-DVt2cqHc.js","assets/rolldown-runtime-hePW80VL.js","assets/vendor-react-hnaVBnLv.js","assets/vendor-codemirror-By0wlJeM.js","assets/vendor-katex-Balf574a.js","assets/vendor-katex-DtkCqjBQ.css"])))=>i.map(i=>d[i]);import{r as e}from"./rolldown-runtime-hePW80VL.js";import{Bt as t,Ht as n}from"./vendor-react-hnaVBnLv.js";import{t as r}from"./index-DVWZ15xt.js";var i=e(n(),1),a=t(),o=(0,i.lazy)(()=>r(()=>import(`./KatexRenderer-DVt2cqHc.js`),__vite__mapDeps([0,1,2,3,4,5])));function s(e){return e?e.split(/(\$\$[\s\S]*?\$\$|\\\[[\s\S]*?\\\]|\\\([\s\S]*?\\\)|\$(?:\\\$|[^$\n])+?\$|`[^`\n]+`|\*\*[^*\n]+\*\*|__[^_\n]+__|(?<!\*)\*[^*\n]+(?<!\*)\*|(?<!_)_[^_\n]+(?<!_)_|\[[^\]\n]+\]\([^)\n]+\))/g).map((e,t)=>{if(!e)return null;if(e.startsWith(`$$`)&&e.endsWith(`$$`)&&e.length>=4){let n=e.slice(2,-2);return n.trim()?(0,a.jsx)(i.Suspense,{fallback:(0,a.jsx)(`span`,{className:`font-mono text-xs opacity-75`,children:n}),children:(0,a.jsx)(o,{math:n,displayMode:!0,className:`inline-block my-1 px-1 overflow-x-auto align-middle`})},t):e}if(e.startsWith(`\\[`)&&e.endsWith(`\\]`)&&e.length>=4){let n=e.slice(2,-2);return n.trim()?(0,a.jsx)(i.Suspense,{fallback:(0,a.jsx)(`span`,{className:`font-mono text-xs opacity-75`,children:n}),children:(0,a.jsx)(o,{math:n,displayMode:!0,className:`inline-block my-1 px-1 overflow-x-auto align-middle`})},t):e}if(e.startsWith(`\\(`)&&e.endsWith(`\\)`)&&e.length>=4){let n=e.slice(2,-2);return n.trim()?(0,a.jsx)(i.Suspense,{fallback:(0,a.jsx)(`span`,{className:`font-mono text-xs opacity-75`,children:n}),children:(0,a.jsx)(o,{math:n,displayMode:!1,className:`inline-katex px-0.5 align-baseline`})},t):e}if(e.startsWith(`$`)&&e.endsWith(`$`)&&e.length>=2){let n=e.slice(1,-1);return n.trim()?(0,a.jsx)(i.Suspense,{fallback:(0,a.jsx)(`span`,{className:`font-mono text-xs opacity-75`,children:n}),children:(0,a.jsx)(o,{math:n,displayMode:!1,className:`inline-katex px-0.5 align-baseline`})},t):e}if(e.startsWith("`")&&e.endsWith("`")&&e.length>=2)return(0,a.jsx)(`code`,{className:`bg-[#1E293B] text-[#4ADE80] px-1.5 py-0.5 rounded text-[11px] font-mono border border-ink-black shadow-[1px_1px_0px_0px_#000]`,children:e.slice(1,-1)},t);if(e.startsWith(`**`)&&e.endsWith(`**`)&&e.length>=4||e.startsWith(`__`)&&e.endsWith(`__`)&&e.length>=4)return(0,a.jsx)(`strong`,{className:`text-ink-black font-extrabold`,children:s(e.slice(2,-2))},t);if(e.startsWith(`*`)&&e.endsWith(`*`)&&e.length>=2||e.startsWith(`_`)&&e.endsWith(`_`)&&e.length>=2)return(0,a.jsx)(`em`,{className:`italic text-slate-800`,children:s(e.slice(1,-1))},t);let n=e.match(/^\[([^\]]+)\]\(([^)]+)\)$/);return n?(0,a.jsx)(`a`,{href:n[2],target:`_blank`,rel:`noopener noreferrer`,className:`text-primary underline hover:text-primary/80 font-bold`,children:n[1]},t):e}):[]}var c=(0,i.lazy)(()=>r(()=>import(`./KatexRenderer-DVt2cqHc.js`),__vite__mapDeps([0,1,2,3,4,5]))),l=({content:e,className:t=``})=>{if(!e)return null;let n=e.split(/(```[\s\S]*?```|\$\$[\s\S]*?\$\$|\\\[[\s\S]*?\\\])/g);return(0,a.jsx)(`div`,{className:`markdown-content space-y-2.5 text-ink-black text-xs leading-relaxed font-sans ${t}`,children:n.map((e,t)=>{if(!e)return null;let n=e.trim();if(n.startsWith("```")&&n.endsWith("```")&&n.length>=6){let e=n.indexOf(``),r=e===-1?``:n.slice(3,e).trim(),i=e===-1?n.slice(3,-3).trim():n.slice(e+1,-3).trimEnd();return(0,a.jsxs)(`div`,{className:`my-3 rounded-md overflow-hidden border-[2px] border-ink-black shadow-[3px_3px_0px_0px_#1E293B] bg-[#1E293B]`,children:[r&&(0,a.jsxs)(`div`,{className:`bg-slate-800 text-slate-400 px-3 py-1 text-[9px] font-arcade uppercase tracking-wider border-b border-slate-700 flex justify-between items-center`,children:[(0,a.jsx)(`span`,{children:r}),(0,a.jsx)(`span`,{className:`text-[8px] opacity-70`,children:`SNIPPET`})]}),(0,a.jsx)(`pre`,{className:`p-3 overflow-x-auto font-mono text-[11px] text-[#4ADE80] leading-relaxed custom-scrollbar selection:bg-[#4ADE80] selection:text-[#1E293B]`,children:(0,a.jsx)(`code`,{children:i})})]},`code-${t}`)}if(n.startsWith(`$$`)&&n.endsWith(`$$`)&&n.length>=4||n.startsWith(`\\[`)&&n.endsWith(`\\]`)&&n.length>=4){let e=n.slice(2,-2);return(0,a.jsx)(`div`,{className:`my-3 p-3 bg-slate-50 border-2 border-ink-black rounded overflow-x-auto text-center shadow-[2px_2px_0px_0px_rgba(30,41,59,0.3)] custom-scrollbar`,children:(0,a.jsx)(i.Suspense,{fallback:(0,a.jsx)(`span`,{className:`font-mono text-xs opacity-75`,children:e}),children:(0,a.jsx)(c,{math:e,displayMode:!0})})},`math-${t}`)}let r=e.split(``),o=[],l=0;for(;l<r.length;){let e=r[l],n=e.trim(),i=`${t}-${l}`;if(n===``){o.push((0,a.jsx)(`div`,{className:`h-1`},i)),l++;continue}if(n.startsWith(`|`)&&n.endsWith(`|`)&&l+1<r.length&&r[l+1].trim().startsWith(`|`)){let e=[];for(;l<r.length&&r[l].trim().startsWith(`|`)&&r[l].trim().endsWith(`|`);)e.push(r[l].trim()),l++;if(e.length>=2){let t=e[0].slice(1,-1).split(`|`).map(e=>e.trim()),n=e.slice(2).map(e=>e.slice(1,-1).split(`|`).map(e=>e.trim()));o.push((0,a.jsx)(`div`,{className:`my-3 overflow-x-auto border-2 border-ink-black rounded shadow-[2px_2px_0px_0px_#1E293B]`,children:(0,a.jsxs)(`table`,{className:`w-full text-left border-collapse text-xs`,children:[(0,a.jsx)(`thead`,{children:(0,a.jsx)(`tr`,{className:`bg-slate-200 border-b-2 border-ink-black`,children:t.map((e,t)=>(0,a.jsx)(`th`,{className:`p-2 font-bold font-headline-md border-r last:border-r-0 border-ink-black`,children:s(e)},t))})}),(0,a.jsx)(`tbody`,{children:n.map((e,t)=>(0,a.jsx)(`tr`,{className:`border-b border-slate-300 last:border-b-0 ${t%2==1?`bg-slate-50`:`bg-white`}`,children:e.map((e,t)=>(0,a.jsx)(`td`,{className:`p-2 border-r last:border-r-0 border-slate-200 font-medium`,children:s(e)},t))},t))})]})},`table-${i}`));continue}}if(n.startsWith(`#### `)){o.push((0,a.jsx)(`h4`,{className:`text-xs font-bold text-ink-black mt-3 mb-1 font-headline-md`,children:s(n.substring(5))},i)),l++;continue}if(n.startsWith(`### `)){o.push((0,a.jsxs)(`h3`,{className:`text-xs font-bold text-primary mt-4 mb-1.5 uppercase font-arcade tracking-wide flex items-center gap-1.5`,children:[(0,a.jsx)(`span`,{className:`w-2 h-2 bg-primary inline-block rounded-xs`}),s(n.substring(4))]},i)),l++;continue}if(n.startsWith(`## `)){o.push((0,a.jsx)(`h2`,{className:`text-sm font-extrabold text-ink-black mt-4 mb-2 font-headline-md border-b-2 border-ink-black pb-1`,children:s(n.substring(3))},i)),l++;continue}if(n.startsWith(`# `)){o.push((0,a.jsx)(`h1`,{className:`text-base font-black text-ink-black mt-5 mb-2 font-headline-md`,children:s(n.substring(2))},i)),l++;continue}if(n===`---`||n===`***`||n===`___`){o.push((0,a.jsx)(`hr`,{className:`my-3 border-t-2 border-dashed border-slate-300`},i)),l++;continue}if(e.trim().startsWith(`>`)){o.push((0,a.jsx)(`blockquote`,{className:`border-l-4 border-primary pl-3 py-1 my-2 bg-slate-50 italic text-slate-700`,children:s(e.trim().substring(1).trim())},i)),l++;continue}if(n.startsWith(`- `)||n.startsWith(`* `)||n.startsWith(`+ `)){let t=e.search(/\S/)>=2?`pl-6`:`pl-2`;o.push((0,a.jsxs)(`div`,{className:`flex items-start gap-2 my-1 ${t}`,children:[(0,a.jsx)(`span`,{className:`text-primary font-bold mt-0.5 shrink-0`,children:`•`}),(0,a.jsx)(`div`,{className:`text-ink-black leading-relaxed flex-1 font-medium`,children:s(n.substring(2))})]},i)),l++;continue}let c=n.match(/^(\d+)\.\s+(.*)$/);if(c){let t=e.search(/\S/)>=2?`pl-6`:`pl-2`;o.push((0,a.jsxs)(`div`,{className:`flex items-start gap-2 my-1 ${t}`,children:[(0,a.jsx)(`span`,{className:`text-primary font-arcade text-[9px] font-bold mt-1 shrink-0 px-1 py-0.2 bg-slate-100 border border-ink-black rounded-xs`,children:c[1]}),(0,a.jsx)(`div`,{className:`text-ink-black leading-relaxed flex-1 font-medium`,children:s(c[2])})]},i)),l++;continue}o.push((0,a.jsx)(`p`,{className:`text-ink-black my-1 font-medium leading-relaxed`,children:s(e)},i)),l++}return(0,a.jsx)(i.Fragment,{children:o},`block-${t}`)})})};export{s as n,l as t};1234const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/KatexRenderer-DVt2cqHc.js","assets/rolldown-runtime-hePW80VL.js","assets/vendor-react-hnaVBnLv.js","assets/vendor-codemirror-By0wlJeM.js","assets/vendor-katex-Balf574a.js","assets/vendor-katex-DtkCqjBQ.css"])))=>i.map(i=>d[i]);import{r as e}from"./rolldown-runtime-hePW80VL.js";import{Bt as t,Ht as n}from"./vendor-react-hnaVBnLv.js";import{t as r}from"./index-Q9onQHft.js";var i=e(n(),1),a=t(),o=(0,i.lazy)(()=>r(()=>import(`./KatexRenderer-DVt2cqHc.js`),__vite__mapDeps([0,1,2,3,4,5])));function s(e){return e?e.split(/(\$\$[\s\S]*?\$\$|\\\[[\s\S]*?\\\]|\\\([\s\S]*?\\\)|\$(?:\\\$|[^$\n])+?\$|`[^`\n]+`|\*\*[^*\n]+\*\*|__[^_\n]+__|(?<!\*)\*[^*\n]+(?<!\*)\*|(?<!_)_[^_\n]+(?<!_)_|\[[^\]\n]+\]\([^)\n]+\))/g).map((e,t)=>{if(!e)return null;if(e.startsWith(`$$`)&&e.endsWith(`$$`)&&e.length>=4){let n=e.slice(2,-2);return n.trim()?(0,a.jsx)(i.Suspense,{fallback:(0,a.jsx)(`span`,{className:`font-mono text-xs opacity-75`,children:n}),children:(0,a.jsx)(o,{math:n,displayMode:!0,className:`inline-block my-1 px-1 overflow-x-auto align-middle`})},t):e}if(e.startsWith(`\\[`)&&e.endsWith(`\\]`)&&e.length>=4){let n=e.slice(2,-2);return n.trim()?(0,a.jsx)(i.Suspense,{fallback:(0,a.jsx)(`span`,{className:`font-mono text-xs opacity-75`,children:n}),children:(0,a.jsx)(o,{math:n,displayMode:!0,className:`inline-block my-1 px-1 overflow-x-auto align-middle`})},t):e}if(e.startsWith(`\\(`)&&e.endsWith(`\\)`)&&e.length>=4){let n=e.slice(2,-2);return n.trim()?(0,a.jsx)(i.Suspense,{fallback:(0,a.jsx)(`span`,{className:`font-mono text-xs opacity-75`,children:n}),children:(0,a.jsx)(o,{math:n,displayMode:!1,className:`inline-katex px-0.5 align-baseline`})},t):e}if(e.startsWith(`$`)&&e.endsWith(`$`)&&e.length>=2){let n=e.slice(1,-1);return n.trim()?(0,a.jsx)(i.Suspense,{fallback:(0,a.jsx)(`span`,{className:`font-mono text-xs opacity-75`,children:n}),children:(0,a.jsx)(o,{math:n,displayMode:!1,className:`inline-katex px-0.5 align-baseline`})},t):e}if(e.startsWith("`")&&e.endsWith("`")&&e.length>=2)return(0,a.jsx)(`code`,{className:`bg-[#1E293B] text-[#4ADE80] px-1.5 py-0.5 rounded text-[11px] font-mono border border-ink-black shadow-[1px_1px_0px_0px_#000]`,children:e.slice(1,-1)},t);if(e.startsWith(`**`)&&e.endsWith(`**`)&&e.length>=4||e.startsWith(`__`)&&e.endsWith(`__`)&&e.length>=4)return(0,a.jsx)(`strong`,{className:`text-ink-black font-extrabold`,children:s(e.slice(2,-2))},t);if(e.startsWith(`*`)&&e.endsWith(`*`)&&e.length>=2||e.startsWith(`_`)&&e.endsWith(`_`)&&e.length>=2)return(0,a.jsx)(`em`,{className:`italic text-slate-800`,children:s(e.slice(1,-1))},t);let n=e.match(/^\[([^\]]+)\]\(([^)]+)\)$/);return n?(0,a.jsx)(`a`,{href:n[2],target:`_blank`,rel:`noopener noreferrer`,className:`text-primary underline hover:text-primary/80 font-bold`,children:n[1]},t):e}):[]}var c=(0,i.lazy)(()=>r(()=>import(`./KatexRenderer-DVt2cqHc.js`),__vite__mapDeps([0,1,2,3,4,5]))),l=({content:e,className:t=``})=>{if(!e)return null;let n=e.split(/(```[\s\S]*?```|\$\$[\s\S]*?\$\$|\\\[[\s\S]*?\\\])/g);return(0,a.jsx)(`div`,{className:`markdown-content space-y-2.5 text-ink-black text-xs leading-relaxed font-sans ${t}`,children:n.map((e,t)=>{if(!e)return null;let n=e.trim();if(n.startsWith("```")&&n.endsWith("```")&&n.length>=6){let e=n.indexOf(``),r=e===-1?``:n.slice(3,e).trim(),i=e===-1?n.slice(3,-3).trim():n.slice(e+1,-3).trimEnd();return(0,a.jsxs)(`div`,{className:`my-3 rounded-md overflow-hidden border-[2px] border-ink-black shadow-[3px_3px_0px_0px_#1E293B] bg-[#1E293B]`,children:[r&&(0,a.jsxs)(`div`,{className:`bg-slate-800 text-slate-400 px-3 py-1 text-[9px] font-arcade uppercase tracking-wider border-b border-slate-700 flex justify-between items-center`,children:[(0,a.jsx)(`span`,{children:r}),(0,a.jsx)(`span`,{className:`text-[8px] opacity-70`,children:`SNIPPET`})]}),(0,a.jsx)(`pre`,{className:`p-3 overflow-x-auto font-mono text-[11px] text-[#4ADE80] leading-relaxed custom-scrollbar selection:bg-[#4ADE80] selection:text-[#1E293B]`,children:(0,a.jsx)(`code`,{children:i})})]},`code-${t}`)}if(n.startsWith(`$$`)&&n.endsWith(`$$`)&&n.length>=4||n.startsWith(`\\[`)&&n.endsWith(`\\]`)&&n.length>=4){let e=n.slice(2,-2);return(0,a.jsx)(`div`,{className:`my-3 p-3 bg-slate-50 border-2 border-ink-black rounded overflow-x-auto text-center shadow-[2px_2px_0px_0px_rgba(30,41,59,0.3)] custom-scrollbar`,children:(0,a.jsx)(i.Suspense,{fallback:(0,a.jsx)(`span`,{className:`font-mono text-xs opacity-75`,children:e}),children:(0,a.jsx)(c,{math:e,displayMode:!0})})},`math-${t}`)}let r=e.split(``),o=[],l=0;for(;l<r.length;){let e=r[l],n=e.trim(),i=`${t}-${l}`;if(n===``){o.push((0,a.jsx)(`div`,{className:`h-1`},i)),l++;continue}if(n.startsWith(`|`)&&n.endsWith(`|`)&&l+1<r.length&&r[l+1].trim().startsWith(`|`)){let e=[];for(;l<r.length&&r[l].trim().startsWith(`|`)&&r[l].trim().endsWith(`|`);)e.push(r[l].trim()),l++;if(e.length>=2){let t=e[0].slice(1,-1).split(`|`).map(e=>e.trim()),n=e.slice(2).map(e=>e.slice(1,-1).split(`|`).map(e=>e.trim()));o.push((0,a.jsx)(`div`,{className:`my-3 overflow-x-auto border-2 border-ink-black rounded shadow-[2px_2px_0px_0px_#1E293B]`,children:(0,a.jsxs)(`table`,{className:`w-full text-left border-collapse text-xs`,children:[(0,a.jsx)(`thead`,{children:(0,a.jsx)(`tr`,{className:`bg-slate-200 border-b-2 border-ink-black`,children:t.map((e,t)=>(0,a.jsx)(`th`,{className:`p-2 font-bold font-headline-md border-r last:border-r-0 border-ink-black`,children:s(e)},t))})}),(0,a.jsx)(`tbody`,{children:n.map((e,t)=>(0,a.jsx)(`tr`,{className:`border-b border-slate-300 last:border-b-0 ${t%2==1?`bg-slate-50`:`bg-white`}`,children:e.map((e,t)=>(0,a.jsx)(`td`,{className:`p-2 border-r last:border-r-0 border-slate-200 font-medium`,children:s(e)},t))},t))})]})},`table-${i}`));continue}}if(n.startsWith(`#### `)){o.push((0,a.jsx)(`h4`,{className:`text-xs font-bold text-ink-black mt-3 mb-1 font-headline-md`,children:s(n.substring(5))},i)),l++;continue}if(n.startsWith(`### `)){o.push((0,a.jsxs)(`h3`,{className:`text-xs font-bold text-primary mt-4 mb-1.5 uppercase font-arcade tracking-wide flex items-center gap-1.5`,children:[(0,a.jsx)(`span`,{className:`w-2 h-2 bg-primary inline-block rounded-xs`}),s(n.substring(4))]},i)),l++;continue}if(n.startsWith(`## `)){o.push((0,a.jsx)(`h2`,{className:`text-sm font-extrabold text-ink-black mt-4 mb-2 font-headline-md border-b-2 border-ink-black pb-1`,children:s(n.substring(3))},i)),l++;continue}if(n.startsWith(`# `)){o.push((0,a.jsx)(`h1`,{className:`text-base font-black text-ink-black mt-5 mb-2 font-headline-md`,children:s(n.substring(2))},i)),l++;continue}if(n===`---`||n===`***`||n===`___`){o.push((0,a.jsx)(`hr`,{className:`my-3 border-t-2 border-dashed border-slate-300`},i)),l++;continue}if(e.trim().startsWith(`>`)){o.push((0,a.jsx)(`blockquote`,{className:`border-l-4 border-primary pl-3 py-1 my-2 bg-slate-50 italic text-slate-700`,children:s(e.trim().substring(1).trim())},i)),l++;continue}if(n.startsWith(`- `)||n.startsWith(`* `)||n.startsWith(`+ `)){let t=e.search(/\S/)>=2?`pl-6`:`pl-2`;o.push((0,a.jsxs)(`div`,{className:`flex items-start gap-2 my-1 ${t}`,children:[(0,a.jsx)(`span`,{className:`text-primary font-bold mt-0.5 shrink-0`,children:`•`}),(0,a.jsx)(`div`,{className:`text-ink-black leading-relaxed flex-1 font-medium`,children:s(n.substring(2))})]},i)),l++;continue}let c=n.match(/^(\d+)\.\s+(.*)$/);if(c){let t=e.search(/\S/)>=2?`pl-6`:`pl-2`;o.push((0,a.jsxs)(`div`,{className:`flex items-start gap-2 my-1 ${t}`,children:[(0,a.jsx)(`span`,{className:`text-primary font-arcade text-[9px] font-bold mt-1 shrink-0 px-1 py-0.2 bg-slate-100 border border-ink-black rounded-xs`,children:c[1]}),(0,a.jsx)(`div`,{className:`text-ink-black leading-relaxed flex-1 font-medium`,children:s(c[2])})]},i)),l++;continue}o.push((0,a.jsx)(`p`,{className:`text-ink-black my-1 font-medium leading-relaxed`,children:s(e)},i)),l++}return(0,a.jsx)(i.Fragment,{children:o},`block-${t}`)})})};export{s as n,l as t};
1import{n as e,r as t}from"./rolldown-runtime-hePW80VL.js";import{A as n,Bt as r,Ct as i,D as a,G as o,Ht as s,R as c,Tt as l,a as u,c as d,dt as f,ht as p,j as m,l as h,o as g,p as _,w as v,x as y}from"./vendor-react-hnaVBnLv.js";import{C as b,S as x,T as S,_ as C,b as w,g as T,v as E,w as D,x as O,y as k}from"./index-Q9onQHft.js";var A=t(s(),1),j={1:{particleType:`pollen`,particleCount:16,particleColors:[`#FDE047`,`#FEF08A`,`#86EFAC`],gradientBg:`from-[#FFFDF0] via-[#FFF9E6] to-[#FEF3C7]`,glowColor:`rgba(251, 191, 36, 0.3)`,badgeLabel:`🌾 Plains Breeze`},2:{particleType:`leaves`,particleCount:18,particleColors:[`#86EFAC`,`#4ADE80`,`#22C55E`,`#A7F3D0`],gradientBg:`from-[#F0FDF4] via-[#DCFCE7] to-[#FEF9C3]`,glowColor:`rgba(34, 197, 94, 0.3)`,badgeLabel:`🍃 Whispering Leaves`},3:{particleType:`spores`,particleCount:22,particleColors:[`#67E8F9`,`#38BDF8`,`#818CF8`,`#C084FC`],gradientBg:`from-[#F0F9FF] via-[#E0F2FE] to-[#EDE9FE]`,glowColor:`rgba(56, 189, 248, 0.35)`,badgeLabel:`✨ Crystal Spores`},4:{particleType:`snow`,particleCount:28,particleColors:[`#FFFFFF`,`#E0F2FE`,`#BAE6FD`],gradientBg:`from-[#F8FAFC] via-[#F1F5F9] to-[#E2E8F0]`,glowColor:`rgba(186, 230, 253, 0.4)`,badgeLabel:`❄️ Alpine Snowfall`},5:{particleType:`runes`,particleCount:20,particleColors:[`#E879F9`,`#C084FC`,`#A855F7`,`#F472B6`],gradientBg:`from-[#FAF5FF] via-[#F3E8FF] to-[#FCE7F3]`,glowColor:`rgba(192, 132, 252, 0.4)`,badgeLabel:`🔮 Arcane Runes`},6:{particleType:`stardust`,particleCount:35,particleColors:[`#FDE047`,`#F59E0B`,`#E11D48`,`#818CF8`],gradientBg:`from-[#FFFBEB] via-[#FEF3C7] to-[#FFE4E6]`,glowColor:`rgba(245, 158, 11, 0.5)`,badgeLabel:`✨ Tower of the Elixir`}};function M(e){return e<=30?j[1]:e<=60?j[2]:e<=90?j[3]:e<=120?j[4]:e<150?j[5]:j[6]}var N=r();function P({emotion:e,floor:t,rhythm:n,activity:r,isLoading:i=!1,className:a=``,onClick:o}){let s=E[e]||E.smiling_warmly,c=(0,A.useMemo)(()=>M(t),[t]),l=(0,A.useMemo)(()=>{switch(n){case`dawn`:return`from-amber-400/30 via-yellow-300/20 to-transparent`;case`dusk`:return`from-orange-500/30 via-purple-500/20 to-transparent`;case`night`:return`from-indigo-600/30 via-blue-500/20 to-transparent`;default:return`from-amber-300/25 via-sky-300/20 to-transparent`}},[n]);return(0,N.jsxs)(`div`,{onClick:o,className:`relative flex flex-col items-center justify-end select-none pointer-events-auto transition-transform ${a}`,children:[(0,N.jsx)(`div`,{className:`absolute -inset-10 overflow-hidden pointer-events-none z-0`,children:Array.from({length:Math.min(16,c.particleCount)}).map((e,t)=>{let n=c.particleColors[t%c.particleColors.length],r=`${t*17%100}%`,i=`${7+t%5*2}s`,a=`${t*.8%4}s`,o=c.particleType===`leaves`||c.particleType===`runes`?`w-2 h-2`:`w-1.5 h-1.5`;return(0,N.jsx)(`span`,{className:`absolute rounded-full opacity-60 animate-pulse ${o}`,style:{backgroundColor:n,left:r,top:`${t*21%90}%`,boxShadow:`0 0 10px ${n}`,animationDuration:i,animationDelay:a}},t)})}),(0,N.jsx)(`div`,{className:`absolute bottom-4 inset-x-0 h-48 sm:h-72 md:h-96 bg-radial ${l} blur-2xl opacity-70 pointer-events-none z-0`}),(0,N.jsxs)(`div`,{className:`relative z-10 flex flex-col items-start justify-end`,children:[r&&(0,N.jsx)(`div`,{className:`mb-2 max-w-[120px] sm:max-w-xs text-center pointer-events-none animate-in fade-in duration-300`,children:(0,N.jsxs)(`span`,{className:`text-[9px] sm:text-[10px] font-mono font-medium text-[#bfe1ff] bg-[#101e2e]/85 px-2 sm:px-2.5 py-0.5 rounded-full border border-[#3e6080]/70 shadow-md inline-flex items-center gap-1 sm:gap-1.5 backdrop-blur-xs`,children:[(0,N.jsx)(`span`,{className:`text-amber-400`,children:`⛺`}),(0,N.jsx)(`span`,{className:`truncate`,children:r})]})}),(0,N.jsx)(`div`,{className:`relative h-[28vh] sm:h-[40vh] md:h-[46vh] lg:h-[50vh] max-h-[220px] sm:max-h-[380px] md:max-h-[460px] lg:max-h-[500px] min-h-[160px] sm:min-h-[240px] md:min-h-[300px] w-auto max-w-[110px] sm:max-w-[200px] md:max-w-[270px] lg:max-w-[320px] flex items-end justify-end`,children:(0,N.jsx)(`img`,{src:s.imagePath,alt:s.label,loading:`eager`,className:`h-full w-auto max-h-[85vh] object-contain object-bottom-left drop-shadow-[0_16px_32px_rgba(0,0,0,0.55)] transition-all duration-300 ${i?`scale-[1.02] filter brightness-110 saturate-125`:`scale-100`}`,onError:e=>{let t=e.currentTarget;t.src.endsWith(`/sprites/princess/smiling_warmly.webp`)?t.src.endsWith(`/sprites/princess/neutral.webp`)||(t.src=`/sprites/princess/neutral.webp`):t.src=`/sprites/princess/smiling_warmly.webp`}})})]})]})}var F=[`How is your strength holding up today?`,`Let us rest by the fire for a moment.`,`We made good progress toward the Tower today.`],I={backgroundColor:`rgba(20, 36, 54, 0.94)`,boxShadow:`0 0 0 2px #0a1420, inset 0 0 0 3px #4c7396, inset 1px 1px 0 4px #8db7dc, inset -1px -1px 0 4px #1a2c3f, inset 0 0 0 5px #0c1724, 0 10px 28px rgba(0, 0, 0, 0.75)`};function L({characterName:e,text:t,isStreaming:n=!1,isLoading:r=!1,choices:o,toolCalls:s,onSelectChoice:l,onSendMessage:u,onTypingStatusChange:f,currentFloor:p,bondTier:_,satchelCount:v=0,isMuted:b=!1,onToggleMute:S,onOpenProgress:C,onOpenSatchel:w,onOpenHistory:T,onMinimize:E,onClose:D,className:O=``}){let[k,j]=(0,A.useState)(``),[M,P]=(0,A.useState)(!1),[L,R]=(0,A.useState)(0),[z,B]=(0,A.useState)(``),[V,H]=(0,A.useState)(!1),U=(0,A.useRef)(t),W=(0,A.useRef)(!1),G=(0,A.useRef)(null),K=(0,A.useRef)(null),q=n||M;(0,A.useEffect)(()=>{f?.(q)},[q,f]);let J=(0,A.useMemo)(()=>{if(Array.isArray(o)&&o.length>0){let t=x(o,void 0,e);if(t.length>0)return t.slice(0,4)}return F},[o,e]),Y=L<J.length?L:0,X=!n&&M?k:t;(0,A.useEffect)(()=>{if(n){G.current&&=(clearInterval(G.current),null),W.current=!0,U.current=t;return}if(W.current){W.current=!1,U.current=t,G.current&&=(clearInterval(G.current),null);return}if(t!==U.current&&!r){if(U.current=t,!t){G.current&&=(clearInterval(G.current),null);return}G.current&&clearInterval(G.current);let e=0,n=setInterval(()=>{e++,j(t.slice(0,e)),P(!0),e>=t.length&&(clearInterval(n),G.current=null,P(!1))},20);return G.current=n,()=>{clearInterval(n),G.current=null,P(!1)}}},[t,r,n]);let Z=(0,A.useCallback)(()=>{G.current&&=(clearInterval(G.current),null),P(!1)},[]),Q=()=>{let e=z.trim();!e||r||n||(u(e),B(``))};return(0,A.useEffect)(()=>{let e=e=>{if(e.key===`Escape`&&D){e.preventDefault(),D();return}if(!V){if(e.key>=`1`&&e.key<=String(J.length)){let t=parseInt(e.key,10)-1;J[t]&&!r&&!n&&(e.preventDefault(),l(J[t]));return}if(e.key===`ArrowUp`){e.preventDefault(),R(e=>(e-1+J.length)%J.length);return}if(e.key===`ArrowDown`){e.preventDefault(),R(e=>(e+1)%J.length);return}if(e.key===`Enter`){!r&&!n&&J[Y]&&(e.preventDefault(),l(J[Y]));return}e.key===` `&&q&&(e.preventDefault(),Z())}};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[V,J,Y,r,n,q,l,Z,D]),(0,N.jsxs)(`div`,{className:`relative flex flex-col gap-2 w-full ${O}`,children:[(0,N.jsxs)(`div`,{onClick:Z,className:`relative w-full rounded-md sm:rounded-lg text-white pt-3.5 pb-3.5 pr-3.5 pl-8 sm:pt-5 sm:pb-5 sm:pr-5 sm:pl-14 md:pl-16 lg:pl-18 flex flex-col gap-2.5 backdrop-blur-md transition-all select-none cursor-pointer`,style:I,children:[(0,N.jsxs)(`div`,{className:`absolute -top-7 right-1 flex items-center gap-1 sm:gap-1.5 z-30`,onClick:e=>e.stopPropagation(),children:[C&&(0,N.jsxs)(`button`,{type:`button`,onClick:C,className:`px-2 py-0.5 bg-[#101e2e]/90 hover:bg-[#1f3750] border border-[#3e6080]/80 hover:border-[#67b1ec] rounded text-[10px] sm:text-[11px] font-mono font-bold text-[#8cb4db] hover:text-white transition-all cursor-pointer flex items-center gap-1 shadow-md`,title:`Road to the Tower (Leagues Progress)`,children:[(0,N.jsx)(i,{className:`w-3 h-3 text-amber-400`}),(0,N.jsxs)(`span`,{children:[p,`/150 Leagues`]})]}),w&&(0,N.jsxs)(`button`,{type:`button`,onClick:w,className:`px-2 py-0.5 bg-[#101e2e]/90 hover:bg-[#1f3750] border border-[#3e6080]/80 hover:border-[#67b1ec] rounded text-[10px] sm:text-[11px] font-mono font-bold text-[#8cb4db] hover:text-white transition-all cursor-pointer flex items-center gap-1 shadow-md`,title:`Open Royal Satchel`,children:[(0,N.jsx)(a,{className:`w-3 h-3 text-amber-400`}),(0,N.jsx)(`span`,{className:`hidden sm:inline`,children:`Satchel`}),v>0&&(0,N.jsxs)(`span`,{className:`text-[9px] text-[#f3cb65]`,children:[`(`,v,`)`]})]}),T&&(0,N.jsxs)(`button`,{type:`button`,onClick:T,className:`px-2 py-0.5 bg-[#101e2e]/90 hover:bg-[#1f3750] border border-[#3e6080]/80 hover:border-[#67b1ec] rounded text-[10px] sm:text-[11px] font-mono font-bold text-[#8cb4db] hover:text-white transition-all cursor-pointer flex items-center gap-1 shadow-md`,title:`Dialogue Transcript`,children:[(0,N.jsx)(m,{className:`w-3 h-3 text-[#8cb4db]`}),(0,N.jsx)(`span`,{className:`hidden sm:inline`,children:`Log`})]}),S&&(0,N.jsx)(`button`,{type:`button`,onClick:S,className:`p-1 bg-[#101e2e]/90 hover:bg-[#1f3750] border border-[#3e6080]/80 hover:border-[#67b1ec] rounded text-[#8cb4db] hover:text-white transition-all cursor-pointer shadow-md`,title:b?`Unmute Audio`:`Mute Audio`,children:b?(0,N.jsx)(d,{className:`w-3 h-3`}):(0,N.jsx)(h,{className:`w-3 h-3`})}),E&&(0,N.jsx)(`button`,{type:`button`,onClick:E,className:`p-1 bg-[#101e2e]/90 hover:bg-[#1f3750] border border-[#3e6080]/80 hover:border-[#67b1ec] rounded text-[#8cb4db] hover:text-white transition-all cursor-pointer shadow-md`,title:`Minimize to Taskbar`,children:(0,N.jsx)(c,{className:`w-3 h-3`})}),D&&(0,N.jsx)(`button`,{type:`button`,onClick:D,className:`p-1 bg-[#101e2e]/90 hover:bg-rose-900/70 border border-[#3e6080]/80 hover:border-rose-400 rounded text-[#8cb4db] hover:text-rose-200 transition-all cursor-pointer shadow-md`,title:`Rest by the Fire (Esc)`,children:(0,N.jsx)(g,{className:`w-3 h-3`})})]}),(0,N.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,N.jsxs)(`span`,{className:`font-mono text-sm sm:text-base font-bold text-[#f3cb65] tracking-wide drop-shadow-[0_1px_2px_rgba(0,0,0,0.9)]`,children:[`-`,e||`Princess Aurelia`,`-`]}),_&&(0,N.jsx)(`span`,{className:`hidden md:inline-block text-[9px] font-mono text-[#8cb4db] bg-[#101d2c]/80 border border-[#3e6080]/60 px-1.5 py-0.2 rounded uppercase tracking-wider`,children:_})]}),(0,N.jsxs)(`div`,{className:`min-h-[48px] sm:min-h-[54px] flex flex-col justify-start`,children:[r?(0,N.jsxs)(`div`,{className:`flex items-center gap-2 py-1 text-xs sm:text-sm font-mono text-[#8cb4db]`,children:[(0,N.jsx)(`span`,{className:`inline-block w-2 h-2 bg-[#f3cb65] rounded-full animate-ping`}),(0,N.jsxs)(`span`,{children:[e||`Princess Aurelia`,` is gathering her strength...`]})]}):(0,N.jsxs)(`div`,{className:`font-mono text-xs sm:text-sm md:text-[15px] leading-relaxed text-[#e6edf4] select-text`,children:[(e=>e.split(/(\*[^*]+\*)/g).map((e,t)=>e.startsWith(`*`)&&e.endsWith(`*`)?(0,N.jsx)(`span`,{className:`text-[#f3cb65] italic font-semibold mr-1 inline-block`,children:e},t):(0,N.jsx)(`span`,{children:e},t)))(X),q&&(0,N.jsx)(`span`,{className:`inline-block w-1.5 h-3.5 bg-[#f3cb65] ml-1 animate-pulse align-middle`})]}),s&&s.length>0&&!r&&(0,N.jsx)(`div`,{className:`mt-2 flex flex-wrap gap-1.5 select-none`,children:s.map((e,t)=>(0,N.jsxs)(`span`,{className:`px-2 py-0.5 rounded bg-[#102438] border border-[#44729b] text-[10px] font-mono font-bold text-[#bfe1ff] flex items-center gap-1`,children:[(0,N.jsx)(y,{className:`w-2.5 h-2.5 text-[#f3cb65]`}),(0,N.jsxs)(`span`,{children:[`Enchantment: `,e.name]})]},t))})]}),(0,N.jsx)(`div`,{className:`flex flex-col gap-1 pt-1`,onClick:e=>e.stopPropagation(),children:J.map((e,t)=>{let i=t+1,a=Y===t;return(0,N.jsxs)(`button`,{type:`button`,disabled:r||n,onClick:()=>l(e),onMouseEnter:()=>R(t),className:`w-full sm:max-w-[90%] md:max-w-[85%] text-left flex items-center gap-2 px-2.5 py-1 rounded-xs sm:rounded-sm transition-all select-none font-mono text-xs sm:text-sm disabled:opacity-40 disabled:cursor-not-allowed ${a&&!r&&!n?`bg-[#1c3e61]/80 border border-[#4883b6]/80 shadow-[0_0_12px_rgba(72,131,182,0.25)] cursor-pointer`:`border border-transparent hover:bg-[#1c3e61]/35 cursor-pointer`}`,children:[(0,N.jsxs)(`span`,{className:`font-bold shrink-0 ${a?`text-[#e2ecf7]`:`text-[#b4c8dc]`}`,children:[i,`.`]}),(0,N.jsxs)(`span`,{className:`truncate font-medium ${a?`text-[#f3cb65]`:`text-[#dde7f2]`}`,children:[`[`,e,`]`]})]},t)})})]}),(0,N.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),Q()},onClick:e=>e.stopPropagation(),className:`w-full rounded-md sm:rounded-lg text-white py-2 sm:py-2.5 pr-3 sm:pr-4 pl-8 sm:pl-14 md:pl-16 lg:pl-18 flex items-center gap-2 backdrop-blur-md transition-all select-none`,style:I,children:[(0,N.jsx)(`span`,{className:`font-mono text-sm sm:text-base font-bold text-[#e2ecf7] select-none pl-0.5 shrink-0`,children:`>`}),(0,N.jsxs)(`div`,{className:`flex-1 flex items-center bg-[#101e2e]/90 border border-[#3b5d7d] rounded px-2.5 py-1 focus-within:border-[#67b1ec] focus-within:ring-1 focus-within:ring-[#67b1ec]/40 shadow-inner`,children:[(0,N.jsx)(`span`,{className:`text-[#f3cb65] font-mono text-xs sm:text-sm select-none mr-1.5 shrink-0`,children:`[`}),(0,N.jsx)(`input`,{ref:K,type:`text`,value:z,onChange:e=>B(e.target.value),onFocus:()=>H(!0),onBlur:()=>H(!1),disabled:r||n,placeholder:`Speak with ${e||`Princess Aurelia`}...`,className:`flex-1 bg-transparent border-none text-[#e2ecf7] placeholder-[#f3cb65]/70 font-mono text-xs sm:text-sm focus:outline-none disabled:opacity-50 disabled:cursor-not-allowed`}),(0,N.jsx)(`span`,{className:`text-[#f3cb65] font-mono text-xs sm:text-sm select-none ml-1.5 shrink-0`,children:`]`})]}),(0,N.jsxs)(`button`,{type:`submit`,disabled:r||n||!z.trim(),className:`bg-[#34597b] hover:bg-[#3f6990] active:bg-[#2b4c6e] disabled:opacity-40 disabled:cursor-not-allowed border border-[#5c8cb5] hover:border-[#8db7dc] rounded px-3 sm:px-4 py-1 text-xs sm:text-sm font-mono font-bold text-white transition-all cursor-pointer shadow-md select-none shrink-0 flex items-center`,children:[(0,N.jsx)(`span`,{className:`text-[#f3cb65]`,children:`[`}),(0,N.jsx)(`span`,{className:`text-white px-1`,children:`Send`}),(0,N.jsx)(`span`,{className:`text-[#f3cb65]`,children:`]`})]})]})]})}function R({currentFloor:e,onClose:t}){let n=S(e),r=Math.min(100,Math.round(e/150*100));return(0,N.jsx)(`div`,{className:`absolute inset-0 z-50 bg-ink-black/40 backdrop-blur-xs flex items-center justify-center p-3 sm:p-4 animate-in fade-in duration-200 select-none`,onClick:t,children:(0,N.jsxs)(`div`,{className:`bg-[#FFFDF0] border-[3px] border-ink-black rounded-xl p-4 sm:p-5 max-w-md w-full shadow-[6px_6px_0px_0px_#1E293B] flex flex-col gap-3.5`,onClick:e=>e.stopPropagation(),children:[(0,N.jsxs)(`div`,{className:`flex items-center justify-between border-b-[2px] border-ink-black pb-2`,children:[(0,N.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,N.jsx)(i,{className:`w-5 h-5 text-indigo-600`}),(0,N.jsx)(`h4`,{className:`font-headline-md font-bold text-sm text-ink-black m-0`,children:`Journey to the Tower of the Elixir`})]}),(0,N.jsx)(`button`,{type:`button`,onClick:t,className:`p-1 hover:bg-slate-200 rounded text-slate-700 cursor-pointer`,title:`Close`,children:(0,N.jsx)(g,{className:`w-4 h-4`})})]}),(0,N.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,N.jsxs)(`div`,{className:`flex items-center justify-between text-xs font-bold font-headline-md`,children:[(0,N.jsx)(`span`,{children:`Path Progress:`}),(0,N.jsxs)(`span`,{className:`font-arcade bg-indigo-100 text-indigo-900 px-2 py-0.5 rounded border border-indigo-300`,children:[e,` / 150 Leagues`]})]}),(0,N.jsx)(`div`,{className:`w-full bg-slate-200 h-4 border-[2px] border-ink-black rounded-full overflow-hidden p-0.5`,children:(0,N.jsx)(`div`,{className:`bg-gradient-to-r from-amber-400 via-yellow-400 to-emerald-400 h-full rounded-full transition-all duration-500`,style:{width:`${r}%`}})}),(0,N.jsxs)(`div`,{className:`flex items-center justify-between text-[11px] text-trash-gray font-medium`,children:[(0,N.jsxs)(`span`,{children:[`Progress: `,(0,N.jsxs)(`strong`,{children:[r,`%`]})]}),(0,N.jsxs)(`span`,{children:[`Distance to Tower: `,(0,N.jsxs)(`strong`,{children:[Math.max(0,150-e),` leagues`]})]})]})]}),(0,N.jsxs)(`div`,{className:`bg-white border-[2px] border-ink-black rounded-lg p-3 shadow-[2px_2px_0px_0px_#1E293B] flex flex-col gap-1`,children:[(0,N.jsx)(`div`,{className:`text-[10px] font-bold uppercase text-amber-700 tracking-wider`,children:`Current Realm:`}),(0,N.jsx)(`div`,{className:`font-bold text-xs text-ink-black`,children:n.title}),(0,N.jsx)(`p`,{className:`text-[11px] text-slate-600 m-0 leading-relaxed font-medium`,children:n.description}),(0,N.jsxs)(`div`,{className:`text-[10px] text-amber-900 bg-amber-50 p-1.5 rounded border border-amber-200 italic mt-1`,children:[`📜 `,n.bgLore]})]}),(0,N.jsx)(`div`,{className:`flex items-center justify-between gap-1 text-center`,children:[{floor:30,label:`Plains`},{floor:60,label:`Forest`},{floor:90,label:`Caverns`},{floor:120,label:`Passes`},{floor:150,label:`The Tower`}].map(t=>{let n=e>=t.floor;return(0,N.jsxs)(`div`,{className:`flex-1 p-1.5 rounded border text-[10px] flex flex-col items-center ${n?`bg-emerald-100 border-emerald-600 text-emerald-900 font-bold`:`bg-slate-100 border-slate-300 text-slate-500`}`,children:[(0,N.jsx)(`span`,{children:n?`✓`:t.floor}),(0,N.jsx)(`span`,{className:`text-[9px] truncate w-full`,children:t.label})]},t.floor)})}),(0,N.jsx)(`div`,{className:`flex items-center justify-end border-t border-slate-200 pt-2 mt-1`,children:(0,N.jsx)(`button`,{type:`button`,onClick:t,className:`px-4 py-1.5 bg-white hover:bg-slate-100 border-[1.5px] border-ink-black rounded font-bold text-xs text-ink-black cursor-pointer shadow-xs active:translate-y-0.5`,children:`Done`})})]})})}function z({unlockedLetters:e,spireChronicles:t,currentFloor:n,heroCodex:r,episodicEvents:i,recentToolTelemetry:s,onRemoveCodexItem:c,onClose:d}){let[m,h]=(0,A.useState)(`letters`),[b,x]=(0,A.useState)(e[e.length-1]||null);return(0,N.jsx)(`div`,{className:`absolute inset-0 z-50 bg-ink-black/50 backdrop-blur-xs flex items-center justify-center p-3 sm:p-4 animate-in fade-in duration-200 select-none`,onClick:d,children:(0,N.jsxs)(`div`,{className:`bg-[#FFFDF0] border-[3px] border-ink-black rounded-xl max-w-lg w-full h-[85%] max-h-[560px] shadow-[6px_6px_0px_0px_#1E293B] flex flex-col overflow-hidden`,onClick:e=>e.stopPropagation(),children:[(0,N.jsxs)(`div`,{className:`bg-white border-b-[2px] border-ink-black px-4 py-2.5 flex items-center justify-between shrink-0`,children:[(0,N.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,N.jsx)(a,{className:`w-5 h-5 text-amber-700`}),(0,N.jsx)(`h4`,{className:`font-headline-md font-bold text-sm text-ink-black m-0`,children:`The Royal Satchel`})]}),(0,N.jsx)(`button`,{type:`button`,onClick:d,className:`p-1 hover:bg-slate-200 rounded text-slate-700 cursor-pointer`,title:`Close`,children:(0,N.jsx)(g,{className:`w-4 h-4`})})]}),(0,N.jsxs)(`div`,{className:`flex border-b-2 border-ink-black bg-amber-100/70 shrink-0`,children:[(0,N.jsxs)(`button`,{type:`button`,onClick:()=>h(`letters`),className:`flex-1 py-2 text-xs font-bold font-headline-md flex items-center justify-center gap-1.5 transition-colors cursor-pointer border-r border-ink-black/20 ${m===`letters`?`bg-[#FFFDF0] text-amber-950 border-b-2 border-b-[#FFFDF0] -mb-[2px]`:`text-slate-600 hover:bg-amber-200/50`}`,children:[(0,N.jsx)(a,{className:`w-3.5 h-3.5`}),(0,N.jsxs)(`span`,{children:[`Missives (`,e.length,`/5)`]})]}),(0,N.jsxs)(`button`,{type:`button`,onClick:()=>h(`diary`),className:`flex-1 py-2 text-xs font-bold font-headline-md flex items-center justify-center gap-1.5 transition-colors cursor-pointer border-r border-ink-black/20 ${m===`diary`?`bg-[#FFFDF0] text-amber-950 border-b-2 border-b-[#FFFDF0] -mb-[2px]`:`text-slate-600 hover:bg-amber-200/50`}`,children:[(0,N.jsx)(l,{className:`w-3.5 h-3.5`}),(0,N.jsxs)(`span`,{children:[`Chronicles (`,t.length,`)`]})]}),(0,N.jsxs)(`button`,{type:`button`,onClick:()=>h(`codex`),className:`flex-1 py-2 text-xs font-bold font-headline-md flex items-center justify-center gap-1.5 transition-colors cursor-pointer ${m===`codex`?`bg-[#FFFDF0] text-amber-950 border-b-2 border-b-[#FFFDF0] -mb-[2px]`:`text-slate-600 hover:bg-amber-200/50`}`,children:[(0,N.jsx)(y,{className:`w-3.5 h-3.5 text-amber-700`}),(0,N.jsx)(`span`,{children:`Codex`})]})]}),(0,N.jsxs)(`div`,{className:`flex-1 p-3 sm:p-4 overflow-y-auto custom-scrollbar flex flex-col gap-3 min-h-0`,children:[m===`letters`&&(0,N.jsxs)(`div`,{className:`flex flex-col gap-3 flex-1`,children:[(0,N.jsx)(`div`,{className:`flex items-center gap-1.5 overflow-x-auto pb-1`,children:[30,60,90,120,150].map(e=>{let t=D[e],r=n>=e,i=b?.floor===e;return(0,N.jsxs)(`button`,{type:`button`,disabled:!r,onClick:()=>r&&x(t),className:`px-3 py-1 rounded-full text-[11px] font-bold border-[1.5px] border-ink-black flex items-center gap-1 shrink-0 transition-all cursor-pointer ${r?i?`bg-[#FFE24C] text-ink-black shadow-[1.5px_1.5px_0px_0px_#1E293B]`:`bg-white hover:bg-amber-100 text-slate-800`:`opacity-40 bg-slate-200 text-slate-500 cursor-not-allowed`}`,children:[r?(0,N.jsx)(`span`,{children:`📜`}):(0,N.jsx)(o,{className:`w-3 h-3`}),(0,N.jsxs)(`span`,{children:[`League `,e]})]},e)})}),b?(0,N.jsxs)(`div`,{className:`bg-[#FFF9E6] border-[2px] border-amber-900/40 rounded-lg p-4 shadow-sm flex-1 overflow-y-auto custom-scrollbar flex flex-col select-text`,children:[(0,N.jsxs)(`div`,{className:`border-b border-amber-800/20 pb-2 mb-3 flex items-center justify-between`,children:[(0,N.jsxs)(`div`,{children:[(0,N.jsxs)(`div`,{className:`text-[10px] font-bold text-amber-800 uppercase tracking-wider`,children:[b.chapterTitle,` • League `,b.floor]}),(0,N.jsx)(`h5`,{className:`font-headline-md font-bold text-sm text-amber-950 m-0`,children:b.title})]}),(0,N.jsx)(`span`,{className:`text-xl`,children:`🪶`})]}),(0,N.jsx)(`p`,{className:`text-xs sm:text-[13px] text-amber-950 font-serif leading-relaxed whitespace-pre-wrap flex-1 italic`,children:b.letterText})]}):(0,N.jsxs)(`div`,{className:`flex-1 flex flex-col items-center justify-center text-center p-6 text-slate-500`,children:[(0,N.jsx)(o,{className:`w-8 h-8 mb-2 text-slate-400`}),(0,N.jsx)(`p`,{className:`text-xs font-medium`,children:`Travel 30 leagues along the path to unlock your first missive from Aurelia.`})]})]}),m===`diary`&&(0,N.jsx)(`div`,{className:`flex flex-col gap-2.5 flex-1`,children:t.length>0?t.map(e=>(0,N.jsxs)(`div`,{className:`p-3 bg-white border-[1.5px] border-ink-black rounded-lg shadow-xs flex flex-col gap-1 select-text`,children:[(0,N.jsxs)(`div`,{className:`flex items-center justify-between text-[10px] text-amber-800 font-bold border-b border-slate-100 pb-1`,children:[(0,N.jsxs)(`span`,{children:[`League `,e.floor,` along the Path`]}),(0,N.jsx)(`span`,{children:new Date(e.timestamp).toLocaleDateString()})]}),(0,N.jsxs)(`p`,{className:`text-xs text-ink-black font-medium leading-relaxed m-0 italic font-serif`,children:[`“`,e.text,`”`]})]},e.id)):(0,N.jsxs)(`div`,{className:`flex-1 flex flex-col items-center justify-center text-center p-6 text-slate-500`,children:[(0,N.jsx)(l,{className:`w-8 h-8 mb-2 text-slate-400`}),(0,N.jsx)(`p`,{className:`text-xs font-medium`,children:`Aurelia records entries in her travel journal as you journey together, rest by the fire, and cross chapter milestones.`})]})}),m===`codex`&&(0,N.jsxs)(`div`,{className:`flex flex-col gap-3 flex-1 select-text`,children:[(0,N.jsxs)(`div`,{className:`bg-white border-[1.5px] border-ink-black rounded-lg p-3 shadow-xs flex flex-col gap-2`,children:[(0,N.jsxs)(`div`,{className:`flex items-center justify-between border-b border-slate-100 pb-1.5`,children:[(0,N.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,N.jsx)(y,{className:`w-4 h-4 text-amber-600`}),(0,N.jsx)(`h5`,{className:`font-headline-md font-bold text-xs text-ink-black m-0`,children:`Hero Codex (MemGPT & Mem0 Core Memory)`})]}),(0,N.jsx)(`span`,{className:`text-[10px] text-slate-400 font-mono`,children:`Cognitive Sync`})]}),(0,N.jsxs)(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-2 text-xs`,children:[(0,N.jsxs)(`div`,{className:`bg-[#FFFDF0] border border-amber-900/20 rounded p-2`,children:[(0,N.jsx)(`span`,{className:`text-[10px] font-bold text-slate-500 uppercase tracking-wider block`,children:`Hero Alias`}),(0,N.jsx)(`span`,{className:`font-bold text-ink-black text-xs`,children:r?.heroName||`Champion`})]}),(0,N.jsxs)(`div`,{className:`bg-[#FFFDF0] border border-amber-900/20 rounded p-2`,children:[(0,N.jsx)(`span`,{className:`text-[10px] font-bold text-slate-500 uppercase tracking-wider block`,children:`Target Goal`}),(0,N.jsx)(`span`,{className:`font-bold text-amber-900 text-xs`,children:r?.targetGoal||`None shared yet (mention to Aurelia!)`})]})]}),r?.preferredLanguage&&(0,N.jsxs)(`div`,{className:`bg-[#FFFDF0] border border-amber-900/20 rounded p-2 text-xs`,children:[(0,N.jsx)(`span`,{className:`text-[10px] font-bold text-slate-500 uppercase tracking-wider block`,children:`Weapon of Choice (Language)`}),(0,N.jsx)(`span`,{className:`font-bold text-ink-black`,children:r.preferredLanguage})]})]}),(0,N.jsxs)(`div`,{className:`bg-white border-[1.5px] border-ink-black rounded-lg p-3 shadow-xs flex flex-col gap-2`,children:[(0,N.jsxs)(`div`,{className:`flex items-center gap-1.5 text-xs font-bold text-emerald-800`,children:[(0,N.jsx)(p,{className:`w-3.5 h-3.5`}),(0,N.jsxs)(`span`,{children:[`Mastered Patterns (`,r?.strengths?.length||0,`)`]})]}),r?.strengths&&r.strengths.length>0?(0,N.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:r.strengths.map(e=>(0,N.jsxs)(`span`,{className:`inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[11px] font-bold bg-emerald-50 text-emerald-800 border border-emerald-300`,children:[e,c&&(0,N.jsx)(`button`,{type:`button`,onClick:()=>c(`strengths`,e),className:`hover:text-red-600 ml-0.5 cursor-pointer`,title:`Forget strength`,children:(0,N.jsx)(g,{className:`w-3 h-3`})})]},e))}):(0,N.jsx)(`p`,{className:`text-[11px] text-slate-400 italic m-0`,children:`Aurelia will note trials you conquer along our journey.`})]}),(0,N.jsxs)(`div`,{className:`bg-white border-[1.5px] border-ink-black rounded-lg p-3 shadow-xs flex flex-col gap-2`,children:[(0,N.jsxs)(`div`,{className:`flex items-center gap-1.5 text-xs font-bold text-rose-800`,children:[(0,N.jsx)(v,{className:`w-3.5 h-3.5`}),(0,N.jsxs)(`span`,{children:[`Nemesis Patterns (`,r?.nemesisPatterns?.length||0,`)`]})]}),r?.nemesisPatterns&&r.nemesisPatterns.length>0?(0,N.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:r.nemesisPatterns.map(e=>(0,N.jsxs)(`span`,{className:`inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[11px] font-bold bg-rose-50 text-rose-800 border border-rose-300`,children:[e,c&&(0,N.jsx)(`button`,{type:`button`,onClick:()=>c(`nemesisPatterns`,e),className:`hover:text-red-700 ml-0.5 cursor-pointer`,title:`Forget nemesis`,children:(0,N.jsx)(g,{className:`w-3 h-3`})})]},e))}):(0,N.jsx)(`p`,{className:`text-[11px] text-slate-400 italic m-0`,children:`Aurelia tracks difficult trials to help you prepare targeted drills.`})]}),(0,N.jsxs)(`div`,{className:`bg-white border-[1.5px] border-ink-black rounded-lg p-3 shadow-xs flex flex-col gap-2`,children:[(0,N.jsx)(`div`,{className:`text-xs font-bold text-slate-800`,children:(0,N.jsxs)(`span`,{children:[`Personal Notes & Shared Lore (`,r?.personalNotes?.length||0,`)`]})}),r?.personalNotes&&r.personalNotes.length>0?(0,N.jsx)(`div`,{className:`flex flex-col gap-1.5`,children:r.personalNotes.map(e=>(0,N.jsxs)(`div`,{className:`flex items-start justify-between gap-2 p-2 bg-slate-50 border border-slate-200 rounded text-[11px] text-slate-700`,children:[(0,N.jsxs)(`span`,{children:[`• `,e]}),c&&(0,N.jsx)(`button`,{type:`button`,onClick:()=>c(`personalNotes`,e),className:`text-slate-400 hover:text-red-600 shrink-0 cursor-pointer p-0.5`,title:`Forget note`,children:(0,N.jsx)(_,{className:`w-3 h-3`})})]},e))}):(0,N.jsx)(`p`,{className:`text-[11px] text-slate-400 italic m-0`,children:`Share your background or routine with Aurelia and she will hold it in her memory.`})]}),i&&i.length>0&&(0,N.jsxs)(`div`,{className:`bg-white border-[1.5px] border-ink-black rounded-lg p-3 shadow-xs flex flex-col gap-2`,children:[(0,N.jsxs)(`div`,{className:`flex items-center justify-between border-b border-slate-100 pb-1`,children:[(0,N.jsx)(`span`,{className:`text-xs font-bold text-slate-800`,children:`Episodic Memory Chain (EM-LLM)`}),(0,N.jsxs)(`span`,{className:`text-[10px] text-slate-400 font-mono`,children:[i.length,` events`]})]}),(0,N.jsx)(`div`,{className:`flex flex-col gap-2 max-h-40 overflow-y-auto custom-scrollbar`,children:i.slice(0,8).map(e=>(0,N.jsxs)(`div`,{className:`text-[11px] p-2 bg-[#FFFDF0] border border-amber-900/15 rounded flex flex-col gap-0.5`,children:[(0,N.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,N.jsx)(`span`,{className:`font-bold text-ink-black uppercase text-[9px] px-1.5 py-0.5 bg-amber-200/60 rounded`,children:e.eventType.replace(`_`,` `)}),(0,N.jsx)(`span`,{className:`text-[10px] text-slate-400`,children:new Date(e.timestamp).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`})})]}),(0,N.jsx)(`div`,{className:`font-bold text-slate-800 mt-0.5`,children:e.title}),(0,N.jsx)(`div`,{className:`text-slate-600 text-[10px]`,children:e.description})]},e.id))})]}),(0,N.jsxs)(`div`,{className:`bg-white border-[1.5px] border-ink-black rounded-lg p-3 shadow-xs flex flex-col gap-2`,children:[(0,N.jsxs)(`div`,{className:`flex items-center justify-between border-b border-slate-100 pb-1`,children:[(0,N.jsxs)(`div`,{className:`flex items-center gap-1.5 text-xs font-bold text-indigo-900`,children:[(0,N.jsx)(u,{className:`w-3.5 h-3.5 text-amber-500`}),(0,N.jsx)(`span`,{children:`Autonomous Enchantment Telemetry`})]}),(0,N.jsxs)(`span`,{className:`text-[10px] text-slate-400 font-mono`,children:[s?.length||0,` executed`]})]}),s&&s.length>0?(0,N.jsx)(`div`,{className:`flex flex-col gap-1.5 max-h-36 overflow-y-auto custom-scrollbar`,children:s.slice(0,10).map((e,t)=>(0,N.jsxs)(`div`,{className:`text-[11px] p-2 bg-indigo-50/50 border border-indigo-100 rounded flex items-center justify-between gap-2`,children:[(0,N.jsxs)(`div`,{className:`flex flex-col min-w-0`,children:[(0,N.jsxs)(`span`,{className:`font-bold text-indigo-950 font-mono text-[10px] truncate`,children:[e.tool_name,`()`]}),e.args&&Object.keys(e.args).length>0&&(0,N.jsx)(`span`,{className:`text-[9px] text-slate-500 truncate`,children:JSON.stringify(e.args).slice(0,50)})]}),(0,N.jsxs)(`div`,{className:`flex items-center gap-2 shrink-0`,children:[e.execution_time_ms!==void 0&&(0,N.jsxs)(`span`,{className:`text-[9px] text-slate-400 flex items-center gap-0.5 font-mono`,children:[(0,N.jsx)(f,{className:`w-2.5 h-2.5`}),e.execution_time_ms,`ms`]}),(0,N.jsx)(`span`,{className:`px-1.5 py-0.2 text-[9px] font-bold rounded ${e.success?`bg-emerald-100 text-emerald-800`:`bg-rose-100 text-rose-800`}`,children:e.success?`SUCCESS`:`ERR`})]})]},t))}):(0,N.jsx)(`p`,{className:`text-[11px] text-slate-400 italic m-0`,children:`No autonomous enchantments executed yet in this session.`})]})]})]}),(0,N.jsx)(`div`,{className:`bg-white border-t border-slate-200 px-4 py-2 flex items-center justify-end shrink-0`,children:(0,N.jsx)(`button`,{type:`button`,onClick:d,className:`px-4 py-1.5 bg-white hover:bg-slate-100 border-[1.5px] border-ink-black rounded font-bold text-xs text-ink-black cursor-pointer shadow-xs active:translate-y-0.5`,children:`Close`})})]})})}var B=e({default:()=>V});function V({onClose:e,onMinimize:t,isActive:r=!0,onFocus:i,zIndex:a}){let o=b(),[s,c]=(0,A.useState)(T()),[l,u]=(0,A.useState)(!1),[d,f]=(0,A.useState)(!1),[p,h]=(0,A.useState)(!1);(0,A.useEffect)(()=>{O.syncWithBackend(),O.triggerProactiveGreeting()},[]);let _=(0,A.useCallback)(()=>{e?e():k.getState().closeWindow(`companion`)},[e]),v=(0,A.useCallback)(()=>{t?t():k.getState().minimizeWindow(`companion`)},[t]),y=(0,A.useCallback)(()=>{i?i():k.getState().setActiveWindow(`companion`)},[i]),S=(0,A.useCallback)(()=>{let e=!s;c(e),C(e)},[s]),E=(0,A.useCallback)(()=>{window.confirm(`Clear conversation transcript with Princess Aurelia?`)&&O.clearTranscript()},[]),D=(0,A.useCallback)(e=>{O.setIsTyping(e)},[]),j=(0,A.useMemo)(()=>[...o.transcript].reverse().find(e=>e.sender===`princess`)||o.transcript[0],[o.transcript]),M=`Welcome back to camp. How is your strength holding up today? Are you ready to continue our journey, or would you like to rest for a while?`,F=j?j.isStreaming?j.text:j.text||(o.isLoading?``:M):M,I=(0,A.useMemo)(()=>{let e=j?.choiceSuggestions&&j.choiceSuggestions.length>0?j.choiceSuggestions:[...o.transcript].reverse().find(e=>e.sender===`princess`&&e.choiceSuggestions&&e.choiceSuggestions.length>0)?.choiceSuggestions,t=x(e,o.heroCodex?.heroName||o.heroProfile?.heroName||`Champion`,o.companionSettings.name||`Princess Aurelia`);return t.length>0?t:w},[j,o.transcript,o.heroCodex?.heroName,o.heroProfile?.heroName,o.companionSettings.name]);return(0,N.jsxs)(`div`,{onClick:y,className:`fixed inset-x-0 top-0 bottom-[40px] select-none pointer-events-none overflow-hidden font-sans`,style:{zIndex:a??(r?40:30)},children:[(0,N.jsx)(`div`,{className:`absolute inset-x-0 bottom-0 h-44 bg-gradient-to-t from-slate-950/35 via-slate-900/10 to-transparent pointer-events-none z-0`}),(0,N.jsxs)(`div`,{className:`relative w-full h-full flex flex-col justify-end pointer-events-none pb-2 sm:pb-3 px-2 sm:px-4 md:px-8`,children:[(0,N.jsxs)(`div`,{className:`relative w-full max-w-5xl lg:max-w-6xl mx-auto flex items-end justify-start pointer-events-none`,children:[(0,N.jsx)(`div`,{className:`relative z-30 shrink-0 pointer-events-auto -mr-6 sm:-mr-10 md:-mr-12 lg:-mr-14`,children:(0,N.jsx)(P,{emotion:o.activeEmotion,floor:o.currentFloor,rhythm:o.currentRhythm,activity:o.currentActivity,isLoading:o.isLoading,onClick:y})}),(0,N.jsx)(`div`,{className:`relative z-20 flex-1 min-w-0 pointer-events-auto mb-1`,children:(0,N.jsx)(L,{characterName:o.companionSettings.name||`Princess Aurelia`,emotion:o.activeEmotion,text:F,isStreaming:j?.isStreaming,isLoading:o.isLoading,choices:I,toolCalls:j?.toolCalls,onSelectChoice:e=>O.sendMessage(e),onSendMessage:e=>O.sendMessage(e),onTypingStatusChange:D,currentFloor:o.currentFloor,bondTier:o.bondTier,satchelCount:o.unlockedLetters.length,isMuted:s,onToggleMute:S,onOpenProgress:()=>u(!0),onOpenSatchel:()=>f(!0),onOpenHistory:()=>h(!0),onMinimize:v,onClose:_})})]}),(0,N.jsxs)(`div`,{className:`absolute bottom-1 right-3.5 pointer-events-none z-30 hidden md:flex flex-col items-center gap-0.5 opacity-65 select-none`,children:[(0,N.jsx)(`svg`,{className:`w-8 h-8 text-[#9cbcdb] drop-shadow-[0_0_6px_rgba(156,188,219,0.5)] rotate-6`,viewBox:`0 0 24 24`,fill:`currentColor`,children:(0,N.jsx)(`path`,{d:`M12 2 C12 7.8 7.8 12 2 12 C7.8 12 12 16.2 12 22 C12 16.2 16.2 12 22 12 C16.2 12 12 7.8 12 2 Z`})}),(0,N.jsxs)(`div`,{className:`font-mono text-[9px] text-[#7ba4c8] tracking-tight leading-tight text-center`,children:[(0,N.jsx)(`div`,{children:`AlgoSpaced (Beta)`}),(0,N.jsx)(`div`,{children:`Build Jun24 preview`})]})]})]}),l&&(0,N.jsx)(`div`,{className:`pointer-events-auto`,children:(0,N.jsx)(R,{currentFloor:o.currentFloor,totalSolved:o.totalSolved,onClose:()=>u(!1)})}),d&&(0,N.jsx)(`div`,{className:`pointer-events-auto`,children:(0,N.jsx)(z,{unlockedLetters:o.unlockedLetters,spireChronicles:o.spireChronicles,currentFloor:o.currentFloor,heroCodex:o.heroCodex,episodicEvents:o.episodicEvents,recentToolTelemetry:o.recentToolTelemetry,onRemoveCodexItem:O.removeCodexItem,onClose:()=>f(!1)})}),p&&(0,N.jsx)(`div`,{className:`fixed inset-0 z-50 bg-black/60 backdrop-blur-xs flex items-center justify-center p-3 sm:p-4 animate-in fade-in duration-200 pointer-events-auto`,onClick:()=>h(!1),children:(0,N.jsxs)(`div`,{className:`bg-[#142335] border-[3px] border-[#5a80a2] rounded-xl max-w-lg w-full h-[80%] max-h-[520px] shadow-[0_16px_40px_rgba(0,0,0,0.85)] flex flex-col overflow-hidden text-white`,onClick:e=>e.stopPropagation(),style:{boxShadow:`inset 0 0 0 1px #0a1420, inset 0 1px 0 rgba(255, 255, 255, 0.15), 0 16px 40px rgba(0, 0, 0, 0.85)`},children:[(0,N.jsxs)(`div`,{className:`bg-[#101b2a] border-b border-[#304f6f] px-4 py-2.5 flex items-center justify-between shrink-0`,children:[(0,N.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,N.jsx)(m,{className:`w-4 h-4 text-[#67b1ec]`}),(0,N.jsxs)(`h4`,{className:`font-mono font-bold text-xs sm:text-sm text-[#e6f0fa] m-0`,children:[`Dialogue Transcript (`,o.transcript.length,` turns)`]})]}),(0,N.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,N.jsxs)(`button`,{type:`button`,onClick:E,className:`px-2 py-0.5 bg-rose-950/60 hover:bg-rose-900 border border-rose-700/60 rounded text-[11px] font-mono font-bold text-rose-300 hover:text-white flex items-center gap-1 cursor-pointer mr-1 transition-colors`,title:`Clear Chat History`,children:[(0,N.jsx)(n,{className:`w-3 h-3`}),(0,N.jsx)(`span`,{children:`Clear`})]}),(0,N.jsx)(`button`,{type:`button`,onClick:()=>h(!1),className:`p-1 hover:bg-[#203a55] rounded text-[#8cb4db] hover:text-white cursor-pointer transition-colors`,title:`Close`,children:(0,N.jsx)(g,{className:`w-4 h-4`})})]})]}),(0,N.jsx)(`div`,{className:`flex-1 p-3 sm:p-4 overflow-y-auto custom-scrollbar flex flex-col gap-2.5 bg-[#0e1824]/90`,children:o.transcript.map((e,t)=>(0,N.jsxs)(`div`,{className:`p-2.5 rounded-lg border font-mono text-xs max-w-[90%] shadow-md ${e.sender===`princess`?`bg-[#182c42] border-[#3e6080] text-[#e6f0fa] self-start`:`bg-[#214365] border-[#5a8bb9] text-white self-end`}`,children:[(0,N.jsx)(`div`,{className:`text-[10px] font-bold mb-1 text-[#f6d267]`,children:e.sender===`princess`?o.companionSettings.name:`Hero`}),(0,N.jsx)(`p`,{className:`font-medium m-0 leading-relaxed whitespace-pre-wrap select-text`,children:e.text})]},e.id||t))})]})})]})}export{B as t};1import{n as e,r as t}from"./rolldown-runtime-hePW80VL.js";import{A as n,Bt as r,Ct as i,D as a,G as o,Ht as s,R as c,Tt as l,a as u,c as d,dt as f,ht as p,j as m,l as h,o as g,p as _,w as v,x as y}from"./vendor-react-hnaVBnLv.js";import{C as b,S as x,_ as S,b as C,g as w,v as T,x as E,y as D}from"./index-DVWZ15xt.js";var O=t(s(),1),k={1:{particleType:`pollen`,particleCount:16,particleColors:[`#FDE047`,`#FEF08A`,`#86EFAC`],gradientBg:`from-[#FFFDF0] via-[#FFF9E6] to-[#FEF3C7]`,glowColor:`rgba(251, 191, 36, 0.3)`,badgeLabel:`🌾 Plains Breeze`},2:{particleType:`leaves`,particleCount:18,particleColors:[`#86EFAC`,`#4ADE80`,`#22C55E`,`#A7F3D0`],gradientBg:`from-[#F0FDF4] via-[#DCFCE7] to-[#FEF9C3]`,glowColor:`rgba(34, 197, 94, 0.3)`,badgeLabel:`🍃 Whispering Leaves`},3:{particleType:`spores`,particleCount:22,particleColors:[`#67E8F9`,`#38BDF8`,`#818CF8`,`#C084FC`],gradientBg:`from-[#F0F9FF] via-[#E0F2FE] to-[#EDE9FE]`,glowColor:`rgba(56, 189, 248, 0.35)`,badgeLabel:`✨ Crystal Spores`},4:{particleType:`snow`,particleCount:28,particleColors:[`#FFFFFF`,`#E0F2FE`,`#BAE6FD`],gradientBg:`from-[#F8FAFC] via-[#F1F5F9] to-[#E2E8F0]`,glowColor:`rgba(186, 230, 253, 0.4)`,badgeLabel:`❄️ Alpine Snowfall`},5:{particleType:`runes`,particleCount:20,particleColors:[`#E879F9`,`#C084FC`,`#A855F7`,`#F472B6`],gradientBg:`from-[#FAF5FF] via-[#F3E8FF] to-[#FCE7F3]`,glowColor:`rgba(192, 132, 252, 0.4)`,badgeLabel:`🔮 Arcane Runes`},6:{particleType:`stardust`,particleCount:35,particleColors:[`#FDE047`,`#F59E0B`,`#E11D48`,`#818CF8`],gradientBg:`from-[#FFFBEB] via-[#FEF3C7] to-[#FFE4E6]`,glowColor:`rgba(245, 158, 11, 0.5)`,badgeLabel:`👑 Spire Gates`}};function A(e){return e<=30?k[1]:e<=60?k[2]:e<=90?k[3]:e<=120?k[4]:e<150?k[5]:k[6]}var j=r();function M({emotion:e,floor:t,rhythm:n,activity:r,isLoading:i=!1,className:a=``,onClick:o}){let s=T[e]||T.smiling_warmly,c=(0,O.useMemo)(()=>A(t),[t]),l=(0,O.useMemo)(()=>{switch(n){case`dawn`:return`from-amber-400/30 via-yellow-300/20 to-transparent`;case`dusk`:return`from-orange-500/30 via-purple-500/20 to-transparent`;case`night`:return`from-indigo-600/30 via-blue-500/20 to-transparent`;default:return`from-amber-300/25 via-sky-300/20 to-transparent`}},[n]);return(0,j.jsxs)(`div`,{onClick:o,className:`relative flex flex-col items-center justify-end select-none pointer-events-auto transition-transform ${a}`,children:[(0,j.jsx)(`div`,{className:`absolute -inset-10 overflow-hidden pointer-events-none z-0`,children:Array.from({length:Math.min(16,c.particleCount)}).map((e,t)=>{let n=c.particleColors[t%c.particleColors.length],r=`${t*17%100}%`,i=`${7+t%5*2}s`,a=`${t*.8%4}s`,o=c.particleType===`leaves`||c.particleType===`runes`?`w-2 h-2`:`w-1.5 h-1.5`;return(0,j.jsx)(`span`,{className:`absolute rounded-full opacity-60 animate-pulse ${o}`,style:{backgroundColor:n,left:r,top:`${t*21%90}%`,boxShadow:`0 0 10px ${n}`,animationDuration:i,animationDelay:a}},t)})}),(0,j.jsx)(`div`,{className:`absolute bottom-4 inset-x-0 h-48 sm:h-72 md:h-96 bg-radial ${l} blur-2xl opacity-70 pointer-events-none z-0`}),(0,j.jsxs)(`div`,{className:`relative z-10 flex flex-col items-start justify-end`,children:[r&&(0,j.jsx)(`div`,{className:`mb-2 max-w-[120px] sm:max-w-xs text-center pointer-events-none animate-in fade-in duration-300`,children:(0,j.jsxs)(`span`,{className:`text-[9px] sm:text-[10px] font-mono font-medium text-[#bfe1ff] bg-[#101e2e]/85 px-2 sm:px-2.5 py-0.5 rounded-full border border-[#3e6080]/70 shadow-md inline-flex items-center gap-1 sm:gap-1.5 backdrop-blur-xs`,children:[(0,j.jsx)(`span`,{className:`text-amber-400`,children:`🏰`}),(0,j.jsx)(`span`,{className:`truncate`,children:r})]})}),(0,j.jsx)(`div`,{className:`relative h-[28vh] sm:h-[40vh] md:h-[46vh] lg:h-[50vh] max-h-[220px] sm:max-h-[380px] md:max-h-[460px] lg:max-h-[500px] min-h-[160px] sm:min-h-[240px] md:min-h-[300px] w-auto max-w-[110px] sm:max-w-[200px] md:max-w-[270px] lg:max-w-[320px] flex items-end justify-end`,children:(0,j.jsx)(`img`,{src:s.imagePath,alt:s.label,loading:`eager`,className:`h-full w-auto max-h-[85vh] object-contain object-bottom-left drop-shadow-[0_16px_32px_rgba(0,0,0,0.55)] transition-all duration-300 ${i?`scale-[1.02] filter brightness-110 saturate-125`:`scale-100`}`,onError:e=>{let t=e.currentTarget;t.src.endsWith(`/sprites/princess/smiling_warmly.webp`)?t.src.endsWith(`/sprites/princess/neutral.webp`)||(t.src=`/sprites/princess/neutral.webp`):t.src=`/sprites/princess/smiling_warmly.webp`}})})]})]})}var N=[`I solved a tough task today!`,`I'm feeling stuck on something.`,`Just need a breather.`],P={backgroundColor:`rgba(20, 36, 54, 0.94)`,boxShadow:`0 0 0 2px #0a1420, inset 0 0 0 3px #4c7396, inset 1px 1px 0 4px #8db7dc, inset -1px -1px 0 4px #1a2c3f, inset 0 0 0 5px #0c1724, 0 10px 28px rgba(0, 0, 0, 0.75)`};function F({characterName:e,text:t,isStreaming:n=!1,isLoading:r=!1,choices:o,toolCalls:s,onSelectChoice:l,onSendMessage:u,onTypingStatusChange:f,currentFloor:p,bondTier:_,satchelCount:v=0,isMuted:b=!1,onToggleMute:x,onOpenProgress:S,onOpenSatchel:C,onOpenHistory:w,onMinimize:T,onClose:E,className:D=``}){let[k,A]=(0,O.useState)(``),[M,F]=(0,O.useState)(!1),[I,L]=(0,O.useState)(0),[R,z]=(0,O.useState)(``),[B,V]=(0,O.useState)(!1),H=(0,O.useRef)(t),U=(0,O.useRef)(!1),W=(0,O.useRef)(null),G=(0,O.useRef)(null),K=n||M;(0,O.useEffect)(()=>{f?.(K)},[K,f]);let q=(0,O.useMemo)(()=>Array.isArray(o)&&o.length>0?o.slice(0,4):N,[o]),J=I<q.length?I:0,Y=!n&&M?k:t;(0,O.useEffect)(()=>{if(n){W.current&&=(clearInterval(W.current),null),U.current=!0,H.current=t;return}if(U.current){U.current=!1,H.current=t,W.current&&=(clearInterval(W.current),null);return}if(t!==H.current&&!r){if(H.current=t,!t){W.current&&=(clearInterval(W.current),null);return}W.current&&clearInterval(W.current);let e=0,n=setInterval(()=>{e++,A(t.slice(0,e)),F(!0),e>=t.length&&(clearInterval(n),W.current=null,F(!1))},20);return W.current=n,()=>{clearInterval(n),W.current=null,F(!1)}}},[t,r,n]);let X=(0,O.useCallback)(()=>{W.current&&=(clearInterval(W.current),null),F(!1)},[]),Z=()=>{let e=R.trim();!e||r||n||(u(e),z(``))};return(0,O.useEffect)(()=>{let e=e=>{if(e.key===`Escape`&&E){e.preventDefault(),E();return}if(!B){if(e.key>=`1`&&e.key<=String(q.length)){let t=parseInt(e.key,10)-1;q[t]&&!r&&!n&&(e.preventDefault(),l(q[t]));return}if(e.key===`ArrowUp`){e.preventDefault(),L(e=>(e-1+q.length)%q.length);return}if(e.key===`ArrowDown`){e.preventDefault(),L(e=>(e+1)%q.length);return}if(e.key===`Enter`){!r&&!n&&q[J]&&(e.preventDefault(),l(q[J]));return}e.key===` `&&K&&(e.preventDefault(),X())}};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[B,q,J,r,n,K,l,X,E]),(0,j.jsxs)(`div`,{className:`relative flex flex-col gap-2 w-full ${D}`,children:[(0,j.jsxs)(`div`,{onClick:X,className:`relative w-full rounded-md sm:rounded-lg text-white pt-3.5 pb-3.5 pr-3.5 pl-8 sm:pt-5 sm:pb-5 sm:pr-5 sm:pl-14 md:pl-16 lg:pl-18 flex flex-col gap-2.5 backdrop-blur-md transition-all select-none cursor-pointer`,style:P,children:[(0,j.jsxs)(`div`,{className:`absolute -top-7 right-1 flex items-center gap-1 sm:gap-1.5 z-30`,onClick:e=>e.stopPropagation(),children:[S&&(0,j.jsxs)(`button`,{type:`button`,onClick:S,className:`px-2 py-0.5 bg-[#101e2e]/90 hover:bg-[#1f3750] border border-[#3e6080]/80 hover:border-[#67b1ec] rounded text-[10px] sm:text-[11px] font-mono font-bold text-[#8cb4db] hover:text-white transition-all cursor-pointer flex items-center gap-1 shadow-md`,title:`Spire Tower Road (Floor Progress)`,children:[(0,j.jsx)(i,{className:`w-3 h-3 text-amber-400`}),(0,j.jsxs)(`span`,{children:[p,`/150 LC`]})]}),C&&(0,j.jsxs)(`button`,{type:`button`,onClick:C,className:`px-2 py-0.5 bg-[#101e2e]/90 hover:bg-[#1f3750] border border-[#3e6080]/80 hover:border-[#67b1ec] rounded text-[10px] sm:text-[11px] font-mono font-bold text-[#8cb4db] hover:text-white transition-all cursor-pointer flex items-center gap-1 shadow-md`,title:`Open Royal Satchel`,children:[(0,j.jsx)(a,{className:`w-3 h-3 text-amber-400`}),(0,j.jsx)(`span`,{className:`hidden sm:inline`,children:`Satchel`}),v>0&&(0,j.jsxs)(`span`,{className:`text-[9px] text-[#f3cb65]`,children:[`(`,v,`)`]})]}),w&&(0,j.jsxs)(`button`,{type:`button`,onClick:w,className:`px-2 py-0.5 bg-[#101e2e]/90 hover:bg-[#1f3750] border border-[#3e6080]/80 hover:border-[#67b1ec] rounded text-[10px] sm:text-[11px] font-mono font-bold text-[#8cb4db] hover:text-white transition-all cursor-pointer flex items-center gap-1 shadow-md`,title:`Dialogue Transcript`,children:[(0,j.jsx)(m,{className:`w-3 h-3 text-[#8cb4db]`}),(0,j.jsx)(`span`,{className:`hidden sm:inline`,children:`Log`})]}),x&&(0,j.jsx)(`button`,{type:`button`,onClick:x,className:`p-1 bg-[#101e2e]/90 hover:bg-[#1f3750] border border-[#3e6080]/80 hover:border-[#67b1ec] rounded text-[#8cb4db] hover:text-white transition-all cursor-pointer shadow-md`,title:b?`Unmute Audio`:`Mute Audio`,children:b?(0,j.jsx)(d,{className:`w-3 h-3`}):(0,j.jsx)(h,{className:`w-3 h-3`})}),T&&(0,j.jsx)(`button`,{type:`button`,onClick:T,className:`p-1 bg-[#101e2e]/90 hover:bg-[#1f3750] border border-[#3e6080]/80 hover:border-[#67b1ec] rounded text-[#8cb4db] hover:text-white transition-all cursor-pointer shadow-md`,title:`Minimize to Taskbar`,children:(0,j.jsx)(c,{className:`w-3 h-3`})}),E&&(0,j.jsx)(`button`,{type:`button`,onClick:E,className:`p-1 bg-[#101e2e]/90 hover:bg-rose-900/70 border border-[#3e6080]/80 hover:border-rose-400 rounded text-[#8cb4db] hover:text-rose-200 transition-all cursor-pointer shadow-md`,title:`Leave Parlor (Esc)`,children:(0,j.jsx)(g,{className:`w-3 h-3`})})]}),(0,j.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,j.jsxs)(`span`,{className:`font-mono text-sm sm:text-base font-bold text-[#f3cb65] tracking-wide drop-shadow-[0_1px_2px_rgba(0,0,0,0.9)]`,children:[`-`,e||`Princess Aurelia`,`-`]}),_&&(0,j.jsx)(`span`,{className:`hidden md:inline-block text-[9px] font-mono text-[#8cb4db] bg-[#101d2c]/80 border border-[#3e6080]/60 px-1.5 py-0.2 rounded uppercase tracking-wider`,children:_})]}),(0,j.jsxs)(`div`,{className:`min-h-[48px] sm:min-h-[54px] flex flex-col justify-start`,children:[r?(0,j.jsxs)(`div`,{className:`flex items-center gap-2 py-1 text-xs sm:text-sm font-mono text-[#8cb4db]`,children:[(0,j.jsx)(`span`,{className:`inline-block w-2 h-2 bg-[#f3cb65] rounded-full animate-ping`}),(0,j.jsxs)(`span`,{children:[e||`Princess Aurelia`,` is attuning the crystal relay...`]})]}):(0,j.jsxs)(`div`,{className:`font-mono text-xs sm:text-sm md:text-[15px] leading-relaxed text-[#e6edf4] select-text`,children:[(e=>e.split(/(\*[^*]+\*)/g).map((e,t)=>e.startsWith(`*`)&&e.endsWith(`*`)?(0,j.jsx)(`span`,{className:`text-[#f3cb65] italic font-semibold mr-1 inline-block`,children:e},t):(0,j.jsx)(`span`,{children:e},t)))(Y),K&&(0,j.jsx)(`span`,{className:`inline-block w-1.5 h-3.5 bg-[#f3cb65] ml-1 animate-pulse align-middle`})]}),s&&s.length>0&&!r&&(0,j.jsx)(`div`,{className:`mt-2 flex flex-wrap gap-1.5 select-none`,children:s.map((e,t)=>(0,j.jsxs)(`span`,{className:`px-2 py-0.5 rounded bg-[#102438] border border-[#44729b] text-[10px] font-mono font-bold text-[#bfe1ff] flex items-center gap-1`,children:[(0,j.jsx)(y,{className:`w-2.5 h-2.5 text-[#f3cb65]`}),(0,j.jsxs)(`span`,{children:[`Enchantment: `,e.name]})]},t))})]}),(0,j.jsx)(`div`,{className:`flex flex-col gap-1 pt-1`,onClick:e=>e.stopPropagation(),children:q.map((e,t)=>{let i=t+1,a=J===t;return(0,j.jsxs)(`button`,{type:`button`,disabled:r||n,onClick:()=>l(e),onMouseEnter:()=>L(t),className:`w-full sm:max-w-[90%] md:max-w-[85%] text-left flex items-center gap-2 px-2.5 py-1 rounded-xs sm:rounded-sm transition-all select-none font-mono text-xs sm:text-sm disabled:opacity-40 disabled:cursor-not-allowed ${a&&!r&&!n?`bg-[#1c3e61]/80 border border-[#4883b6]/80 shadow-[0_0_12px_rgba(72,131,182,0.25)] cursor-pointer`:`border border-transparent hover:bg-[#1c3e61]/35 cursor-pointer`}`,children:[(0,j.jsxs)(`span`,{className:`font-bold shrink-0 ${a?`text-[#e2ecf7]`:`text-[#b4c8dc]`}`,children:[i,`.`]}),(0,j.jsxs)(`span`,{className:`truncate font-medium ${a?`text-[#f3cb65]`:`text-[#dde7f2]`}`,children:[`[`,e,`]`]})]},t)})})]}),(0,j.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),Z()},onClick:e=>e.stopPropagation(),className:`w-full rounded-md sm:rounded-lg text-white py-2 sm:py-2.5 pr-3 sm:pr-4 pl-8 sm:pl-14 md:pl-16 lg:pl-18 flex items-center gap-2 backdrop-blur-md transition-all select-none`,style:P,children:[(0,j.jsx)(`span`,{className:`font-mono text-sm sm:text-base font-bold text-[#e2ecf7] select-none pl-0.5 shrink-0`,children:`>`}),(0,j.jsxs)(`div`,{className:`flex-1 flex items-center bg-[#101e2e]/90 border border-[#3b5d7d] rounded px-2.5 py-1 focus-within:border-[#67b1ec] focus-within:ring-1 focus-within:ring-[#67b1ec]/40 shadow-inner`,children:[(0,j.jsx)(`span`,{className:`text-[#f3cb65] font-mono text-xs sm:text-sm select-none mr-1.5 shrink-0`,children:`[`}),(0,j.jsx)(`input`,{ref:G,type:`text`,value:R,onChange:e=>z(e.target.value),onFocus:()=>V(!0),onBlur:()=>V(!1),disabled:r||n,placeholder:`Speak with ${e||`Princess Aurelia`}...`,className:`flex-1 bg-transparent border-none text-[#e2ecf7] placeholder-[#f3cb65]/70 font-mono text-xs sm:text-sm focus:outline-none disabled:opacity-50 disabled:cursor-not-allowed`}),(0,j.jsx)(`span`,{className:`text-[#f3cb65] font-mono text-xs sm:text-sm select-none ml-1.5 shrink-0`,children:`]`})]}),(0,j.jsxs)(`button`,{type:`submit`,disabled:r||n||!R.trim(),className:`bg-[#34597b] hover:bg-[#3f6990] active:bg-[#2b4c6e] disabled:opacity-40 disabled:cursor-not-allowed border border-[#5c8cb5] hover:border-[#8db7dc] rounded px-3 sm:px-4 py-1 text-xs sm:text-sm font-mono font-bold text-white transition-all cursor-pointer shadow-md select-none shrink-0 flex items-center`,children:[(0,j.jsx)(`span`,{className:`text-[#f3cb65]`,children:`[`}),(0,j.jsx)(`span`,{className:`text-white px-1`,children:`Send`}),(0,j.jsx)(`span`,{className:`text-[#f3cb65]`,children:`]`})]})]})]})}function I({currentFloor:e,onClose:t}){let n=b(e),r=Math.min(100,Math.round(e/150*100));return(0,j.jsx)(`div`,{className:`absolute inset-0 z-50 bg-ink-black/40 backdrop-blur-xs flex items-center justify-center p-3 sm:p-4 animate-in fade-in duration-200 select-none`,onClick:t,children:(0,j.jsxs)(`div`,{className:`bg-[#FFFDF0] border-[3px] border-ink-black rounded-xl p-4 sm:p-5 max-w-md w-full shadow-[6px_6px_0px_0px_#1E293B] flex flex-col gap-3.5`,onClick:e=>e.stopPropagation(),children:[(0,j.jsxs)(`div`,{className:`flex items-center justify-between border-b-[2px] border-ink-black pb-2`,children:[(0,j.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,j.jsx)(i,{className:`w-5 h-5 text-indigo-600`}),(0,j.jsx)(`h4`,{className:`font-headline-md font-bold text-sm text-ink-black m-0`,children:`Journey to the Big-O Spire`})]}),(0,j.jsx)(`button`,{type:`button`,onClick:t,className:`p-1 hover:bg-slate-200 rounded text-slate-700 cursor-pointer`,title:`Close`,children:(0,j.jsx)(g,{className:`w-4 h-4`})})]}),(0,j.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,j.jsxs)(`div`,{className:`flex items-center justify-between text-xs font-bold font-headline-md`,children:[(0,j.jsx)(`span`,{children:`Path Progress:`}),(0,j.jsxs)(`span`,{className:`font-arcade bg-indigo-100 text-indigo-900 px-2 py-0.5 rounded border border-indigo-300`,children:[e,` / 150 Leagues`]})]}),(0,j.jsx)(`div`,{className:`w-full bg-slate-200 h-4 border-[2px] border-ink-black rounded-full overflow-hidden p-0.5`,children:(0,j.jsx)(`div`,{className:`bg-gradient-to-r from-amber-400 via-yellow-400 to-emerald-400 h-full rounded-full transition-all duration-500`,style:{width:`${r}%`}})}),(0,j.jsxs)(`div`,{className:`flex items-center justify-between text-[11px] text-trash-gray font-medium`,children:[(0,j.jsxs)(`span`,{children:[`Progress: `,(0,j.jsxs)(`strong`,{children:[r,`%`]})]}),(0,j.jsxs)(`span`,{children:[`Distance to Tower: `,(0,j.jsxs)(`strong`,{children:[Math.max(0,150-e),` leagues`]})]})]})]}),(0,j.jsxs)(`div`,{className:`bg-white border-[2px] border-ink-black rounded-lg p-3 shadow-[2px_2px_0px_0px_#1E293B] flex flex-col gap-1`,children:[(0,j.jsx)(`div`,{className:`text-[10px] font-bold uppercase text-amber-700 tracking-wider`,children:`Current Realm:`}),(0,j.jsx)(`div`,{className:`font-bold text-xs text-ink-black`,children:n.title}),(0,j.jsx)(`p`,{className:`text-[11px] text-slate-600 m-0 leading-relaxed font-medium`,children:n.description}),(0,j.jsxs)(`div`,{className:`text-[10px] text-amber-900 bg-amber-50 p-1.5 rounded border border-amber-200 italic mt-1`,children:[`📜 `,n.bgLore]})]}),(0,j.jsx)(`div`,{className:`flex items-center justify-between gap-1 text-center`,children:[{floor:30,label:`Arrays`},{floor:60,label:`Pointers`},{floor:90,label:`Trees`},{floor:120,label:`Heaps`},{floor:150,label:`Spire`}].map(t=>{let n=e>=t.floor;return(0,j.jsxs)(`div`,{className:`flex-1 p-1.5 rounded border text-[10px] flex flex-col items-center ${n?`bg-emerald-100 border-emerald-600 text-emerald-900 font-bold`:`bg-slate-100 border-slate-300 text-slate-500`}`,children:[(0,j.jsx)(`span`,{children:n?`✓`:t.floor}),(0,j.jsx)(`span`,{className:`text-[9px] truncate w-full`,children:t.label})]},t.floor)})}),(0,j.jsx)(`div`,{className:`flex items-center justify-end border-t border-slate-200 pt-2 mt-1`,children:(0,j.jsx)(`button`,{type:`button`,onClick:t,className:`px-4 py-1.5 bg-white hover:bg-slate-100 border-[1.5px] border-ink-black rounded font-bold text-xs text-ink-black cursor-pointer shadow-xs active:translate-y-0.5`,children:`Done`})})]})})}function L({unlockedLetters:e,spireChronicles:t,currentFloor:n,heroCodex:r,episodicEvents:i,recentToolTelemetry:s,onRemoveCodexItem:c,onClose:d}){let[m,h]=(0,O.useState)(`letters`),[b,S]=(0,O.useState)(e[e.length-1]||null);return(0,j.jsx)(`div`,{className:`absolute inset-0 z-50 bg-ink-black/50 backdrop-blur-xs flex items-center justify-center p-3 sm:p-4 animate-in fade-in duration-200 select-none`,onClick:d,children:(0,j.jsxs)(`div`,{className:`bg-[#FFFDF0] border-[3px] border-ink-black rounded-xl max-w-lg w-full h-[85%] max-h-[560px] shadow-[6px_6px_0px_0px_#1E293B] flex flex-col overflow-hidden`,onClick:e=>e.stopPropagation(),children:[(0,j.jsxs)(`div`,{className:`bg-white border-b-[2px] border-ink-black px-4 py-2.5 flex items-center justify-between shrink-0`,children:[(0,j.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,j.jsx)(a,{className:`w-5 h-5 text-amber-700`}),(0,j.jsx)(`h4`,{className:`font-headline-md font-bold text-sm text-ink-black m-0`,children:`The Royal Satchel`})]}),(0,j.jsx)(`button`,{type:`button`,onClick:d,className:`p-1 hover:bg-slate-200 rounded text-slate-700 cursor-pointer`,title:`Close`,children:(0,j.jsx)(g,{className:`w-4 h-4`})})]}),(0,j.jsxs)(`div`,{className:`flex border-b-2 border-ink-black bg-amber-100/70 shrink-0`,children:[(0,j.jsxs)(`button`,{type:`button`,onClick:()=>h(`letters`),className:`flex-1 py-2 text-xs font-bold font-headline-md flex items-center justify-center gap-1.5 transition-colors cursor-pointer border-r border-ink-black/20 ${m===`letters`?`bg-[#FFFDF0] text-amber-950 border-b-2 border-b-[#FFFDF0] -mb-[2px]`:`text-slate-600 hover:bg-amber-200/50`}`,children:[(0,j.jsx)(a,{className:`w-3.5 h-3.5`}),(0,j.jsxs)(`span`,{children:[`Missives (`,e.length,`/5)`]})]}),(0,j.jsxs)(`button`,{type:`button`,onClick:()=>h(`diary`),className:`flex-1 py-2 text-xs font-bold font-headline-md flex items-center justify-center gap-1.5 transition-colors cursor-pointer border-r border-ink-black/20 ${m===`diary`?`bg-[#FFFDF0] text-amber-950 border-b-2 border-b-[#FFFDF0] -mb-[2px]`:`text-slate-600 hover:bg-amber-200/50`}`,children:[(0,j.jsx)(l,{className:`w-3.5 h-3.5`}),(0,j.jsxs)(`span`,{children:[`Chronicles (`,t.length,`)`]})]}),(0,j.jsxs)(`button`,{type:`button`,onClick:()=>h(`codex`),className:`flex-1 py-2 text-xs font-bold font-headline-md flex items-center justify-center gap-1.5 transition-colors cursor-pointer ${m===`codex`?`bg-[#FFFDF0] text-amber-950 border-b-2 border-b-[#FFFDF0] -mb-[2px]`:`text-slate-600 hover:bg-amber-200/50`}`,children:[(0,j.jsx)(y,{className:`w-3.5 h-3.5 text-amber-700`}),(0,j.jsx)(`span`,{children:`Codex`})]})]}),(0,j.jsxs)(`div`,{className:`flex-1 p-3 sm:p-4 overflow-y-auto custom-scrollbar flex flex-col gap-3 min-h-0`,children:[m===`letters`&&(0,j.jsxs)(`div`,{className:`flex flex-col gap-3 flex-1`,children:[(0,j.jsx)(`div`,{className:`flex items-center gap-1.5 overflow-x-auto pb-1`,children:[30,60,90,120,150].map(e=>{let t=x[e],r=n>=e,i=b?.floor===e;return(0,j.jsxs)(`button`,{type:`button`,disabled:!r,onClick:()=>r&&S(t),className:`px-3 py-1 rounded-full text-[11px] font-bold border-[1.5px] border-ink-black flex items-center gap-1 shrink-0 transition-all cursor-pointer ${r?i?`bg-[#FFE24C] text-ink-black shadow-[1.5px_1.5px_0px_0px_#1E293B]`:`bg-white hover:bg-amber-100 text-slate-800`:`opacity-40 bg-slate-200 text-slate-500 cursor-not-allowed`}`,children:[r?(0,j.jsx)(`span`,{children:`📜`}):(0,j.jsx)(o,{className:`w-3 h-3`}),(0,j.jsxs)(`span`,{children:[`League `,e]})]},e)})}),b?(0,j.jsxs)(`div`,{className:`bg-[#FFF9E6] border-[2px] border-amber-900/40 rounded-lg p-4 shadow-sm flex-1 overflow-y-auto custom-scrollbar flex flex-col select-text`,children:[(0,j.jsxs)(`div`,{className:`border-b border-amber-800/20 pb-2 mb-3 flex items-center justify-between`,children:[(0,j.jsxs)(`div`,{children:[(0,j.jsxs)(`div`,{className:`text-[10px] font-bold text-amber-800 uppercase tracking-wider`,children:[b.chapterTitle,` • League `,b.floor]}),(0,j.jsx)(`h5`,{className:`font-headline-md font-bold text-sm text-amber-950 m-0`,children:b.title})]}),(0,j.jsx)(`span`,{className:`text-xl`,children:`🪶`})]}),(0,j.jsx)(`p`,{className:`text-xs sm:text-[13px] text-amber-950 font-serif leading-relaxed whitespace-pre-wrap flex-1 italic`,children:b.letterText})]}):(0,j.jsxs)(`div`,{className:`flex-1 flex flex-col items-center justify-center text-center p-6 text-slate-500`,children:[(0,j.jsx)(o,{className:`w-8 h-8 mb-2 text-slate-400`}),(0,j.jsx)(`p`,{className:`text-xs font-medium`,children:`Conquer 30 LeetCode problems along the path to receive your first Royal Missive from Aurelia.`})]})]}),m===`diary`&&(0,j.jsx)(`div`,{className:`flex flex-col gap-2.5 flex-1`,children:t.length>0?t.map(e=>(0,j.jsxs)(`div`,{className:`p-3 bg-white border-[1.5px] border-ink-black rounded-lg shadow-xs flex flex-col gap-1 select-text`,children:[(0,j.jsxs)(`div`,{className:`flex items-center justify-between text-[10px] text-amber-800 font-bold border-b border-slate-100 pb-1`,children:[(0,j.jsxs)(`span`,{children:[`League `,e.floor,` along the Path`]}),(0,j.jsx)(`span`,{children:new Date(e.timestamp).toLocaleDateString()})]}),(0,j.jsxs)(`p`,{className:`text-xs text-ink-black font-medium leading-relaxed m-0 italic font-serif`,children:[`“`,e.text,`”`]})]},e.id)):(0,j.jsxs)(`div`,{className:`flex-1 flex flex-col items-center justify-center text-center p-6 text-slate-500`,children:[(0,j.jsx)(l,{className:`w-8 h-8 mb-2 text-slate-400`}),(0,j.jsx)(`p`,{className:`text-xs font-medium`,children:`Aurelia records entries in her Spire Chronicles autonomously as you chat, rest, and cross chapter milestones.`})]})}),m===`codex`&&(0,j.jsxs)(`div`,{className:`flex flex-col gap-3 flex-1 select-text`,children:[(0,j.jsxs)(`div`,{className:`bg-white border-[1.5px] border-ink-black rounded-lg p-3 shadow-xs flex flex-col gap-2`,children:[(0,j.jsxs)(`div`,{className:`flex items-center justify-between border-b border-slate-100 pb-1.5`,children:[(0,j.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,j.jsx)(y,{className:`w-4 h-4 text-amber-600`}),(0,j.jsx)(`h5`,{className:`font-headline-md font-bold text-xs text-ink-black m-0`,children:`Hero Codex (MemGPT & Mem0 Core Memory)`})]}),(0,j.jsx)(`span`,{className:`text-[10px] text-slate-400 font-mono`,children:`Cognitive Sync`})]}),(0,j.jsxs)(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-2 text-xs`,children:[(0,j.jsxs)(`div`,{className:`bg-[#FFFDF0] border border-amber-900/20 rounded p-2`,children:[(0,j.jsx)(`span`,{className:`text-[10px] font-bold text-slate-500 uppercase tracking-wider block`,children:`Hero Alias`}),(0,j.jsx)(`span`,{className:`font-bold text-ink-black text-xs`,children:r?.heroName||`Champion`})]}),(0,j.jsxs)(`div`,{className:`bg-[#FFFDF0] border border-amber-900/20 rounded p-2`,children:[(0,j.jsx)(`span`,{className:`text-[10px] font-bold text-slate-500 uppercase tracking-wider block`,children:`Target Goal`}),(0,j.jsx)(`span`,{className:`font-bold text-amber-900 text-xs`,children:r?.targetGoal||`None shared yet (mention to Aurelia!)`})]})]}),r?.preferredLanguage&&(0,j.jsxs)(`div`,{className:`bg-[#FFFDF0] border border-amber-900/20 rounded p-2 text-xs`,children:[(0,j.jsx)(`span`,{className:`text-[10px] font-bold text-slate-500 uppercase tracking-wider block`,children:`Weapon of Choice (Language)`}),(0,j.jsx)(`span`,{className:`font-bold text-ink-black`,children:r.preferredLanguage})]})]}),(0,j.jsxs)(`div`,{className:`bg-white border-[1.5px] border-ink-black rounded-lg p-3 shadow-xs flex flex-col gap-2`,children:[(0,j.jsxs)(`div`,{className:`flex items-center gap-1.5 text-xs font-bold text-emerald-800`,children:[(0,j.jsx)(p,{className:`w-3.5 h-3.5`}),(0,j.jsxs)(`span`,{children:[`Mastered Patterns (`,r?.strengths?.length||0,`)`]})]}),r?.strengths&&r.strengths.length>0?(0,j.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:r.strengths.map(e=>(0,j.jsxs)(`span`,{className:`inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[11px] font-bold bg-emerald-50 text-emerald-800 border border-emerald-300`,children:[e,c&&(0,j.jsx)(`button`,{type:`button`,onClick:()=>c(`strengths`,e),className:`hover:text-red-600 ml-0.5 cursor-pointer`,title:`Forget strength`,children:(0,j.jsx)(g,{className:`w-3 h-3`})})]},e))}):(0,j.jsx)(`p`,{className:`text-[11px] text-slate-400 italic m-0`,children:`Aurelia will note topics you conquer during your practice.`})]}),(0,j.jsxs)(`div`,{className:`bg-white border-[1.5px] border-ink-black rounded-lg p-3 shadow-xs flex flex-col gap-2`,children:[(0,j.jsxs)(`div`,{className:`flex items-center gap-1.5 text-xs font-bold text-rose-800`,children:[(0,j.jsx)(v,{className:`w-3.5 h-3.5`}),(0,j.jsxs)(`span`,{children:[`Nemesis Patterns (`,r?.nemesisPatterns?.length||0,`)`]})]}),r?.nemesisPatterns&&r.nemesisPatterns.length>0?(0,j.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:r.nemesisPatterns.map(e=>(0,j.jsxs)(`span`,{className:`inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[11px] font-bold bg-rose-50 text-rose-800 border border-rose-300`,children:[e,c&&(0,j.jsx)(`button`,{type:`button`,onClick:()=>c(`nemesisPatterns`,e),className:`hover:text-red-700 ml-0.5 cursor-pointer`,title:`Forget nemesis`,children:(0,j.jsx)(g,{className:`w-3 h-3`})})]},e))}):(0,j.jsx)(`p`,{className:`text-[11px] text-slate-400 italic m-0`,children:`Aurelia tracks patterns that give you trouble to help you prepare targeted drills.`})]}),(0,j.jsxs)(`div`,{className:`bg-white border-[1.5px] border-ink-black rounded-lg p-3 shadow-xs flex flex-col gap-2`,children:[(0,j.jsx)(`div`,{className:`text-xs font-bold text-slate-800`,children:(0,j.jsxs)(`span`,{children:[`Personal Notes & Shared Lore (`,r?.personalNotes?.length||0,`)`]})}),r?.personalNotes&&r.personalNotes.length>0?(0,j.jsx)(`div`,{className:`flex flex-col gap-1.5`,children:r.personalNotes.map(e=>(0,j.jsxs)(`div`,{className:`flex items-start justify-between gap-2 p-2 bg-slate-50 border border-slate-200 rounded text-[11px] text-slate-700`,children:[(0,j.jsxs)(`span`,{children:[`• `,e]}),c&&(0,j.jsx)(`button`,{type:`button`,onClick:()=>c(`personalNotes`,e),className:`text-slate-400 hover:text-red-600 shrink-0 cursor-pointer p-0.5`,title:`Forget note`,children:(0,j.jsx)(_,{className:`w-3 h-3`})})]},e))}):(0,j.jsx)(`p`,{className:`text-[11px] text-slate-400 italic m-0`,children:`Share your background or routine with Aurelia and she will hold it in her memory.`})]}),i&&i.length>0&&(0,j.jsxs)(`div`,{className:`bg-white border-[1.5px] border-ink-black rounded-lg p-3 shadow-xs flex flex-col gap-2`,children:[(0,j.jsxs)(`div`,{className:`flex items-center justify-between border-b border-slate-100 pb-1`,children:[(0,j.jsx)(`span`,{className:`text-xs font-bold text-slate-800`,children:`Episodic Memory Chain (EM-LLM)`}),(0,j.jsxs)(`span`,{className:`text-[10px] text-slate-400 font-mono`,children:[i.length,` events`]})]}),(0,j.jsx)(`div`,{className:`flex flex-col gap-2 max-h-40 overflow-y-auto custom-scrollbar`,children:i.slice(0,8).map(e=>(0,j.jsxs)(`div`,{className:`text-[11px] p-2 bg-[#FFFDF0] border border-amber-900/15 rounded flex flex-col gap-0.5`,children:[(0,j.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,j.jsx)(`span`,{className:`font-bold text-ink-black uppercase text-[9px] px-1.5 py-0.5 bg-amber-200/60 rounded`,children:e.eventType.replace(`_`,` `)}),(0,j.jsx)(`span`,{className:`text-[10px] text-slate-400`,children:new Date(e.timestamp).toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`})})]}),(0,j.jsx)(`div`,{className:`font-bold text-slate-800 mt-0.5`,children:e.title}),(0,j.jsx)(`div`,{className:`text-slate-600 text-[10px]`,children:e.description})]},e.id))})]}),(0,j.jsxs)(`div`,{className:`bg-white border-[1.5px] border-ink-black rounded-lg p-3 shadow-xs flex flex-col gap-2`,children:[(0,j.jsxs)(`div`,{className:`flex items-center justify-between border-b border-slate-100 pb-1`,children:[(0,j.jsxs)(`div`,{className:`flex items-center gap-1.5 text-xs font-bold text-indigo-900`,children:[(0,j.jsx)(u,{className:`w-3.5 h-3.5 text-amber-500`}),(0,j.jsx)(`span`,{children:`Autonomous Enchantment Telemetry`})]}),(0,j.jsxs)(`span`,{className:`text-[10px] text-slate-400 font-mono`,children:[s?.length||0,` executed`]})]}),s&&s.length>0?(0,j.jsx)(`div`,{className:`flex flex-col gap-1.5 max-h-36 overflow-y-auto custom-scrollbar`,children:s.slice(0,10).map((e,t)=>(0,j.jsxs)(`div`,{className:`text-[11px] p-2 bg-indigo-50/50 border border-indigo-100 rounded flex items-center justify-between gap-2`,children:[(0,j.jsxs)(`div`,{className:`flex flex-col min-w-0`,children:[(0,j.jsxs)(`span`,{className:`font-bold text-indigo-950 font-mono text-[10px] truncate`,children:[e.tool_name,`()`]}),e.args&&Object.keys(e.args).length>0&&(0,j.jsx)(`span`,{className:`text-[9px] text-slate-500 truncate`,children:JSON.stringify(e.args).slice(0,50)})]}),(0,j.jsxs)(`div`,{className:`flex items-center gap-2 shrink-0`,children:[e.execution_time_ms!==void 0&&(0,j.jsxs)(`span`,{className:`text-[9px] text-slate-400 flex items-center gap-0.5 font-mono`,children:[(0,j.jsx)(f,{className:`w-2.5 h-2.5`}),e.execution_time_ms,`ms`]}),(0,j.jsx)(`span`,{className:`px-1.5 py-0.2 text-[9px] font-bold rounded ${e.success?`bg-emerald-100 text-emerald-800`:`bg-rose-100 text-rose-800`}`,children:e.success?`SUCCESS`:`ERR`})]})]},t))}):(0,j.jsx)(`p`,{className:`text-[11px] text-slate-400 italic m-0`,children:`No autonomous enchantments executed yet in this session.`})]})]})]}),(0,j.jsx)(`div`,{className:`bg-white border-t border-slate-200 px-4 py-2 flex items-center justify-end shrink-0`,children:(0,j.jsx)(`button`,{type:`button`,onClick:d,className:`px-4 py-1.5 bg-white hover:bg-slate-100 border-[1.5px] border-ink-black rounded font-bold text-xs text-ink-black cursor-pointer shadow-xs active:translate-y-0.5`,children:`Close`})})]})})}var R=e({default:()=>z});function z({onClose:e,onMinimize:t,isActive:r=!0,onFocus:i,zIndex:a}){let o=E(),[s,c]=(0,O.useState)(w()),[l,u]=(0,O.useState)(!1),[d,f]=(0,O.useState)(!1),[p,h]=(0,O.useState)(!1);(0,O.useEffect)(()=>{C.syncWithBackend(),C.triggerProactiveGreeting()},[]);let _=(0,O.useCallback)(()=>{e?e():D.getState().closeWindow(`companion`)},[e]),v=(0,O.useCallback)(()=>{t?t():D.getState().minimizeWindow(`companion`)},[t]),y=(0,O.useCallback)(()=>{i?i():D.getState().setActiveWindow(`companion`)},[i]),b=(0,O.useCallback)(()=>{let e=!s;c(e),S(e)},[s]),x=(0,O.useCallback)(()=>{window.confirm(`Clear conversation transcript with Princess Aurelia?`)&&C.clearTranscript()},[]),T=(0,O.useCallback)(e=>{C.setIsTyping(e)},[]),k=(0,O.useMemo)(()=>[...o.transcript].reverse().find(e=>e.sender===`princess`)||o.transcript[0],[o.transcript]),A=`Welcome back to the Spire Tower Parlor. How is your day going today? Are you making progress, or could you use a hand?`,N=k?k.isStreaming?k.text:k.text||(o.isLoading?``:A):A,P=(0,O.useMemo)(()=>k?.choiceSuggestions&&k.choiceSuggestions.length>0?k.choiceSuggestions:[...o.transcript].reverse().find(e=>e.sender===`princess`&&e.choiceSuggestions&&e.choiceSuggestions.length>0)?.choiceSuggestions,[k,o.transcript]);return(0,j.jsxs)(`div`,{onClick:y,className:`fixed inset-x-0 top-0 bottom-[40px] select-none pointer-events-none overflow-hidden font-sans`,style:{zIndex:a??(r?40:30)},children:[(0,j.jsx)(`div`,{className:`absolute inset-x-0 bottom-0 h-44 bg-gradient-to-t from-slate-950/35 via-slate-900/10 to-transparent pointer-events-none z-0`}),(0,j.jsxs)(`div`,{className:`relative w-full h-full flex flex-col justify-end pointer-events-none pb-2 sm:pb-3 px-2 sm:px-4 md:px-8`,children:[(0,j.jsxs)(`div`,{className:`relative w-full max-w-5xl lg:max-w-6xl mx-auto flex items-end justify-start pointer-events-none`,children:[(0,j.jsx)(`div`,{className:`relative z-30 shrink-0 pointer-events-auto -mr-6 sm:-mr-10 md:-mr-12 lg:-mr-14`,children:(0,j.jsx)(M,{emotion:o.activeEmotion,floor:o.currentFloor,rhythm:o.currentRhythm,activity:o.currentActivity,isLoading:o.isLoading,onClick:y})}),(0,j.jsx)(`div`,{className:`relative z-20 flex-1 min-w-0 pointer-events-auto mb-1`,children:(0,j.jsx)(F,{characterName:o.companionSettings.name||`Princess Aurelia`,emotion:o.activeEmotion,text:N,isStreaming:k?.isStreaming,isLoading:o.isLoading,choices:P,toolCalls:k?.toolCalls,onSelectChoice:e=>C.sendMessage(e),onSendMessage:e=>C.sendMessage(e),onTypingStatusChange:T,currentFloor:o.currentFloor,bondTier:o.bondTier,satchelCount:o.unlockedLetters.length,isMuted:s,onToggleMute:b,onOpenProgress:()=>u(!0),onOpenSatchel:()=>f(!0),onOpenHistory:()=>h(!0),onMinimize:v,onClose:_})})]}),(0,j.jsxs)(`div`,{className:`absolute bottom-1 right-3.5 pointer-events-none z-30 hidden md:flex flex-col items-center gap-0.5 opacity-65 select-none`,children:[(0,j.jsx)(`svg`,{className:`w-8 h-8 text-[#9cbcdb] drop-shadow-[0_0_6px_rgba(156,188,219,0.5)] rotate-6`,viewBox:`0 0 24 24`,fill:`currentColor`,children:(0,j.jsx)(`path`,{d:`M12 2 C12 7.8 7.8 12 2 12 C7.8 12 12 16.2 12 22 C12 16.2 16.2 12 22 12 C16.2 12 12 7.8 12 2 Z`})}),(0,j.jsxs)(`div`,{className:`font-mono text-[9px] text-[#7ba4c8] tracking-tight leading-tight text-center`,children:[(0,j.jsx)(`div`,{children:`AlgoSpaced (Beta)`}),(0,j.jsx)(`div`,{children:`Build Jun24 preview`})]})]})]}),l&&(0,j.jsx)(`div`,{className:`pointer-events-auto`,children:(0,j.jsx)(I,{currentFloor:o.currentFloor,totalSolved:o.totalSolved,onClose:()=>u(!1)})}),d&&(0,j.jsx)(`div`,{className:`pointer-events-auto`,children:(0,j.jsx)(L,{unlockedLetters:o.unlockedLetters,spireChronicles:o.spireChronicles,currentFloor:o.currentFloor,heroCodex:o.heroCodex,episodicEvents:o.episodicEvents,recentToolTelemetry:o.recentToolTelemetry,onRemoveCodexItem:C.removeCodexItem,onClose:()=>f(!1)})}),p&&(0,j.jsx)(`div`,{className:`fixed inset-0 z-50 bg-black/60 backdrop-blur-xs flex items-center justify-center p-3 sm:p-4 animate-in fade-in duration-200 pointer-events-auto`,onClick:()=>h(!1),children:(0,j.jsxs)(`div`,{className:`bg-[#142335] border-[3px] border-[#5a80a2] rounded-xl max-w-lg w-full h-[80%] max-h-[520px] shadow-[0_16px_40px_rgba(0,0,0,0.85)] flex flex-col overflow-hidden text-white`,onClick:e=>e.stopPropagation(),style:{boxShadow:`inset 0 0 0 1px #0a1420, inset 0 1px 0 rgba(255, 255, 255, 0.15), 0 16px 40px rgba(0, 0, 0, 0.85)`},children:[(0,j.jsxs)(`div`,{className:`bg-[#101b2a] border-b border-[#304f6f] px-4 py-2.5 flex items-center justify-between shrink-0`,children:[(0,j.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,j.jsx)(m,{className:`w-4 h-4 text-[#67b1ec]`}),(0,j.jsxs)(`h4`,{className:`font-mono font-bold text-xs sm:text-sm text-[#e6f0fa] m-0`,children:[`Dialogue Transcript (`,o.transcript.length,` turns)`]})]}),(0,j.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,j.jsxs)(`button`,{type:`button`,onClick:x,className:`px-2 py-0.5 bg-rose-950/60 hover:bg-rose-900 border border-rose-700/60 rounded text-[11px] font-mono font-bold text-rose-300 hover:text-white flex items-center gap-1 cursor-pointer mr-1 transition-colors`,title:`Clear Chat History`,children:[(0,j.jsx)(n,{className:`w-3 h-3`}),(0,j.jsx)(`span`,{children:`Clear`})]}),(0,j.jsx)(`button`,{type:`button`,onClick:()=>h(!1),className:`p-1 hover:bg-[#203a55] rounded text-[#8cb4db] hover:text-white cursor-pointer transition-colors`,title:`Close`,children:(0,j.jsx)(g,{className:`w-4 h-4`})})]})]}),(0,j.jsx)(`div`,{className:`flex-1 p-3 sm:p-4 overflow-y-auto custom-scrollbar flex flex-col gap-2.5 bg-[#0e1824]/90`,children:o.transcript.map((e,t)=>(0,j.jsxs)(`div`,{className:`p-2.5 rounded-lg border font-mono text-xs max-w-[90%] shadow-md ${e.sender===`princess`?`bg-[#182c42] border-[#3e6080] text-[#e6f0fa] self-start`:`bg-[#214365] border-[#5a8bb9] text-white self-end`}`,children:[(0,j.jsx)(`div`,{className:`text-[10px] font-bold mb-1 text-[#f6d267]`,children:e.sender===`princess`?o.companionSettings.name:`Hero`}),(0,j.jsx)(`p`,{className:`font-medium m-0 leading-relaxed whitespace-pre-wrap select-text`,children:e.text})]},e.id||t))})]})})]})}export{R as t};1234import{r as e}from"./rolldown-runtime-hePW80VL.js";import{Bt as t,F as n,G as ee,Ht as r,M as i,N as te,Tt as a,a as o,d as s,f as c,ht as ne,lt as re,nt as ie,o as ae,ot as l,p as oe,q as se,rt as u,tt as ce,wt as le,x as d}from"./vendor-react-hnaVBnLv.js";import{u as f}from"./index-DVWZ15xt.js";import{n as p,t as m}from"./MarkdownRenderer-D8UdFpnD.js";import{n as h}from"./ReviewQueue-CltGWQpb.js";var g=e(r(),1),_=t(),ue=[`Arrays & Hashing`,`Two Pointers`,`Sliding Window`,`Stack`,`Binary Search`,`Linked List`,`Trees`,`Tries`,`Heap / Priority Queue`,`Backtracking`,`Graphs`,`Advanced Graphs`,`1-D Dynamic Programming`,`2-D Dynamic Programming`,`Greedy`,`Intervals`,`Math & Geometry`,`Bit Manipulation`];function v(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?`sol-${crypto.randomUUID()}`:`sol-${Date.now()}`}var y=({leftTab:e,onSelectLeftTab:t,mobileView:r,isNarrow:y=!1,problem:b,parsed:x,userSolution:S,officialSolution:C,effectiveReferenceCode:de,copiedSnippet:w,onCopyText:T,saveRefError:E,aiSolutionLoading:D,aiSolutionError:O,onFetchAiSolution:fe,explainLoading:k,explainError:A,explanationText:j,onExplainCode:pe,activeReview:M,onUpdateSolutions:N})=>{let[me,P]=(0,g.useState)(!1),[F,I]=(0,g.useState)(()=>b.id||b.name),[L,R]=(0,g.useState)(0),[z,B]=(0,g.useState)(!1),[V,H]=(0,g.useState)(null),[U,W]=(0,g.useState)({name:``,pattern:`Arrays & Hashing`,time_complexity:`O(N)`,space_complexity:`O(1)`,code:``,explanation:``,is_optimal:!1}),[G,K]=(0,g.useState)(!1),[q,J]=(0,g.useState)(null),Y=b.id||b.name;F!==Y&&(I(Y),P(!1),R(0),B(!1),H(null),J(null));let X=h(b,C,S),Z=L<X.length?L:0,Q=X[Z];(0,g.useEffect)(()=>{if(q){let e=setTimeout(()=>J(null),3500);return()=>clearTimeout(e)}},[q]);let he=async()=>{if(!U.name.trim()){J({type:`error`,message:`Solution name cannot be empty.`});return}if(!U.code.trim()){J({type:`error`,message:`Solution code cannot be empty.`});return}K(!0),J(null);try{let e;if(V)e=X.map(e=>e.id===V?{...e,name:U.name.trim(),pattern:U.pattern.trim()||`General Algorithm`,time_complexity:U.time_complexity.trim()||`O(N)`,space_complexity:U.space_complexity.trim()||`O(1)`,code:U.code,explanation:U.explanation.trim(),is_optimal:U.is_optimal}:U.is_optimal&&e.id!==V?{...e,is_optimal:!1}:e);else{let t={id:v(),name:U.name.trim(),pattern:U.pattern.trim()||`General Algorithm`,time_complexity:U.time_complexity.trim()||`O(N)`,space_complexity:U.space_complexity.trim()||`O(1)`,code:U.code,explanation:U.explanation.trim(),is_optimal:U.is_optimal||X.length===0};e=t.is_optimal?[...X.map(e=>({...e,is_optimal:!1})),t]:[...X,t]}let t=e.find(e=>e.is_optimal)||e[0];b.id&&await f(b.id,e,t?.time_complexity,t?.space_complexity,b),N?.(e),J({type:`success`,message:V?`Solution updated successfully!`:`New solution added to problem dossier!`}),B(!1),H(null),R(V?Z:e.length-1)}catch(e){let t=e instanceof Error?e.message:`Failed to save solution.`;J({type:`error`,message:t})}finally{K(!1)}},ge=async e=>{if(X.length<=1){J({type:`error`,message:`Problem must have at least one solution.`});return}if(window.confirm(`Are you sure you want to remove this solution?`)){K(!0);try{let t=X.filter(t=>t.id!==e);!t.some(e=>e.is_optimal)&&t.length>0&&(t[0].is_optimal=!0);let n=t.find(e=>e.is_optimal)||t[0];b.id&&await f(b.id,t,n?.time_complexity,n?.space_complexity,b),N?.(t),R(0),J({type:`success`,message:`Solution removed successfully.`})}catch(e){let t=e instanceof Error?e.message:`Failed to delete solution.`;J({type:`error`,message:t})}finally{K(!1)}}},$=e=>`cursor-pointer font-arcade text-[7.5px] min-[400px]:text-[8px] sm:text-[8.5px] transition-all flex items-center justify-center gap-1 sm:gap-1.5 focus:outline-none focus-visible:ring-2 focus-visible:ring-ink-black select-none whitespace-nowrap shrink-0 ${e?`h-10 px-2 sm:px-2.5 bg-paper-white text-ink-black font-extrabold border-t-2 border-x-2 border-b-0 border-ink-black relative z-10 -mb-[2px] pb-[10px] shadow-[0_-2px_0_0_rgba(30,41,59,0.06)] after:content-[''] after:absolute after:-bottom-[2px] after:left-0 after:right-0 after:h-[2.5px] after:bg-paper-white after:z-10`:`h-9 px-2 sm:px-2.5 bg-[#e8e4da] text-slate-700 hover:bg-[#efece3] hover:text-ink-black font-bold border-2 border-ink-black relative z-0 mb-0`}`;return(0,_.jsxs)(`div`,{className:`w-full ${y?`flex flex-1`:`lg:w-[49%] flex`} flex-col bg-paper-white border-b-[3px] lg:border-b-0 ${y?``:`lg:border-r-[3px]`} border-ink-black overflow-hidden ${y&&r!==`spec`&&r!==`ref`?`hidden`:`flex`}`,children:[(0,_.jsxs)(`div`,{className:`shrink-0 bg-[#f4f1ea] border-b-2 border-ink-black px-1.5 sm:px-2.5 pt-2 flex items-end gap-1 relative z-10 overflow-x-auto no-scrollbar`,children:[(0,_.jsxs)(`button`,{onClick:()=>t(`spec`),className:$(e===`spec`),children:[(0,_.jsx)(ce,{className:`w-3 h-3 text-purple-700 shrink-0`}),(0,_.jsx)(`span`,{children:y?`SPEC`:`SPECIFICATIONS`})]}),(0,_.jsxs)(`button`,{onClick:()=>t(`ref`),className:$(e===`ref`),children:[(0,_.jsx)(re,{className:`w-3 h-3 text-blue-700 shrink-0`}),(0,_.jsx)(`span`,{children:y?`SOL (${X.length})`:`SOLUTIONS (${X.length})`})]}),(0,_.jsxs)(`button`,{onClick:()=>t(`fsrs`),className:$(e===`fsrs`),children:[(0,_.jsx)(c,{className:`w-3 h-3 text-emerald-700 shrink-0`}),(0,_.jsx)(`span`,{className:`whitespace-nowrap`,children:y?`FSRS`:`FSRS STATS`})]})]}),(0,_.jsxs)(`div`,{className:`flex-1 overflow-y-auto no-scrollbar p-4 sm:p-5 space-y-4`,children:[e===`spec`&&(0,_.jsxs)(`div`,{className:`space-y-4`,children:[(0,_.jsxs)(`div`,{className:`p-4 bg-white border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] space-y-3.5`,children:[(0,_.jsx)(`div`,{children:(0,_.jsx)(`h2`,{className:`text-base sm:text-lg font-extrabold text-ink-black font-headline-md leading-tight m-0 select-text`,children:b.name||`Algorithm Problem`})}),x.description&&(0,_.jsxs)(`div`,{className:`pt-3.5 border-t border-slate-200`,children:[(0,_.jsxs)(`div`,{className:`text-[9px] font-arcade text-trash-gray uppercase font-bold mb-2 flex items-center gap-1`,children:[(0,_.jsx)(a,{className:`w-3 h-3 text-primary`}),`PROBLEM DESCRIPTION`]}),(0,_.jsx)(`div`,{className:`font-sans text-xs sm:text-[13px] text-slate-800 leading-relaxed space-y-2 font-medium`,children:x.description.split(``).map((e,t)=>e.trim()?(0,_.jsx)(`p`,{className:`m-0 leading-relaxed whitespace-pre-wrap select-text`,children:p(e)},t):(0,_.jsx)(`div`,{className:`h-1.5`},t))})]}),x.examples.length>0&&(0,_.jsxs)(`div`,{className:`pt-3.5 border-t border-slate-200 space-y-2.5`,children:[(0,_.jsxs)(`div`,{className:`text-[9px] font-arcade text-trash-gray uppercase font-bold flex items-center gap-1.5`,children:[(0,_.jsx)(o,{className:`w-3 h-3 text-amber-500`}),`EXAMPLES (`,x.examples.length,`)`]}),(0,_.jsx)(`div`,{className:`space-y-2.5`,children:x.examples.map((e,t)=>(0,_.jsxs)(`div`,{className:`p-3 bg-slate-50 border border-slate-200 space-y-2 text-xs`,children:[(0,_.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,_.jsxs)(`span`,{className:`font-arcade text-[9px] font-bold text-primary`,children:[`EXAMPLE `,t+1]}),e.input&&(0,_.jsxs)(`button`,{onClick:()=>T(e.input,`ex-${t}`),className:`px-2 py-0.5 bg-white hover:bg-slate-100 border border-ink-black text-[9px] font-arcade text-ink-black flex items-center gap-1 cursor-pointer`,title:`Copy input data`,children:[(0,_.jsx)(l,{className:`w-2.5 h-2.5`}),w===`ex-${t}`?`COPIED!`:`COPY`]})]}),e.input&&(0,_.jsxs)(`div`,{className:`space-y-1`,children:[(0,_.jsx)(`span`,{className:`text-[9px] font-arcade text-trash-gray font-bold uppercase block`,children:`Input:`}),(0,_.jsx)(`div`,{className:`bg-[#1E293B] text-[#4ADE80] font-code-mono p-2 border border-ink-black text-[11px] break-all select-text`,children:e.input})]}),e.output&&(0,_.jsxs)(`div`,{className:`space-y-1`,children:[(0,_.jsx)(`span`,{className:`text-[9px] font-arcade text-trash-gray font-bold uppercase block`,children:`Output:`}),(0,_.jsx)(`div`,{className:`bg-[#1E293B] text-[#4ADE80] font-code-mono p-2 border border-ink-black text-[11px] break-all select-text`,children:e.output})]}),e.explanation&&(0,_.jsxs)(`div`,{className:`text-[11px] font-sans text-slate-600 bg-white p-2 border border-slate-200`,children:[(0,_.jsx)(`span`,{className:`font-bold text-slate-700`,children:`Explanation: `}),p(e.explanation)]})]},t))})]}),x.constraints.length>0&&(0,_.jsxs)(`div`,{className:`pt-3.5 border-t border-slate-200`,children:[(0,_.jsx)(`div`,{className:`text-[9px] font-arcade text-trash-gray uppercase font-bold mb-2`,children:`CONSTRAINTS`}),(0,_.jsx)(`ul`,{className:`space-y-1.5 list-none m-0 p-0`,children:x.constraints.map((e,t)=>(0,_.jsxs)(`li`,{className:`flex items-start gap-2 text-xs`,children:[(0,_.jsx)(`span`,{className:`text-primary font-bold select-none`,children:`•`}),(0,_.jsx)(`code`,{className:`bg-slate-100 text-ink-black font-code-mono px-2 py-0.5 border border-slate-300 text-[11px] select-text`,children:e})]},t))})]})]}),me?(0,_.jsxs)(`div`,{className:`p-3 bg-amber-50 border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] flex flex-wrap items-center justify-between gap-2`,children:[(0,_.jsxs)(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[(0,_.jsx)(o,{className:`w-4 h-4 text-amber-600 shrink-0`}),(0,_.jsx)(`span`,{className:`font-arcade text-[9px] font-bold text-ink-black tracking-wide uppercase`,children:`OPTIMAL TARGET:`}),(0,_.jsxs)(`code`,{className:`bg-[#1E293B] text-[#4ADE80] font-code-mono px-2 py-0.5 text-[11px] border border-ink-black font-bold`,children:[`T: `,b.optimal_time||`O(N)`]}),(0,_.jsxs)(`code`,{className:`bg-[#1E293B] text-[#4ADE80] font-code-mono px-2 py-0.5 text-[11px] border border-ink-black font-bold`,children:[`S: `,b.optimal_space||`O(1)`]})]}),(0,_.jsxs)(`button`,{type:`button`,onClick:()=>P(!1),className:`px-2 py-0.5 bg-white hover:bg-slate-100 border border-ink-black font-arcade text-[8px] text-trash-gray hover:text-ink-black cursor-pointer flex items-center gap-1`,title:`Conceal target complexity`,children:[(0,_.jsx)(u,{className:`w-2.5 h-2.5`}),(0,_.jsx)(`span`,{children:`HIDE`})]})]}):(0,_.jsxs)(`div`,{className:`p-3 bg-amber-50/70 border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] flex items-center justify-between gap-2`,children:[(0,_.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,_.jsx)(ee,{className:`w-4 h-4 text-amber-700 shrink-0`}),(0,_.jsxs)(`div`,{children:[(0,_.jsx)(`span`,{className:`font-arcade text-[9px] font-bold text-ink-black tracking-wide uppercase block`,children:`OPTIMAL COMPLEXITY TARGET`}),(0,_.jsx)(`span`,{className:`text-[10px] font-sans text-slate-600 font-semibold`,children:`Hidden to test active recall before coding`})]})]}),(0,_.jsxs)(`button`,{type:`button`,onClick:()=>P(!0),className:`px-2.5 py-1 bg-white hover:bg-amber-100 border-2 border-ink-black font-arcade text-[8.5px] font-bold text-ink-black shadow-[1.5px_1.5px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none transition-all cursor-pointer flex items-center gap-1.5 shrink-0`,title:`Click to reveal target time and space complexity`,children:[(0,_.jsx)(ie,{className:`w-3 h-3 text-amber-700`}),(0,_.jsx)(`span`,{children:`REVEAL TARGET`})]})]})]}),e===`ref`&&(0,_.jsxs)(`div`,{className:`space-y-4`,children:[q&&(0,_.jsxs)(`div`,{className:`p-2.5 border-2 border-ink-black text-xs font-bold flex items-center justify-between shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] ${q.type===`success`?`bg-emerald-100 text-emerald-900 border-emerald-700`:`bg-rose-100 text-rose-900 border-rose-700`}`,children:[(0,_.jsxs)(`div`,{className:`flex items-center gap-2`,children:[q.type===`success`?(0,_.jsx)(ne,{className:`w-4 h-4 text-emerald-700 shrink-0`}):(0,_.jsx)(s,{className:`w-4 h-4 text-rose-700 shrink-0`}),(0,_.jsx)(`span`,{children:q.message})]}),(0,_.jsx)(`button`,{type:`button`,onClick:()=>J(null),className:`text-slate-600 hover:text-ink-black cursor-pointer`,children:(0,_.jsx)(ae,{className:`w-3.5 h-3.5`})})]}),(0,_.jsxs)(`div`,{className:`flex items-center gap-1 p-1 bg-slate-200/90 border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] overflow-x-auto no-scrollbar`,children:[X.map((e,t)=>(0,_.jsxs)(`button`,{type:`button`,onClick:()=>{R(t),B(!1),H(null)},className:`py-1 px-2 rounded-full font-arcade text-[8px] font-bold flex items-center justify-center gap-1 border-2 border-ink-black transition-all cursor-pointer whitespace-nowrap shrink-0 ${Z===t&&!z&&!V?`bg-sky-600 text-white shadow-[1px_1px_0px_0px_rgba(30,41,59,1)] -translate-y-0.5`:`bg-white text-ink-black hover:bg-sky-50 shadow-none`}`,title:e.name?`${e.name} (${e.pattern||`Algorithm`})`:`Solution ${t+1}`,children:[e.is_optimal?(0,_.jsx)(d,{className:`w-3 h-3 text-amber-300`}):(0,_.jsx)(a,{className:`w-3 h-3`}),(0,_.jsx)(`span`,{children:`Sol ${t+1}`}),e.is_optimal&&(0,_.jsx)(`span`,{className:`text-[6.5px] px-1 py-0.2 bg-amber-300 text-ink-black border border-ink-black font-extrabold rounded-full tracking-tight`,children:`OPTIMAL`})]},e.id||t)),(0,_.jsx)(`button`,{type:`button`,onClick:()=>{B(!0),H(null),W({name:`Method ${X.length+1}`,pattern:`Arrays & Hashing`,time_complexity:`O(N)`,space_complexity:`O(1)`,code:``,explanation:``,is_optimal:!1})},className:`h-6 w-6 rounded-full font-arcade text-[9px] font-bold flex items-center justify-center border-2 border-ink-black cursor-pointer shrink-0 active:translate-y-0.5 transition-all shadow-[1px_1px_0px_0px_rgba(30,41,59,1)] ${z?`bg-emerald-600 text-white`:`bg-amber-300 text-ink-black hover:bg-amber-200`}`,title:`Add another solution / method for this problem`,"aria-label":`Add Solution`,children:(0,_.jsx)(te,{className:`w-3 h-3 stroke-[2.5]`})})]}),z||V?(0,_.jsxs)(`div`,{className:`p-4 bg-white border-2 border-ink-black shadow-[3px_3px_0px_0px_rgba(30,41,59,1)] space-y-3.5`,children:[(0,_.jsxs)(`div`,{className:`flex items-center justify-between pb-2 border-b-2 border-dashed border-ink-black`,children:[(0,_.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,_.jsx)(n,{className:`w-4 h-4 text-purple-700`}),(0,_.jsx)(`span`,{className:`font-arcade text-[10px] font-bold text-ink-black uppercase`,children:V?`EDIT SOLUTION`:`ADD NEW SOLUTION / METHOD`})]}),(0,_.jsx)(`button`,{type:`button`,onClick:()=>{B(!1),H(null)},className:`text-xs font-arcade text-trash-gray hover:text-rose-600 cursor-pointer font-bold`,children:`CANCEL`})]}),(0,_.jsxs)(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[(0,_.jsxs)(`div`,{className:`space-y-1`,children:[(0,_.jsx)(`label`,{className:`font-arcade text-[8.5px] font-bold text-trash-gray uppercase block`,children:`Solution / Method Name`}),(0,_.jsx)(`input`,{type:`text`,value:U.name,onChange:e=>W({...U,name:e.target.value}),placeholder:`e.g. One-Pass Hash Map, Two Pointers`,className:`w-full p-2 border-2 border-ink-black text-xs font-bold bg-[#fdf8e1] focus:outline-none focus:bg-white`})]}),(0,_.jsxs)(`div`,{className:`space-y-1`,children:[(0,_.jsx)(`label`,{className:`font-arcade text-[8.5px] font-bold text-trash-gray uppercase block`,children:`Pattern / Strategy`}),(0,_.jsx)(`select`,{value:U.pattern,onChange:e=>W({...U,pattern:e.target.value}),className:`w-full p-2 border-2 border-ink-black text-xs font-bold bg-[#fdf8e1] focus:outline-none focus:bg-white`,children:ue.map(e=>(0,_.jsx)(`option`,{value:e,children:e},e))})]}),(0,_.jsxs)(`div`,{className:`space-y-1`,children:[(0,_.jsx)(`label`,{className:`font-arcade text-[8.5px] font-bold text-trash-gray uppercase block`,children:`Time Complexity`}),(0,_.jsx)(`input`,{type:`text`,value:U.time_complexity,onChange:e=>W({...U,time_complexity:e.target.value}),placeholder:`e.g. O(N), O(N log N), O(N^2)`,className:`w-full p-2 border-2 border-ink-black text-xs font-code-mono font-bold bg-[#fdf8e1] focus:outline-none focus:bg-white`})]}),(0,_.jsxs)(`div`,{className:`space-y-1`,children:[(0,_.jsx)(`label`,{className:`font-arcade text-[8.5px] font-bold text-trash-gray uppercase block`,children:`Space Complexity`}),(0,_.jsx)(`input`,{type:`text`,value:U.space_complexity,onChange:e=>W({...U,space_complexity:e.target.value}),placeholder:`e.g. O(1), O(N)`,className:`w-full p-2 border-2 border-ink-black text-xs font-code-mono font-bold bg-[#fdf8e1] focus:outline-none focus:bg-white`})]})]}),(0,_.jsxs)(`div`,{className:`space-y-1`,children:[(0,_.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,_.jsx)(`label`,{className:`font-arcade text-[8.5px] font-bold text-trash-gray uppercase`,children:`Python Reference Code`}),(0,_.jsx)(`button`,{type:`button`,onClick:()=>W({...U,code:de}),className:`text-[8.5px] font-arcade text-sky-700 hover:underline cursor-pointer`,children:`Paste Current Code`})]}),(0,_.jsx)(`textarea`,{rows:8,value:U.code,onChange:e=>W({...U,code:e.target.value}),placeholder:`class Solution:def solve(self, nums):...`,className:`w-full p-2.5 border-2 border-ink-black bg-[#1E293B] text-[#4ADE80] font-code-mono text-xs focus:outline-none no-scrollbar`})]}),(0,_.jsxs)(`div`,{className:`space-y-1`,children:[(0,_.jsx)(`label`,{className:`font-arcade text-[8.5px] font-bold text-trash-gray uppercase block`,children:`Intuition / How to Solve (Optional)`}),(0,_.jsx)(`textarea`,{rows:3,value:U.explanation,onChange:e=>W({...U,explanation:e.target.value}),placeholder:`Key insight, trade-offs, and state tracking notes...`,className:`w-full p-2 border-2 border-ink-black text-xs bg-[#fdf8e1] focus:outline-none focus:bg-white no-scrollbar`})]}),(0,_.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,_.jsx)(`input`,{type:`checkbox`,id:`is_optimal_solution`,checked:U.is_optimal,onChange:e=>W({...U,is_optimal:e.target.checked}),className:`w-4 h-4 border-2 border-ink-black rounded cursor-pointer accent-emerald-600`}),(0,_.jsx)(`label`,{htmlFor:`is_optimal_solution`,className:`font-arcade text-[9px] font-bold text-ink-black cursor-pointer`,children:`SET AS OPTIMAL / PRIMARY APPROACH FOR THIS PROBLEM`})]}),(0,_.jsxs)(`div`,{className:`flex items-center justify-end gap-2 pt-2 border-t-2 border-dashed border-ink-black`,children:[(0,_.jsx)(`button`,{type:`button`,onClick:()=>{B(!1),H(null)},className:`px-3 py-1.5 bg-slate-100 hover:bg-slate-200 border-2 border-ink-black font-arcade text-[9px] font-bold text-ink-black cursor-pointer`,children:`CANCEL`}),(0,_.jsxs)(`button`,{type:`button`,disabled:G,onClick:he,className:`px-4 py-1.5 bg-emerald-500 hover:bg-emerald-400 border-2 border-ink-black font-arcade text-[9px] font-bold text-white shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none transition-all cursor-pointer disabled:opacity-50 flex items-center gap-1.5`,children:[G&&(0,_.jsx)(i,{className:`w-3 h-3 animate-spin`}),(0,_.jsx)(`span`,{children:V?`UPDATE SOLUTION`:`SAVE SOLUTION`})]})]})]}):Q?(0,_.jsxs)(`div`,{className:`space-y-3.5`,children:[(0,_.jsxs)(`div`,{className:`p-4 bg-white border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] space-y-3.5`,children:[(0,_.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2 pb-3 border-b border-slate-200`,children:[(0,_.jsxs)(`div`,{className:`flex items-center gap-2 flex-wrap min-w-0`,children:[(0,_.jsx)(`h3`,{className:`font-headline-md font-extrabold text-sm sm:text-base text-ink-black m-0 select-text break-words`,children:Q.name||`Solution ${Z+1}`}),Q.is_optimal&&(0,_.jsx)(`span`,{className:`px-2 py-0.5 bg-amber-300 border border-ink-black font-arcade text-[8px] font-bold text-ink-black shadow-[1px_1px_0px_0px_rgba(30,41,59,1)] shrink-0`,children:`★ OPTIMAL`})]}),(0,_.jsxs)(`div`,{className:`flex items-center gap-2 flex-wrap sm:ml-auto`,children:[(0,_.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,_.jsx)(`span`,{className:`font-arcade text-[8px] text-trash-gray uppercase`,children:`Pattern:`}),(0,_.jsx)(`span`,{className:`px-2 py-0.5 bg-purple-50 border border-purple-300 font-arcade text-[8.5px] text-purple-800 font-bold`,children:Q.pattern||`General Algorithm`})]}),(0,_.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,_.jsxs)(`code`,{className:`bg-[#1E293B] text-[#4ADE80] font-code-mono px-1.5 py-0.5 text-[11px] border border-ink-black font-bold`,children:[`T: `,Q.time_complexity||`O(N)`]}),(0,_.jsxs)(`code`,{className:`bg-[#1E293B] text-[#4ADE80] font-code-mono px-1.5 py-0.5 text-[11px] border border-ink-black font-bold`,children:[`S: `,Q.space_complexity||`O(1)`]})]}),(0,_.jsxs)(`div`,{className:`flex items-center gap-1 ml-auto`,children:[(0,_.jsxs)(`button`,{type:`button`,onClick:()=>{H(Q.id),B(!1),W({name:Q.name,pattern:Q.pattern,time_complexity:Q.time_complexity,space_complexity:Q.space_complexity,code:Q.code,explanation:Q.explanation||``,is_optimal:!!Q.is_optimal})},className:`px-2 py-1 bg-white hover:bg-slate-100 border border-ink-black text-ink-black font-arcade text-[8px] font-bold flex items-center gap-1 cursor-pointer`,title:`Edit this solution`,children:[(0,_.jsx)(n,{className:`w-3 h-3 text-slate-700`}),(0,_.jsx)(`span`,{className:`hidden sm:inline`,children:`EDIT`})]}),X.length>1&&(0,_.jsx)(`button`,{type:`button`,onClick:()=>ge(Q.id),className:`px-1.5 py-1 bg-white hover:bg-rose-50 border border-ink-black text-rose-700 font-arcade text-[8px] font-bold flex items-center gap-1 cursor-pointer`,title:`Delete this solution`,children:(0,_.jsx)(oe,{className:`w-3 h-3`})})]})]})]}),Q.code?(0,_.jsxs)(`div`,{className:`border border-ink-black bg-[#0f172a] overflow-hidden`,children:[(0,_.jsxs)(`div`,{className:`bg-[#1e293b] px-2.5 sm:px-3 py-1.5 border-b border-ink-black flex items-center justify-between gap-1.5 flex-wrap min-w-0`,children:[(0,_.jsx)(`span`,{className:`font-arcade text-[8px] text-slate-300 font-bold uppercase truncate min-w-0 flex-1`,children:y?`PYTHON 3`:`PYTHON 3 IMPLEMENTATION`}),(0,_.jsxs)(`div`,{className:`flex items-center gap-1.5 shrink-0`,children:[(0,_.jsxs)(`button`,{type:`button`,onClick:()=>pe(Q.code,Q.pattern,Q.time_complexity,Q.space_complexity),disabled:k,className:`px-2 py-0.5 bg-purple-50 hover:bg-purple-100 text-purple-800 border border-ink-black text-[9px] font-arcade font-bold flex items-center gap-1 cursor-pointer shrink-0 disabled:opacity-50 active:translate-y-0.5 transition-all`,title:`Explain this solution with AI`,children:[k?(0,_.jsx)(i,{className:`w-2.5 h-2.5 animate-spin text-purple-700`}):(0,_.jsx)(d,{className:`w-2.5 h-2.5 text-purple-600`}),(0,_.jsx)(`span`,{children:`Explain✦`})]}),(0,_.jsxs)(`button`,{onClick:()=>T(Q.code,`sol-${Q.id}`),className:`px-2 py-0.5 bg-white hover:bg-slate-100 text-ink-black border border-ink-black text-[9px] font-arcade font-bold flex items-center gap-1 cursor-pointer shrink-0 active:translate-y-0.5 transition-all`,title:`Copy solution code`,children:[(0,_.jsx)(l,{className:`w-2.5 h-2.5`}),w===`sol-${Q.id}`?`COPIED!`:`COPY`]})]})]}),(0,_.jsx)(`div`,{className:`p-3 text-xs overflow-x-auto max-h-80 no-scrollbar`,children:(0,_.jsx)(`pre`,{className:`font-code-mono text-[#4ADE80] text-[11px] leading-relaxed select-text m-0`,children:(0,_.jsx)(`code`,{children:Q.code})})})]}):(0,_.jsxs)(`div`,{className:`p-4 bg-amber-50 border border-dashed border-amber-300 text-center space-y-3`,children:[(0,_.jsx)(`p`,{className:`text-xs font-sans text-stone-700`,children:`No code implementation archived for this solution yet.`}),(0,_.jsx)(`button`,{onClick:fe,disabled:D,className:`px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white font-arcade text-[9px] font-bold border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none transition-all cursor-pointer inline-flex items-center gap-2 disabled:opacity-50`,children:D?(0,_.jsxs)(_.Fragment,{children:[(0,_.jsx)(i,{className:`w-3.5 h-3.5 animate-spin`}),(0,_.jsx)(`span`,{children:`Generating solution...`})]}):(0,_.jsxs)(_.Fragment,{children:[(0,_.jsx)(d,{className:`w-3.5 h-3.5 text-amber-300`}),(0,_.jsx)(`span`,{children:`Generate solution`})]})}),O&&(0,_.jsx)(`div`,{className:`text-xs text-rose-600 font-medium`,children:O})]}),Q.explanation&&(0,_.jsxs)(`div`,{className:`pt-3.5 border-t border-slate-200 space-y-1.5 select-text`,children:[(0,_.jsx)(`span`,{className:`font-arcade text-[8.5px] text-trash-gray uppercase font-bold block`,children:`SOLUTION INTUITION & STRATEGY:`}),(0,_.jsx)(m,{content:Q.explanation})]})]}),Q.code&&(0,_.jsxs)(`div`,{className:`space-y-3`,children:[A&&(0,_.jsx)(`div`,{className:`p-3 border-2 border-rose-500 bg-rose-50 text-rose-800 text-xs font-semibold`,children:A}),j&&(0,_.jsxs)(`div`,{className:`p-4 bg-white border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] space-y-2 select-text`,children:[(0,_.jsxs)(`div`,{className:`flex items-center gap-1.5 pb-2 border-b-2 border-dashed border-ink-black`,children:[(0,_.jsx)(le,{className:`w-4 h-4 text-purple-600`}),(0,_.jsxs)(`span`,{className:`font-arcade text-[9px] font-bold text-ink-black uppercase`,children:[`Gemini Code Breakdown (`,Q.name,`)`]})]}),(0,_.jsx)(`div`,{className:`max-h-96 overflow-y-auto no-scrollbar pt-1 select-text`,children:(0,_.jsx)(m,{content:j})})]})]})]}):null,E&&(0,_.jsxs)(`div`,{className:`p-2.5 border-2 border-rose-500 bg-rose-50 text-rose-800 text-xs font-bold flex items-center gap-2 shadow-[2px_2px_0px_0px_rgba(244,63,94,1)]`,children:[(0,_.jsx)(s,{className:`w-4 h-4 text-rose-600 shrink-0`}),(0,_.jsx)(`div`,{className:`flex-1`,children:E})]})]}),e===`fsrs`&&(0,_.jsxs)(`div`,{className:`space-y-4`,children:[(0,_.jsxs)(`div`,{className:`p-4 bg-white border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] space-y-3`,children:[(0,_.jsxs)(`div`,{className:`text-[9px] font-arcade text-trash-gray uppercase font-bold flex items-center gap-1.5`,children:[(0,_.jsx)(se,{className:`w-3 h-3 text-purple-600`}),`SPACED REPETITION PROGRESSION`]}),(0,_.jsx)(`div`,{className:`space-y-2`,children:[{state:0,label:`NEW`,color:`#3b82f6`},{state:1,label:`LEARNING`,color:`#f59e0b`},{state:2,label:`REVIEW`,color:`#10b981`},{state:3,label:`RELEARNING`,color:`#ef4444`}].map(e=>{let t=(M.fsrs_state??0)===e.state;return(0,_.jsxs)(`div`,{className:`p-2.5 border-2 border-ink-black flex items-center justify-between transition-all ${t?`bg-amber-100 shadow-[3px_3px_0px_0px_rgba(30,41,59,1)] translate-x-1 font-bold`:`bg-slate-50 opacity-70`}`,children:[(0,_.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,_.jsx)(`span`,{className:`w-5 h-5 border border-ink-black flex items-center justify-center font-arcade text-[9px] text-white font-bold`,style:{backgroundColor:e.color},children:e.state}),(0,_.jsx)(`span`,{className:`font-arcade text-[9px] text-ink-black`,children:e.label})]}),(0,_.jsx)(`div`,{className:`flex items-center gap-2`,children:t&&(0,_.jsx)(`span`,{className:`px-1.5 py-0.5 bg-emerald-500 text-white font-arcade text-[7px] border border-ink-black font-bold`,children:`CURRENT`})})]},e.state)})})]}),(0,_.jsxs)(`div`,{className:`p-4 bg-white border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] space-y-3`,children:[(0,_.jsxs)(`div`,{className:`text-[9px] font-arcade text-trash-gray uppercase font-bold flex items-center gap-1.5`,children:[(0,_.jsx)(c,{className:`w-3 h-3 text-emerald-600`}),`PERFORMANCE METRICS`]}),(0,_.jsxs)(`div`,{className:`grid grid-cols-2 gap-3`,children:[(0,_.jsxs)(`div`,{className:`p-2.5 bg-slate-50 border border-ink-black`,children:[(0,_.jsx)(`span`,{className:`font-arcade text-[8px] text-trash-gray block uppercase`,children:`Total Reviews`}),(0,_.jsx)(`span`,{className:`font-headline-md text-lg font-bold text-ink-black`,children:M.total_attempts||0})]}),(0,_.jsxs)(`div`,{className:`p-2.5 bg-slate-50 border border-ink-black`,children:[(0,_.jsx)(`span`,{className:`font-arcade text-[8px] text-trash-gray block uppercase`,children:`Correct Recall`}),(0,_.jsx)(`span`,{className:`font-headline-md text-lg font-bold text-emerald-600`,children:M.times_correct||0})]})]}),(0,_.jsxs)(`div`,{className:`text-xs font-sans text-slate-600 pt-1`,children:[`Next Due Date:`,` `,(0,_.jsx)(`span`,{className:`font-code-mono font-bold text-ink-black`,children:M.next_review?new Date(M.next_review).toLocaleDateString():`Today`})]})]})]})]})]})};export{y as ProblemSpecPanel};1234import{r as e}from"./rolldown-runtime-hePW80VL.js";import{Bt as t,F as n,G as ee,Ht as r,M as i,N as te,Tt as a,a as o,d as s,f as c,ht as ne,lt as re,nt as ie,o as ae,ot as l,p as oe,q as se,rt as u,tt as ce,wt as le,x as d}from"./vendor-react-hnaVBnLv.js";import{u as f}from"./index-Q9onQHft.js";import{n as p,t as m}from"./MarkdownRenderer-BGUaDi8Z.js";import{n as h}from"./ReviewQueue-BRrPvJUP.js";var g=e(r(),1),_=t(),ue=[`Arrays & Hashing`,`Two Pointers`,`Sliding Window`,`Stack`,`Binary Search`,`Linked List`,`Trees`,`Tries`,`Heap / Priority Queue`,`Backtracking`,`Graphs`,`Advanced Graphs`,`1-D Dynamic Programming`,`2-D Dynamic Programming`,`Greedy`,`Intervals`,`Math & Geometry`,`Bit Manipulation`];function v(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?`sol-${crypto.randomUUID()}`:`sol-${Date.now()}`}var y=({leftTab:e,onSelectLeftTab:t,mobileView:r,isNarrow:y=!1,problem:b,parsed:x,userSolution:S,officialSolution:C,effectiveReferenceCode:de,copiedSnippet:w,onCopyText:T,saveRefError:E,aiSolutionLoading:D,aiSolutionError:O,onFetchAiSolution:fe,explainLoading:k,explainError:A,explanationText:j,onExplainCode:pe,activeReview:M,onUpdateSolutions:N})=>{let[me,P]=(0,g.useState)(!1),[F,I]=(0,g.useState)(()=>b.id||b.name),[L,R]=(0,g.useState)(0),[z,B]=(0,g.useState)(!1),[V,H]=(0,g.useState)(null),[U,W]=(0,g.useState)({name:``,pattern:`Arrays & Hashing`,time_complexity:`O(N)`,space_complexity:`O(1)`,code:``,explanation:``,is_optimal:!1}),[G,K]=(0,g.useState)(!1),[q,J]=(0,g.useState)(null),Y=b.id||b.name;F!==Y&&(I(Y),P(!1),R(0),B(!1),H(null),J(null));let X=h(b,C,S),Z=L<X.length?L:0,Q=X[Z];(0,g.useEffect)(()=>{if(q){let e=setTimeout(()=>J(null),3500);return()=>clearTimeout(e)}},[q]);let he=async()=>{if(!U.name.trim()){J({type:`error`,message:`Solution name cannot be empty.`});return}if(!U.code.trim()){J({type:`error`,message:`Solution code cannot be empty.`});return}K(!0),J(null);try{let e;if(V)e=X.map(e=>e.id===V?{...e,name:U.name.trim(),pattern:U.pattern.trim()||`General Algorithm`,time_complexity:U.time_complexity.trim()||`O(N)`,space_complexity:U.space_complexity.trim()||`O(1)`,code:U.code,explanation:U.explanation.trim(),is_optimal:U.is_optimal}:U.is_optimal&&e.id!==V?{...e,is_optimal:!1}:e);else{let t={id:v(),name:U.name.trim(),pattern:U.pattern.trim()||`General Algorithm`,time_complexity:U.time_complexity.trim()||`O(N)`,space_complexity:U.space_complexity.trim()||`O(1)`,code:U.code,explanation:U.explanation.trim(),is_optimal:U.is_optimal||X.length===0};e=t.is_optimal?[...X.map(e=>({...e,is_optimal:!1})),t]:[...X,t]}let t=e.find(e=>e.is_optimal)||e[0];b.id&&await f(b.id,e,t?.time_complexity,t?.space_complexity,b),N?.(e),J({type:`success`,message:V?`Solution updated successfully!`:`New solution added to problem dossier!`}),B(!1),H(null),R(V?Z:e.length-1)}catch(e){let t=e instanceof Error?e.message:`Failed to save solution.`;J({type:`error`,message:t})}finally{K(!1)}},ge=async e=>{if(X.length<=1){J({type:`error`,message:`Problem must have at least one solution.`});return}if(window.confirm(`Are you sure you want to remove this solution?`)){K(!0);try{let t=X.filter(t=>t.id!==e);!t.some(e=>e.is_optimal)&&t.length>0&&(t[0].is_optimal=!0);let n=t.find(e=>e.is_optimal)||t[0];b.id&&await f(b.id,t,n?.time_complexity,n?.space_complexity,b),N?.(t),R(0),J({type:`success`,message:`Solution removed successfully.`})}catch(e){let t=e instanceof Error?e.message:`Failed to delete solution.`;J({type:`error`,message:t})}finally{K(!1)}}},$=e=>`cursor-pointer font-arcade text-[7.5px] min-[400px]:text-[8px] sm:text-[8.5px] transition-all flex items-center justify-center gap-1 sm:gap-1.5 focus:outline-none focus-visible:ring-2 focus-visible:ring-ink-black select-none whitespace-nowrap shrink-0 ${e?`h-10 px-2 sm:px-2.5 bg-paper-white text-ink-black font-extrabold border-t-2 border-x-2 border-b-0 border-ink-black relative z-10 -mb-[2px] pb-[10px] shadow-[0_-2px_0_0_rgba(30,41,59,0.06)] after:content-[''] after:absolute after:-bottom-[2px] after:left-0 after:right-0 after:h-[2.5px] after:bg-paper-white after:z-10`:`h-9 px-2 sm:px-2.5 bg-[#e8e4da] text-slate-700 hover:bg-[#efece3] hover:text-ink-black font-bold border-2 border-ink-black relative z-0 mb-0`}`;return(0,_.jsxs)(`div`,{className:`w-full ${y?`flex flex-1`:`lg:w-[49%] flex`} flex-col bg-paper-white border-b-[3px] lg:border-b-0 ${y?``:`lg:border-r-[3px]`} border-ink-black overflow-hidden ${y&&r!==`spec`&&r!==`ref`?`hidden`:`flex`}`,children:[(0,_.jsxs)(`div`,{className:`shrink-0 bg-[#f4f1ea] border-b-2 border-ink-black px-1.5 sm:px-2.5 pt-2 flex items-end gap-1 relative z-10 overflow-x-auto no-scrollbar`,children:[(0,_.jsxs)(`button`,{onClick:()=>t(`spec`),className:$(e===`spec`),children:[(0,_.jsx)(ce,{className:`w-3 h-3 text-purple-700 shrink-0`}),(0,_.jsx)(`span`,{children:y?`SPEC`:`SPECIFICATIONS`})]}),(0,_.jsxs)(`button`,{onClick:()=>t(`ref`),className:$(e===`ref`),children:[(0,_.jsx)(re,{className:`w-3 h-3 text-blue-700 shrink-0`}),(0,_.jsx)(`span`,{children:y?`SOL (${X.length})`:`SOLUTIONS (${X.length})`})]}),(0,_.jsxs)(`button`,{onClick:()=>t(`fsrs`),className:$(e===`fsrs`),children:[(0,_.jsx)(c,{className:`w-3 h-3 text-emerald-700 shrink-0`}),(0,_.jsx)(`span`,{className:`whitespace-nowrap`,children:y?`FSRS`:`FSRS STATS`})]})]}),(0,_.jsxs)(`div`,{className:`flex-1 overflow-y-auto no-scrollbar p-4 sm:p-5 space-y-4`,children:[e===`spec`&&(0,_.jsxs)(`div`,{className:`space-y-4`,children:[(0,_.jsxs)(`div`,{className:`p-4 bg-white border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] space-y-3.5`,children:[(0,_.jsx)(`div`,{children:(0,_.jsx)(`h2`,{className:`text-base sm:text-lg font-extrabold text-ink-black font-headline-md leading-tight m-0 select-text`,children:b.name||`Algorithm Problem`})}),x.description&&(0,_.jsxs)(`div`,{className:`pt-3.5 border-t border-slate-200`,children:[(0,_.jsxs)(`div`,{className:`text-[9px] font-arcade text-trash-gray uppercase font-bold mb-2 flex items-center gap-1`,children:[(0,_.jsx)(a,{className:`w-3 h-3 text-primary`}),`PROBLEM DESCRIPTION`]}),(0,_.jsx)(`div`,{className:`font-sans text-xs sm:text-[13px] text-slate-800 leading-relaxed space-y-2 font-medium`,children:x.description.split(``).map((e,t)=>e.trim()?(0,_.jsx)(`p`,{className:`m-0 leading-relaxed whitespace-pre-wrap select-text`,children:p(e)},t):(0,_.jsx)(`div`,{className:`h-1.5`},t))})]}),x.examples.length>0&&(0,_.jsxs)(`div`,{className:`pt-3.5 border-t border-slate-200 space-y-2.5`,children:[(0,_.jsxs)(`div`,{className:`text-[9px] font-arcade text-trash-gray uppercase font-bold flex items-center gap-1.5`,children:[(0,_.jsx)(o,{className:`w-3 h-3 text-amber-500`}),`EXAMPLES (`,x.examples.length,`)`]}),(0,_.jsx)(`div`,{className:`space-y-2.5`,children:x.examples.map((e,t)=>(0,_.jsxs)(`div`,{className:`p-3 bg-slate-50 border border-slate-200 space-y-2 text-xs`,children:[(0,_.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,_.jsxs)(`span`,{className:`font-arcade text-[9px] font-bold text-primary`,children:[`EXAMPLE `,t+1]}),e.input&&(0,_.jsxs)(`button`,{onClick:()=>T(e.input,`ex-${t}`),className:`px-2 py-0.5 bg-white hover:bg-slate-100 border border-ink-black text-[9px] font-arcade text-ink-black flex items-center gap-1 cursor-pointer`,title:`Copy input data`,children:[(0,_.jsx)(l,{className:`w-2.5 h-2.5`}),w===`ex-${t}`?`COPIED!`:`COPY`]})]}),e.input&&(0,_.jsxs)(`div`,{className:`space-y-1`,children:[(0,_.jsx)(`span`,{className:`text-[9px] font-arcade text-trash-gray font-bold uppercase block`,children:`Input:`}),(0,_.jsx)(`div`,{className:`bg-[#1E293B] text-[#4ADE80] font-code-mono p-2 border border-ink-black text-[11px] break-all select-text`,children:e.input})]}),e.output&&(0,_.jsxs)(`div`,{className:`space-y-1`,children:[(0,_.jsx)(`span`,{className:`text-[9px] font-arcade text-trash-gray font-bold uppercase block`,children:`Output:`}),(0,_.jsx)(`div`,{className:`bg-[#1E293B] text-[#4ADE80] font-code-mono p-2 border border-ink-black text-[11px] break-all select-text`,children:e.output})]}),e.explanation&&(0,_.jsxs)(`div`,{className:`text-[11px] font-sans text-slate-600 bg-white p-2 border border-slate-200`,children:[(0,_.jsx)(`span`,{className:`font-bold text-slate-700`,children:`Explanation: `}),p(e.explanation)]})]},t))})]}),x.constraints.length>0&&(0,_.jsxs)(`div`,{className:`pt-3.5 border-t border-slate-200`,children:[(0,_.jsx)(`div`,{className:`text-[9px] font-arcade text-trash-gray uppercase font-bold mb-2`,children:`CONSTRAINTS`}),(0,_.jsx)(`ul`,{className:`space-y-1.5 list-none m-0 p-0`,children:x.constraints.map((e,t)=>(0,_.jsxs)(`li`,{className:`flex items-start gap-2 text-xs`,children:[(0,_.jsx)(`span`,{className:`text-primary font-bold select-none`,children:`•`}),(0,_.jsx)(`code`,{className:`bg-slate-100 text-ink-black font-code-mono px-2 py-0.5 border border-slate-300 text-[11px] select-text`,children:e})]},t))})]})]}),me?(0,_.jsxs)(`div`,{className:`p-3 bg-amber-50 border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] flex flex-wrap items-center justify-between gap-2`,children:[(0,_.jsxs)(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[(0,_.jsx)(o,{className:`w-4 h-4 text-amber-600 shrink-0`}),(0,_.jsx)(`span`,{className:`font-arcade text-[9px] font-bold text-ink-black tracking-wide uppercase`,children:`OPTIMAL TARGET:`}),(0,_.jsxs)(`code`,{className:`bg-[#1E293B] text-[#4ADE80] font-code-mono px-2 py-0.5 text-[11px] border border-ink-black font-bold`,children:[`T: `,b.optimal_time||`O(N)`]}),(0,_.jsxs)(`code`,{className:`bg-[#1E293B] text-[#4ADE80] font-code-mono px-2 py-0.5 text-[11px] border border-ink-black font-bold`,children:[`S: `,b.optimal_space||`O(1)`]})]}),(0,_.jsxs)(`button`,{type:`button`,onClick:()=>P(!1),className:`px-2 py-0.5 bg-white hover:bg-slate-100 border border-ink-black font-arcade text-[8px] text-trash-gray hover:text-ink-black cursor-pointer flex items-center gap-1`,title:`Conceal target complexity`,children:[(0,_.jsx)(u,{className:`w-2.5 h-2.5`}),(0,_.jsx)(`span`,{children:`HIDE`})]})]}):(0,_.jsxs)(`div`,{className:`p-3 bg-amber-50/70 border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] flex items-center justify-between gap-2`,children:[(0,_.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,_.jsx)(ee,{className:`w-4 h-4 text-amber-700 shrink-0`}),(0,_.jsxs)(`div`,{children:[(0,_.jsx)(`span`,{className:`font-arcade text-[9px] font-bold text-ink-black tracking-wide uppercase block`,children:`OPTIMAL COMPLEXITY TARGET`}),(0,_.jsx)(`span`,{className:`text-[10px] font-sans text-slate-600 font-semibold`,children:`Hidden to test active recall before coding`})]})]}),(0,_.jsxs)(`button`,{type:`button`,onClick:()=>P(!0),className:`px-2.5 py-1 bg-white hover:bg-amber-100 border-2 border-ink-black font-arcade text-[8.5px] font-bold text-ink-black shadow-[1.5px_1.5px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none transition-all cursor-pointer flex items-center gap-1.5 shrink-0`,title:`Click to reveal target time and space complexity`,children:[(0,_.jsx)(ie,{className:`w-3 h-3 text-amber-700`}),(0,_.jsx)(`span`,{children:`REVEAL TARGET`})]})]})]}),e===`ref`&&(0,_.jsxs)(`div`,{className:`space-y-4`,children:[q&&(0,_.jsxs)(`div`,{className:`p-2.5 border-2 border-ink-black text-xs font-bold flex items-center justify-between shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] ${q.type===`success`?`bg-emerald-100 text-emerald-900 border-emerald-700`:`bg-rose-100 text-rose-900 border-rose-700`}`,children:[(0,_.jsxs)(`div`,{className:`flex items-center gap-2`,children:[q.type===`success`?(0,_.jsx)(ne,{className:`w-4 h-4 text-emerald-700 shrink-0`}):(0,_.jsx)(s,{className:`w-4 h-4 text-rose-700 shrink-0`}),(0,_.jsx)(`span`,{children:q.message})]}),(0,_.jsx)(`button`,{type:`button`,onClick:()=>J(null),className:`text-slate-600 hover:text-ink-black cursor-pointer`,children:(0,_.jsx)(ae,{className:`w-3.5 h-3.5`})})]}),(0,_.jsxs)(`div`,{className:`flex items-center gap-1 p-1 bg-slate-200/90 border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] overflow-x-auto no-scrollbar`,children:[X.map((e,t)=>(0,_.jsxs)(`button`,{type:`button`,onClick:()=>{R(t),B(!1),H(null)},className:`py-1 px-2 rounded-full font-arcade text-[8px] font-bold flex items-center justify-center gap-1 border-2 border-ink-black transition-all cursor-pointer whitespace-nowrap shrink-0 ${Z===t&&!z&&!V?`bg-sky-600 text-white shadow-[1px_1px_0px_0px_rgba(30,41,59,1)] -translate-y-0.5`:`bg-white text-ink-black hover:bg-sky-50 shadow-none`}`,title:e.name?`${e.name} (${e.pattern||`Algorithm`})`:`Solution ${t+1}`,children:[e.is_optimal?(0,_.jsx)(d,{className:`w-3 h-3 text-amber-300`}):(0,_.jsx)(a,{className:`w-3 h-3`}),(0,_.jsx)(`span`,{children:`Sol ${t+1}`}),e.is_optimal&&(0,_.jsx)(`span`,{className:`text-[6.5px] px-1 py-0.2 bg-amber-300 text-ink-black border border-ink-black font-extrabold rounded-full tracking-tight`,children:`OPTIMAL`})]},e.id||t)),(0,_.jsx)(`button`,{type:`button`,onClick:()=>{B(!0),H(null),W({name:`Method ${X.length+1}`,pattern:`Arrays & Hashing`,time_complexity:`O(N)`,space_complexity:`O(1)`,code:``,explanation:``,is_optimal:!1})},className:`h-6 w-6 rounded-full font-arcade text-[9px] font-bold flex items-center justify-center border-2 border-ink-black cursor-pointer shrink-0 active:translate-y-0.5 transition-all shadow-[1px_1px_0px_0px_rgba(30,41,59,1)] ${z?`bg-emerald-600 text-white`:`bg-amber-300 text-ink-black hover:bg-amber-200`}`,title:`Add another solution / method for this problem`,"aria-label":`Add Solution`,children:(0,_.jsx)(te,{className:`w-3 h-3 stroke-[2.5]`})})]}),z||V?(0,_.jsxs)(`div`,{className:`p-4 bg-white border-2 border-ink-black shadow-[3px_3px_0px_0px_rgba(30,41,59,1)] space-y-3.5`,children:[(0,_.jsxs)(`div`,{className:`flex items-center justify-between pb-2 border-b-2 border-dashed border-ink-black`,children:[(0,_.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,_.jsx)(n,{className:`w-4 h-4 text-purple-700`}),(0,_.jsx)(`span`,{className:`font-arcade text-[10px] font-bold text-ink-black uppercase`,children:V?`EDIT SOLUTION`:`ADD NEW SOLUTION / METHOD`})]}),(0,_.jsx)(`button`,{type:`button`,onClick:()=>{B(!1),H(null)},className:`text-xs font-arcade text-trash-gray hover:text-rose-600 cursor-pointer font-bold`,children:`CANCEL`})]}),(0,_.jsxs)(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[(0,_.jsxs)(`div`,{className:`space-y-1`,children:[(0,_.jsx)(`label`,{className:`font-arcade text-[8.5px] font-bold text-trash-gray uppercase block`,children:`Solution / Method Name`}),(0,_.jsx)(`input`,{type:`text`,value:U.name,onChange:e=>W({...U,name:e.target.value}),placeholder:`e.g. One-Pass Hash Map, Two Pointers`,className:`w-full p-2 border-2 border-ink-black text-xs font-bold bg-[#fdf8e1] focus:outline-none focus:bg-white`})]}),(0,_.jsxs)(`div`,{className:`space-y-1`,children:[(0,_.jsx)(`label`,{className:`font-arcade text-[8.5px] font-bold text-trash-gray uppercase block`,children:`Pattern / Strategy`}),(0,_.jsx)(`select`,{value:U.pattern,onChange:e=>W({...U,pattern:e.target.value}),className:`w-full p-2 border-2 border-ink-black text-xs font-bold bg-[#fdf8e1] focus:outline-none focus:bg-white`,children:ue.map(e=>(0,_.jsx)(`option`,{value:e,children:e},e))})]}),(0,_.jsxs)(`div`,{className:`space-y-1`,children:[(0,_.jsx)(`label`,{className:`font-arcade text-[8.5px] font-bold text-trash-gray uppercase block`,children:`Time Complexity`}),(0,_.jsx)(`input`,{type:`text`,value:U.time_complexity,onChange:e=>W({...U,time_complexity:e.target.value}),placeholder:`e.g. O(N), O(N log N), O(N^2)`,className:`w-full p-2 border-2 border-ink-black text-xs font-code-mono font-bold bg-[#fdf8e1] focus:outline-none focus:bg-white`})]}),(0,_.jsxs)(`div`,{className:`space-y-1`,children:[(0,_.jsx)(`label`,{className:`font-arcade text-[8.5px] font-bold text-trash-gray uppercase block`,children:`Space Complexity`}),(0,_.jsx)(`input`,{type:`text`,value:U.space_complexity,onChange:e=>W({...U,space_complexity:e.target.value}),placeholder:`e.g. O(1), O(N)`,className:`w-full p-2 border-2 border-ink-black text-xs font-code-mono font-bold bg-[#fdf8e1] focus:outline-none focus:bg-white`})]})]}),(0,_.jsxs)(`div`,{className:`space-y-1`,children:[(0,_.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,_.jsx)(`label`,{className:`font-arcade text-[8.5px] font-bold text-trash-gray uppercase`,children:`Python Reference Code`}),(0,_.jsx)(`button`,{type:`button`,onClick:()=>W({...U,code:de}),className:`text-[8.5px] font-arcade text-sky-700 hover:underline cursor-pointer`,children:`Paste Current Code`})]}),(0,_.jsx)(`textarea`,{rows:8,value:U.code,onChange:e=>W({...U,code:e.target.value}),placeholder:`class Solution:def solve(self, nums):...`,className:`w-full p-2.5 border-2 border-ink-black bg-[#1E293B] text-[#4ADE80] font-code-mono text-xs focus:outline-none no-scrollbar`})]}),(0,_.jsxs)(`div`,{className:`space-y-1`,children:[(0,_.jsx)(`label`,{className:`font-arcade text-[8.5px] font-bold text-trash-gray uppercase block`,children:`Intuition / How to Solve (Optional)`}),(0,_.jsx)(`textarea`,{rows:3,value:U.explanation,onChange:e=>W({...U,explanation:e.target.value}),placeholder:`Key insight, trade-offs, and state tracking notes...`,className:`w-full p-2 border-2 border-ink-black text-xs bg-[#fdf8e1] focus:outline-none focus:bg-white no-scrollbar`})]}),(0,_.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,_.jsx)(`input`,{type:`checkbox`,id:`is_optimal_solution`,checked:U.is_optimal,onChange:e=>W({...U,is_optimal:e.target.checked}),className:`w-4 h-4 border-2 border-ink-black rounded cursor-pointer accent-emerald-600`}),(0,_.jsx)(`label`,{htmlFor:`is_optimal_solution`,className:`font-arcade text-[9px] font-bold text-ink-black cursor-pointer`,children:`SET AS OPTIMAL / PRIMARY APPROACH FOR THIS PROBLEM`})]}),(0,_.jsxs)(`div`,{className:`flex items-center justify-end gap-2 pt-2 border-t-2 border-dashed border-ink-black`,children:[(0,_.jsx)(`button`,{type:`button`,onClick:()=>{B(!1),H(null)},className:`px-3 py-1.5 bg-slate-100 hover:bg-slate-200 border-2 border-ink-black font-arcade text-[9px] font-bold text-ink-black cursor-pointer`,children:`CANCEL`}),(0,_.jsxs)(`button`,{type:`button`,disabled:G,onClick:he,className:`px-4 py-1.5 bg-emerald-500 hover:bg-emerald-400 border-2 border-ink-black font-arcade text-[9px] font-bold text-white shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none transition-all cursor-pointer disabled:opacity-50 flex items-center gap-1.5`,children:[G&&(0,_.jsx)(i,{className:`w-3 h-3 animate-spin`}),(0,_.jsx)(`span`,{children:V?`UPDATE SOLUTION`:`SAVE SOLUTION`})]})]})]}):Q?(0,_.jsxs)(`div`,{className:`space-y-3.5`,children:[(0,_.jsxs)(`div`,{className:`p-4 bg-white border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] space-y-3.5`,children:[(0,_.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2 pb-3 border-b border-slate-200`,children:[(0,_.jsxs)(`div`,{className:`flex items-center gap-2 flex-wrap min-w-0`,children:[(0,_.jsx)(`h3`,{className:`font-headline-md font-extrabold text-sm sm:text-base text-ink-black m-0 select-text break-words`,children:Q.name||`Solution ${Z+1}`}),Q.is_optimal&&(0,_.jsx)(`span`,{className:`px-2 py-0.5 bg-amber-300 border border-ink-black font-arcade text-[8px] font-bold text-ink-black shadow-[1px_1px_0px_0px_rgba(30,41,59,1)] shrink-0`,children:`★ OPTIMAL`})]}),(0,_.jsxs)(`div`,{className:`flex items-center gap-2 flex-wrap sm:ml-auto`,children:[(0,_.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,_.jsx)(`span`,{className:`font-arcade text-[8px] text-trash-gray uppercase`,children:`Pattern:`}),(0,_.jsx)(`span`,{className:`px-2 py-0.5 bg-purple-50 border border-purple-300 font-arcade text-[8.5px] text-purple-800 font-bold`,children:Q.pattern||`General Algorithm`})]}),(0,_.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,_.jsxs)(`code`,{className:`bg-[#1E293B] text-[#4ADE80] font-code-mono px-1.5 py-0.5 text-[11px] border border-ink-black font-bold`,children:[`T: `,Q.time_complexity||`O(N)`]}),(0,_.jsxs)(`code`,{className:`bg-[#1E293B] text-[#4ADE80] font-code-mono px-1.5 py-0.5 text-[11px] border border-ink-black font-bold`,children:[`S: `,Q.space_complexity||`O(1)`]})]}),(0,_.jsxs)(`div`,{className:`flex items-center gap-1 ml-auto`,children:[(0,_.jsxs)(`button`,{type:`button`,onClick:()=>{H(Q.id),B(!1),W({name:Q.name,pattern:Q.pattern,time_complexity:Q.time_complexity,space_complexity:Q.space_complexity,code:Q.code,explanation:Q.explanation||``,is_optimal:!!Q.is_optimal})},className:`px-2 py-1 bg-white hover:bg-slate-100 border border-ink-black text-ink-black font-arcade text-[8px] font-bold flex items-center gap-1 cursor-pointer`,title:`Edit this solution`,children:[(0,_.jsx)(n,{className:`w-3 h-3 text-slate-700`}),(0,_.jsx)(`span`,{className:`hidden sm:inline`,children:`EDIT`})]}),X.length>1&&(0,_.jsx)(`button`,{type:`button`,onClick:()=>ge(Q.id),className:`px-1.5 py-1 bg-white hover:bg-rose-50 border border-ink-black text-rose-700 font-arcade text-[8px] font-bold flex items-center gap-1 cursor-pointer`,title:`Delete this solution`,children:(0,_.jsx)(oe,{className:`w-3 h-3`})})]})]})]}),Q.code?(0,_.jsxs)(`div`,{className:`border border-ink-black bg-[#0f172a] overflow-hidden`,children:[(0,_.jsxs)(`div`,{className:`bg-[#1e293b] px-2.5 sm:px-3 py-1.5 border-b border-ink-black flex items-center justify-between gap-1.5 flex-wrap min-w-0`,children:[(0,_.jsx)(`span`,{className:`font-arcade text-[8px] text-slate-300 font-bold uppercase truncate min-w-0 flex-1`,children:y?`PYTHON 3`:`PYTHON 3 IMPLEMENTATION`}),(0,_.jsxs)(`div`,{className:`flex items-center gap-1.5 shrink-0`,children:[(0,_.jsxs)(`button`,{type:`button`,onClick:()=>pe(Q.code,Q.pattern,Q.time_complexity,Q.space_complexity),disabled:k,className:`px-2 py-0.5 bg-purple-50 hover:bg-purple-100 text-purple-800 border border-ink-black text-[9px] font-arcade font-bold flex items-center gap-1 cursor-pointer shrink-0 disabled:opacity-50 active:translate-y-0.5 transition-all`,title:`Explain this solution with AI`,children:[k?(0,_.jsx)(i,{className:`w-2.5 h-2.5 animate-spin text-purple-700`}):(0,_.jsx)(d,{className:`w-2.5 h-2.5 text-purple-600`}),(0,_.jsx)(`span`,{children:`Explain✦`})]}),(0,_.jsxs)(`button`,{onClick:()=>T(Q.code,`sol-${Q.id}`),className:`px-2 py-0.5 bg-white hover:bg-slate-100 text-ink-black border border-ink-black text-[9px] font-arcade font-bold flex items-center gap-1 cursor-pointer shrink-0 active:translate-y-0.5 transition-all`,title:`Copy solution code`,children:[(0,_.jsx)(l,{className:`w-2.5 h-2.5`}),w===`sol-${Q.id}`?`COPIED!`:`COPY`]})]})]}),(0,_.jsx)(`div`,{className:`p-3 text-xs overflow-x-auto max-h-80 no-scrollbar`,children:(0,_.jsx)(`pre`,{className:`font-code-mono text-[#4ADE80] text-[11px] leading-relaxed select-text m-0`,children:(0,_.jsx)(`code`,{children:Q.code})})})]}):(0,_.jsxs)(`div`,{className:`p-4 bg-amber-50 border border-dashed border-amber-300 text-center space-y-3`,children:[(0,_.jsx)(`p`,{className:`text-xs font-sans text-stone-700`,children:`No code implementation archived for this solution yet.`}),(0,_.jsx)(`button`,{onClick:fe,disabled:D,className:`px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white font-arcade text-[9px] font-bold border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none transition-all cursor-pointer inline-flex items-center gap-2 disabled:opacity-50`,children:D?(0,_.jsxs)(_.Fragment,{children:[(0,_.jsx)(i,{className:`w-3.5 h-3.5 animate-spin`}),(0,_.jsx)(`span`,{children:`Generating solution...`})]}):(0,_.jsxs)(_.Fragment,{children:[(0,_.jsx)(d,{className:`w-3.5 h-3.5 text-amber-300`}),(0,_.jsx)(`span`,{children:`Generate solution`})]})}),O&&(0,_.jsx)(`div`,{className:`text-xs text-rose-600 font-medium`,children:O})]}),Q.explanation&&(0,_.jsxs)(`div`,{className:`pt-3.5 border-t border-slate-200 space-y-1.5 select-text`,children:[(0,_.jsx)(`span`,{className:`font-arcade text-[8.5px] text-trash-gray uppercase font-bold block`,children:`SOLUTION INTUITION & STRATEGY:`}),(0,_.jsx)(m,{content:Q.explanation})]})]}),Q.code&&(0,_.jsxs)(`div`,{className:`space-y-3`,children:[A&&(0,_.jsx)(`div`,{className:`p-3 border-2 border-rose-500 bg-rose-50 text-rose-800 text-xs font-semibold`,children:A}),j&&(0,_.jsxs)(`div`,{className:`p-4 bg-white border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] space-y-2 select-text`,children:[(0,_.jsxs)(`div`,{className:`flex items-center gap-1.5 pb-2 border-b-2 border-dashed border-ink-black`,children:[(0,_.jsx)(le,{className:`w-4 h-4 text-purple-600`}),(0,_.jsxs)(`span`,{className:`font-arcade text-[9px] font-bold text-ink-black uppercase`,children:[`Gemini Code Breakdown (`,Q.name,`)`]})]}),(0,_.jsx)(`div`,{className:`max-h-96 overflow-y-auto no-scrollbar pt-1 select-text`,children:(0,_.jsx)(m,{content:j})})]})]})]}):null,E&&(0,_.jsxs)(`div`,{className:`p-2.5 border-2 border-rose-500 bg-rose-50 text-rose-800 text-xs font-bold flex items-center gap-2 shadow-[2px_2px_0px_0px_rgba(244,63,94,1)]`,children:[(0,_.jsx)(s,{className:`w-4 h-4 text-rose-600 shrink-0`}),(0,_.jsx)(`div`,{className:`flex-1`,children:E})]})]}),e===`fsrs`&&(0,_.jsxs)(`div`,{className:`space-y-4`,children:[(0,_.jsxs)(`div`,{className:`p-4 bg-white border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] space-y-3`,children:[(0,_.jsxs)(`div`,{className:`text-[9px] font-arcade text-trash-gray uppercase font-bold flex items-center gap-1.5`,children:[(0,_.jsx)(se,{className:`w-3 h-3 text-purple-600`}),`SPACED REPETITION PROGRESSION`]}),(0,_.jsx)(`div`,{className:`space-y-2`,children:[{state:0,label:`NEW`,color:`#3b82f6`},{state:1,label:`LEARNING`,color:`#f59e0b`},{state:2,label:`REVIEW`,color:`#10b981`},{state:3,label:`RELEARNING`,color:`#ef4444`}].map(e=>{let t=(M.fsrs_state??0)===e.state;return(0,_.jsxs)(`div`,{className:`p-2.5 border-2 border-ink-black flex items-center justify-between transition-all ${t?`bg-amber-100 shadow-[3px_3px_0px_0px_rgba(30,41,59,1)] translate-x-1 font-bold`:`bg-slate-50 opacity-70`}`,children:[(0,_.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,_.jsx)(`span`,{className:`w-5 h-5 border border-ink-black flex items-center justify-center font-arcade text-[9px] text-white font-bold`,style:{backgroundColor:e.color},children:e.state}),(0,_.jsx)(`span`,{className:`font-arcade text-[9px] text-ink-black`,children:e.label})]}),(0,_.jsx)(`div`,{className:`flex items-center gap-2`,children:t&&(0,_.jsx)(`span`,{className:`px-1.5 py-0.5 bg-emerald-500 text-white font-arcade text-[7px] border border-ink-black font-bold`,children:`CURRENT`})})]},e.state)})})]}),(0,_.jsxs)(`div`,{className:`p-4 bg-white border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] space-y-3`,children:[(0,_.jsxs)(`div`,{className:`text-[9px] font-arcade text-trash-gray uppercase font-bold flex items-center gap-1.5`,children:[(0,_.jsx)(c,{className:`w-3 h-3 text-emerald-600`}),`PERFORMANCE METRICS`]}),(0,_.jsxs)(`div`,{className:`grid grid-cols-2 gap-3`,children:[(0,_.jsxs)(`div`,{className:`p-2.5 bg-slate-50 border border-ink-black`,children:[(0,_.jsx)(`span`,{className:`font-arcade text-[8px] text-trash-gray block uppercase`,children:`Total Reviews`}),(0,_.jsx)(`span`,{className:`font-headline-md text-lg font-bold text-ink-black`,children:M.total_attempts||0})]}),(0,_.jsxs)(`div`,{className:`p-2.5 bg-slate-50 border border-ink-black`,children:[(0,_.jsx)(`span`,{className:`font-arcade text-[8px] text-trash-gray block uppercase`,children:`Correct Recall`}),(0,_.jsx)(`span`,{className:`font-headline-md text-lg font-bold text-emerald-600`,children:M.times_correct||0})]})]}),(0,_.jsxs)(`div`,{className:`text-xs font-sans text-slate-600 pt-1`,children:[`Next Due Date:`,` `,(0,_.jsx)(`span`,{className:`font-code-mono font-bold text-ink-black`,children:M.next_review?new Date(M.next_review).toLocaleDateString():`Today`})]})]})]})]})]})};export{y as ProblemSpecPanel};
1import{r as e}from"./rolldown-runtime-hePW80VL.js";import{Bt as t,Ht as n}from"./vendor-react-hnaVBnLv.js";import{s as r}from"./firebaseClient-DZobvwSx.js";import{t as i}from"./MarkdownRenderer-D8UdFpnD.js";var a=e(n(),1),o=t();function s(){let[e,t]=(0,a.useState)(null),[n,s]=(0,a.useState)(``),[c,l]=(0,a.useState)(!1),[u,d]=(0,a.useState)([]),[f,p]=(0,a.useState)(``),[m,h]=(0,a.useState)(!0),[g,_]=(0,a.useState)(0),v=async()=>{h(!0),p(``);try{let{data:{session:e}}=await r.auth.getSession();if(!e){p(`Unauthenticated session`);return}let n=await fetch(`/api/challenges/python/daily`,{headers:{Authorization:`Bearer ${e.access_token}`}});if(n.ok){let e=await n.json();t(e),s(e.starter_code),_(e.total_score)}else p(`Failed to load challenge from server.`)}catch{p(`Connection timed out.`)}finally{h(!1)}};return(0,a.useEffect)(()=>{v()},[]),m?(0,o.jsxs)(`div`,{className:`w-full h-full bg-paper-white p-6 flex flex-col items-center justify-center font-arcade text-[10px]`,children:[(0,o.jsx)(`div`,{className:`animate-bounce mb-2`,children:`LOADING CHALLENGE...`}),(0,o.jsx)(`div`,{className:`w-48 h-4 bg-white border-[3px] border-ink-black overflow-hidden relative`,children:(0,o.jsx)(`div`,{className:`absolute inset-y-0 left-0 bg-[#9d4edd] w-2/3 animate-pulse border-r-2 border-ink-black`})})]}):e?(0,o.jsx)(`div`,{className:`w-full h-full bg-paper-white text-ink-black flex flex-col overflow-hidden text-xs md:text-sm`,children:(0,o.jsxs)(`div`,{className:`flex-1 overflow-y-auto p-4 custom-scrollbar flex flex-col gap-4`,children:[(0,o.jsxs)(`div`,{className:`flex justify-between items-center bg-slate-100 border-[3px] border-ink-black p-3`,children:[(0,o.jsxs)(`div`,{className:`flex gap-2`,children:[(0,o.jsx)(`span`,{className:`px-2 py-0.5 border-2 border-ink-black font-bold uppercase text-[9px] ${e.difficulty===`Easy`?`bg-green-200 text-green-800`:e.difficulty===`Medium`?`bg-yellow-200 text-yellow-800`:`bg-red-200 text-red-800`}`,children:e.difficulty}),(0,o.jsxs)(`span`,{className:`bg-blue-100 text-blue-800 px-2 py-0.5 border-2 border-ink-black font-bold text-[9px]`,children:[`+`,e.points,` PTS`]}),e.completed?(0,o.jsx)(`span`,{className:`bg-emerald-500 text-white px-2 py-0.5 border-2 border-ink-black font-bold text-[9px]`,children:`COMPLETED`}):(0,o.jsx)(`span`,{className:`bg-rose-500 text-white px-2 py-0.5 border-2 border-ink-black font-bold text-[9px]`,children:`INCOMPLETE`})]}),(0,o.jsxs)(`div`,{className:`font-arcade text-[8px] text-purple-700 font-bold bg-white border-2 border-ink-black px-2 py-0.5 shadow-[1px_1px_0_0_#1E293B]`,children:[`TOTAL SCORE: `,g]})]}),(0,o.jsxs)(`div`,{className:`border-2 border-ink-black bg-slate-50 p-3 rounded font-sans leading-relaxed text-xs`,children:[(0,o.jsxs)(`h3`,{className:`font-bold border-b border-slate-300 pb-1 mb-2 uppercase tracking-wide text-primary-purple flex items-center gap-1`,children:[(0,o.jsx)(`span`,{className:`material-symbols-outlined text-sm`,children:`description`}),`Problem: `,e.title]}),(0,o.jsx)(i,{content:e.description})]}),(0,o.jsxs)(`div`,{className:`flex flex-col flex-1 min-h-[220px]`,children:[(0,o.jsxs)(`div`,{className:`flex justify-between items-center mb-1`,children:[(0,o.jsxs)(`span`,{className:`font-bold text-[10px] tracking-wide uppercase flex items-center gap-1`,children:[(0,o.jsx)(`span`,{className:`material-symbols-outlined text-sm text-purple-600`,children:`code`}),`Write Python Solution:`]}),(0,o.jsx)(`button`,{onClick:()=>s(e.starter_code),className:`text-[9px] underline text-blue-600 hover:text-blue-800 cursor-pointer font-sans`,children:`Reset Starter Code`})]}),(0,o.jsx)(`textarea`,{value:n,onChange:e=>s(e.target.value),className:`flex-1 w-full bg-slate-900 text-[#4ADE80] font-mono p-3 border-[3px] border-ink-black rounded outline-none focus:ring-2 focus:ring-primary-purple text-xs leading-relaxed resize-none`,placeholder:`# Write your python code here`,spellCheck:`false`})]}),(0,o.jsx)(`div`,{className:`shrink-0`,children:(0,o.jsx)(`button`,{disabled:c,onClick:async()=>{l(!0),p(``),d([]);try{let{data:{session:e}}=await r.auth.getSession();if(!e){p(`Unauthenticated session`);return}let i=await fetch(`/api/challenges/python/submit`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${e.access_token}`},body:JSON.stringify({code:n})});if(i.ok){let e=await i.json();e.success?(d(e.results),e.all_passed&&(_(e.total_score),t(e=>e?{...e,completed:!0}:null))):p(e.error)}else p(`Submission failed at server host.`)}catch{p(`Network connection lost.`)}finally{l(!1)}},className:`w-full bg-highlight-pink text-white font-window-title font-bold py-2 px-4 border-[3px] border-ink-black shadow-[3px_3px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none hover:bg-pink-400 transition-all disabled:opacity-50 cursor-pointer text-center text-xs`,children:c?`EXECUTING TEST CASES...`:`SUBMIT SOLUTION`})}),f&&(0,o.jsxs)(`div`,{className:`border-[3px] border-red-500 bg-red-50 text-red-800 p-3 font-mono text-xs whitespace-pre-wrap`,children:[(0,o.jsx)(`div`,{className:`font-bold mb-1`,children:`COMPILER / RUNTIME ERROR:`}),f]}),u.length>0&&(0,o.jsxs)(`div`,{className:`border-[3px] border-ink-black bg-slate-100 p-3`,children:[(0,o.jsx)(`div`,{className:`font-bold text-[10px] border-b border-slate-300 pb-1 mb-2 uppercase`,children:`Test Case Executions:`}),(0,o.jsx)(`div`,{className:`space-y-1.5 font-mono text-xs`,children:u.map((e,t)=>(0,o.jsxs)(`div`,{className:`flex flex-col p-2 border border-slate-300 bg-white`,children:[(0,o.jsxs)(`div`,{className:`flex justify-between`,children:[(0,o.jsxs)(`span`,{className:`font-bold`,children:[`Test Case `,t+1,`:`]}),(0,o.jsx)(`span`,{className:`font-bold uppercase ${e.status===`passed`?`text-green-600`:`text-red-600`}`,children:e.status})]}),(0,o.jsxs)(`div`,{className:`text-[10px] text-slate-500 mt-1`,children:[(0,o.jsxs)(`div`,{children:[`Input: `,JSON.stringify(e.input)]}),e.status===`passed`&&(0,o.jsxs)(`div`,{children:[`Output: `,JSON.stringify(e.got)]}),e.status===`failed`&&(0,o.jsxs)(`div`,{className:`text-red-700`,children:[`Expected: `,JSON.stringify(e.expected),` | Got: `,JSON.stringify(e.got)]}),e.status===`error`&&(0,o.jsxs)(`div`,{className:`text-red-700 font-semibold`,children:[`Error: `,e.error]})]})]},t))})]})]})}):(0,o.jsxs)(`div`,{className:`w-full h-full bg-paper-white p-6 flex flex-col items-center justify-center font-sans text-center gap-3`,children:[(0,o.jsx)(`span`,{className:`material-symbols-outlined text-red-500 text-4xl`,children:`error`}),(0,o.jsx)(`div`,{className:`font-bold text-ink-black text-sm`,children:f||`No active challenge found.`}),(0,o.jsx)(`button`,{onClick:v,className:`px-3 py-1.5 bg-yellow-400 hover:bg-yellow-300 border-[3px] border-ink-black text-xs font-bold font-window-title cursor-pointer shadow-[2px_2px_0px_rgba(0,0,0,1)] active:translate-y-0.5 active:shadow-none`,children:`RETRY`})]})}export{s as default};1import{r as e}from"./rolldown-runtime-hePW80VL.js";import{Bt as t,Ht as n}from"./vendor-react-hnaVBnLv.js";import{s as r}from"./firebaseClient-DZobvwSx.js";import{t as i}from"./MarkdownRenderer-BGUaDi8Z.js";var a=e(n(),1),o=t();function s(){let[e,t]=(0,a.useState)(null),[n,s]=(0,a.useState)(``),[c,l]=(0,a.useState)(!1),[u,d]=(0,a.useState)([]),[f,p]=(0,a.useState)(``),[m,h]=(0,a.useState)(!0),[g,_]=(0,a.useState)(0),v=async()=>{h(!0),p(``);try{let{data:{session:e}}=await r.auth.getSession();if(!e){p(`Unauthenticated session`);return}let n=await fetch(`/api/challenges/python/daily`,{headers:{Authorization:`Bearer ${e.access_token}`}});if(n.ok){let e=await n.json();t(e),s(e.starter_code),_(e.total_score)}else p(`Failed to load challenge from server.`)}catch{p(`Connection timed out.`)}finally{h(!1)}};return(0,a.useEffect)(()=>{v()},[]),m?(0,o.jsxs)(`div`,{className:`w-full h-full bg-paper-white p-6 flex flex-col items-center justify-center font-arcade text-[10px]`,children:[(0,o.jsx)(`div`,{className:`animate-bounce mb-2`,children:`LOADING CHALLENGE...`}),(0,o.jsx)(`div`,{className:`w-48 h-4 bg-white border-[3px] border-ink-black overflow-hidden relative`,children:(0,o.jsx)(`div`,{className:`absolute inset-y-0 left-0 bg-[#9d4edd] w-2/3 animate-pulse border-r-2 border-ink-black`})})]}):e?(0,o.jsx)(`div`,{className:`w-full h-full bg-paper-white text-ink-black flex flex-col overflow-hidden text-xs md:text-sm`,children:(0,o.jsxs)(`div`,{className:`flex-1 overflow-y-auto p-4 custom-scrollbar flex flex-col gap-4`,children:[(0,o.jsxs)(`div`,{className:`flex justify-between items-center bg-slate-100 border-[3px] border-ink-black p-3`,children:[(0,o.jsxs)(`div`,{className:`flex gap-2`,children:[(0,o.jsx)(`span`,{className:`px-2 py-0.5 border-2 border-ink-black font-bold uppercase text-[9px] ${e.difficulty===`Easy`?`bg-green-200 text-green-800`:e.difficulty===`Medium`?`bg-yellow-200 text-yellow-800`:`bg-red-200 text-red-800`}`,children:e.difficulty}),(0,o.jsxs)(`span`,{className:`bg-blue-100 text-blue-800 px-2 py-0.5 border-2 border-ink-black font-bold text-[9px]`,children:[`+`,e.points,` PTS`]}),e.completed?(0,o.jsx)(`span`,{className:`bg-emerald-500 text-white px-2 py-0.5 border-2 border-ink-black font-bold text-[9px]`,children:`COMPLETED`}):(0,o.jsx)(`span`,{className:`bg-rose-500 text-white px-2 py-0.5 border-2 border-ink-black font-bold text-[9px]`,children:`INCOMPLETE`})]}),(0,o.jsxs)(`div`,{className:`font-arcade text-[8px] text-purple-700 font-bold bg-white border-2 border-ink-black px-2 py-0.5 shadow-[1px_1px_0_0_#1E293B]`,children:[`TOTAL SCORE: `,g]})]}),(0,o.jsxs)(`div`,{className:`border-2 border-ink-black bg-slate-50 p-3 rounded font-sans leading-relaxed text-xs`,children:[(0,o.jsxs)(`h3`,{className:`font-bold border-b border-slate-300 pb-1 mb-2 uppercase tracking-wide text-primary-purple flex items-center gap-1`,children:[(0,o.jsx)(`span`,{className:`material-symbols-outlined text-sm`,children:`description`}),`Problem: `,e.title]}),(0,o.jsx)(i,{content:e.description})]}),(0,o.jsxs)(`div`,{className:`flex flex-col flex-1 min-h-[220px]`,children:[(0,o.jsxs)(`div`,{className:`flex justify-between items-center mb-1`,children:[(0,o.jsxs)(`span`,{className:`font-bold text-[10px] tracking-wide uppercase flex items-center gap-1`,children:[(0,o.jsx)(`span`,{className:`material-symbols-outlined text-sm text-purple-600`,children:`code`}),`Write Python Solution:`]}),(0,o.jsx)(`button`,{onClick:()=>s(e.starter_code),className:`text-[9px] underline text-blue-600 hover:text-blue-800 cursor-pointer font-sans`,children:`Reset Starter Code`})]}),(0,o.jsx)(`textarea`,{value:n,onChange:e=>s(e.target.value),className:`flex-1 w-full bg-slate-900 text-[#4ADE80] font-mono p-3 border-[3px] border-ink-black rounded outline-none focus:ring-2 focus:ring-primary-purple text-xs leading-relaxed resize-none`,placeholder:`# Write your python code here`,spellCheck:`false`})]}),(0,o.jsx)(`div`,{className:`shrink-0`,children:(0,o.jsx)(`button`,{disabled:c,onClick:async()=>{l(!0),p(``),d([]);try{let{data:{session:e}}=await r.auth.getSession();if(!e){p(`Unauthenticated session`);return}let i=await fetch(`/api/challenges/python/submit`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${e.access_token}`},body:JSON.stringify({code:n})});if(i.ok){let e=await i.json();e.success?(d(e.results),e.all_passed&&(_(e.total_score),t(e=>e?{...e,completed:!0}:null))):p(e.error)}else p(`Submission failed at server host.`)}catch{p(`Network connection lost.`)}finally{l(!1)}},className:`w-full bg-highlight-pink text-white font-window-title font-bold py-2 px-4 border-[3px] border-ink-black shadow-[3px_3px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none hover:bg-pink-400 transition-all disabled:opacity-50 cursor-pointer text-center text-xs`,children:c?`EXECUTING TEST CASES...`:`SUBMIT SOLUTION`})}),f&&(0,o.jsxs)(`div`,{className:`border-[3px] border-red-500 bg-red-50 text-red-800 p-3 font-mono text-xs whitespace-pre-wrap`,children:[(0,o.jsx)(`div`,{className:`font-bold mb-1`,children:`COMPILER / RUNTIME ERROR:`}),f]}),u.length>0&&(0,o.jsxs)(`div`,{className:`border-[3px] border-ink-black bg-slate-100 p-3`,children:[(0,o.jsx)(`div`,{className:`font-bold text-[10px] border-b border-slate-300 pb-1 mb-2 uppercase`,children:`Test Case Executions:`}),(0,o.jsx)(`div`,{className:`space-y-1.5 font-mono text-xs`,children:u.map((e,t)=>(0,o.jsxs)(`div`,{className:`flex flex-col p-2 border border-slate-300 bg-white`,children:[(0,o.jsxs)(`div`,{className:`flex justify-between`,children:[(0,o.jsxs)(`span`,{className:`font-bold`,children:[`Test Case `,t+1,`:`]}),(0,o.jsx)(`span`,{className:`font-bold uppercase ${e.status===`passed`?`text-green-600`:`text-red-600`}`,children:e.status})]}),(0,o.jsxs)(`div`,{className:`text-[10px] text-slate-500 mt-1`,children:[(0,o.jsxs)(`div`,{children:[`Input: `,JSON.stringify(e.input)]}),e.status===`passed`&&(0,o.jsxs)(`div`,{children:[`Output: `,JSON.stringify(e.got)]}),e.status===`failed`&&(0,o.jsxs)(`div`,{className:`text-red-700`,children:[`Expected: `,JSON.stringify(e.expected),` | Got: `,JSON.stringify(e.got)]}),e.status===`error`&&(0,o.jsxs)(`div`,{className:`text-red-700 font-semibold`,children:[`Error: `,e.error]})]})]},t))})]})]})}):(0,o.jsxs)(`div`,{className:`w-full h-full bg-paper-white p-6 flex flex-col items-center justify-center font-sans text-center gap-3`,children:[(0,o.jsx)(`span`,{className:`material-symbols-outlined text-red-500 text-4xl`,children:`error`}),(0,o.jsx)(`div`,{className:`font-bold text-ink-black text-sm`,children:f||`No active challenge found.`}),(0,o.jsx)(`button`,{onClick:v,className:`px-3 py-1.5 bg-yellow-400 hover:bg-yellow-300 border-[3px] border-ink-black text-xs font-bold font-window-title cursor-pointer shadow-[2px_2px_0px_rgba(0,0,0,1)] active:translate-y-0.5 active:shadow-none`,children:`RETRY`})]})}export{s as default};
12345const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ProblemSpecPanel-C8iV6oe0.js","assets/rolldown-runtime-hePW80VL.js","assets/vendor-react-hnaVBnLv.js","assets/vendor-codemirror-By0wlJeM.js","assets/index-Q9onQHft.js","assets/firebaseClient-DZobvwSx.js","assets/vendor-firebase-DSIO3PIf.js","assets/vendor-ui-ZXcm-2wU.js","assets/index-kuOEkBQB.css","assets/MarkdownRenderer-BGUaDi8Z.js"])))=>i.map(i=>d[i]);import{n as e,r as t}from"./rolldown-runtime-hePW80VL.js";import{A as n,Bt as r,Et as i,F as a,Ht as o,M as s,O as c,P as l,St as u,Tt as d,X as f,a as p,d as m,et as h,ht as g,it as _,lt as v,mt as y,p as ee,pt as b,q as x,s as S,st as C,t as w,tt as T,u as E,x as D,xt as te,yt as O}from"./vendor-react-hnaVBnLv.js";import{r as k,s as A}from"./firebaseClient-DZobvwSx.js";import{c as j,n as M,o as N,r as P,s as F,t as I,x as L}from"./index-Q9onQHft.js";import{o as ne,r as re}from"./githubSyncService-x0Mm_uEl.js";import{t as ie}from"./confetti.module-Uxh4CK4s.js";import"./MarkdownRenderer-BGUaDi8Z.js";import"./PrincessChamber-DlL5aOl1.js";import{A as R,C as z,I as B,S as V,p as ae,t as oe,x as se,y as ce}from"./vendor-codemirror-By0wlJeM.js";var H=t(o(),1),U=r();function le(e){if(!e)return{description:``,examples:[],constraints:[]};let t=e.description||``,n=[],r=[];if(Array.isArray(e.examples)&&e.examples.length>0&&(n=e.examples.map(e=>typeof e==`string`?{input:e,output:``}:{input:e?.input||``,output:e?.output||``,explanation:e?.explanation||``})),Array.isArray(e.constraints)&&e.constraints.length>0?r=e.constraints.map(e=>String(e).replace(/^[\u2022\-*]\s*/,``).trim()).filter(Boolean):typeof e.constraints==`string`&&e.constraints.trim()&&(r=e.constraints.split(``).map(e=>e.replace(/^[\u2022\-*]\s*/,``).trim()).filter(Boolean)),n.length===0||r.length===0){let e=t.search(/\bExample\s*\d*:/i),i=t.search(/\bConstraints\s*:/i),a=-1;if(e!==-1&&i!==-1?a=Math.min(e,i):e===-1?i!==-1&&(a=i):a=e,a!==-1){let e=t.substring(0,a).trim(),i=t.substring(a),o=i,s=``,c=i.search(/\bConstraints\s*:/i);if(c!==-1&&(o=i.substring(0,c).trim(),s=i.substring(c).replace(/\bConstraints\s*:/i,``).trim()),n.length===0&&o){let e=/\bExample\s*(\d*)\s*:/gi,t=[],r;for(;(r=e.exec(o))!==null;)t.push({index:r.index,text:r[0]});for(let e=0;e<t.length;e++){let r=t[e].index+t[e].text.length,i=e+1<t.length?t[e+1].index:o.length,a=o.substring(r,i).trim(),s=a.match(/Input:\s*([\s\S]+?)(?=(?:Output:|Explanation:|$))/i),c=a.match(/Output:\s*([\s\S]+?)(?=(?:Explanation:|$))/i),l=a.match(/Explanation:\s*([\s\S]+)/i),u=s?s[1].trim():``,d=c?c[1].trim():``,f=l?l[1].trim():``;u||d?n.push({input:u,output:d,explanation:f}):a&&n.push({input:a,output:``,explanation:``})}}r.length===0&&s&&(r=s.split(``).map(e=>e.replace(/^[\u2022\-*]\s*/,``).trim()).filter(Boolean)),(n.length>0||r.length>0)&&(t=e)}}return{description:t,examples:n,constraints:r}}function ue(e,t,n,r){let i=e=>!e||/^Method\s*\d*$/i.test(e.trim())||e.trim().toLowerCase()===`standard`,a=(e||t||`Algorithm Problem`).trim(),o=null;if(t&&a.toLowerCase().startsWith(t.toLowerCase())){let e=a.slice(t.length).trim();if(a=t,e){let t=e.match(/^[-\s]*Method\s*(\d+)\s*\((.+)\)$/i);if(t){let e=parseInt(t[1],10),n=t[2].trim();i(n)?e>1&&(o=`Method ${e}`):o=n}else{let t=e.match(/^[-\s]*Method\s*(\d+)/i);if(t){let e=parseInt(t[1],10);e>1&&(o=`Method ${e}`)}else{let t=e.match(/^[-\s]*\((.+)\)$/);if(t){let e=t[1].trim();i(e)||(o=e)}else{let t=e.match(/^[-\s]+([^-]+)$/);t&&!i(t[1])&&(o=t[1].trim())}}}}}else{let e=a.match(/^(.*?)\s*-\s*Method\s*(\d+)\s*\((.+)\)$/i);if(e){a=e[1].trim();let t=parseInt(e[2],10),n=e[3].trim();i(n)?t>1&&(o=`Method ${t}`):o=n}else{let e=a.match(/^(.*?)\s*-\s*Method\s*(\d+)$/i);if(e){a=e[1].trim();let t=parseInt(e[2],10);t>1&&(o=`Method ${t}`)}else{let e=a.match(/^(.*?)\s*\(\s*Method\s*(\d+)\s*\)$/i);if(e){a=e[1].trim();let t=parseInt(e[2],10);t>1&&(o=`Method ${t}`)}}}}let s=`General Algorithm`;return i(n)?i(r)?o&&!i(o)&&(s=o):s=r.trim():s=n.trim(),{cleanTitle:a,approachVariant:o,pattern:s}}function de(e,t,n){if(!e)return[];if(Array.isArray(e.solutions)&&e.solutions.length>0)return e.solutions;let r=[],i=t||e.reference_code||``,a=e.pattern||`General Algorithm`,o=e.optimal_time||`O(N)`,s=e.optimal_space||`O(1)`;return(i||a)&&r.push({id:`sol-1`,name:e.approach_variant||`Optimal Solution`,pattern:a,time_complexity:o,space_complexity:s,code:i,explanation:e.how_to_solve||``,is_optimal:!0}),n&&n.trim()&&n.trim()!==i.trim()&&r.push({id:`sol-2`,name:`Personal Solution`,pattern:a,time_complexity:o,space_complexity:s,code:n,is_optimal:!1}),r}function W(e){if(e&&e!==`sandbox-user-id`)return e;try{let e=k();if(e?.user?.id&&e.user.id!==`sandbox-user-id`)return e.user.id}catch{}return`guest`}function fe({overrideProblemId:e,refreshTrigger:t,onClearOverride:n}){let[r,i]=(0,H.useState)([]),[a,o]=(0,H.useState)(!0),[s,c]=(0,H.useState)(null),[l,u]=(0,H.useState)(!1),[d,f]=(0,H.useState)(null),[p,m]=(0,H.useState)(null),[h,g]=(0,H.useState)(``),[_,v]=(0,H.useState)(null),[y,ee]=(0,H.useState)(!1),[b,x]=(0,H.useState)(()=>{try{return k()?.user?.id}catch{return}}),S=(0,H.useRef)(!1),C=(0,H.useRef)(n),w=(0,H.useRef)(!1);(0,H.useEffect)(()=>{C.current=n});let T=(0,H.useCallback)(async(t=!0)=>{t?(o(!0),m(null),c(null),g(``),S.current=!1):m(null);let n=W(b);try{if(typeof navigator<`u`&&!navigator.onLine)throw Error(`Network connection offline.`);let{data:{session:r}}=await A.auth.getSession(),a=r?r.access_token:`sandbox`;r?.user?.id&&(x(r.user.id),n=W(r.user.id));let o={Authorization:`Bearer ${a}`},s=new AbortController,l=setTimeout(()=>s.abort(),4e3),u;try{u=await fetch(`/api/reviews/due`,{headers:o,signal:s.signal})}finally{clearTimeout(l)}if(!u.ok)throw Error(`Failed to load review queue: HTTP ${u.status}`);let d=await u.json();if(Array.isArray(d)||(d=[]),e){let t=String(e).trim().toLowerCase(),n=d.findIndex(e=>{let n=e.problems;return!!(e.problem_id&&String(e.problem_id).trim().toLowerCase()===t||n?.id&&String(n.id).trim().toLowerCase()===t||n?.problem_number!==void 0&&n?.problem_number!==null&&String(n.problem_number)===t||n?.name&&n.name.trim().toLowerCase()===t)});if(n>0){let[e]=d.splice(n,1);d.unshift(e)}else if(n===-1){let t=null,n=await fetch(`/api/reviews/problems/id/${e}`,{headers:o});if(n.ok){let e=await n.json();Array.isArray(e)&&e.length>0&&(t=e[0])}if(!t){let n=/^\d+$/.test(e),r=P(n?parseInt(e,10):void 0,e);if(r)try{let e=await j(r);if(e?.problem_id){let n=await fetch(`/api/reviews/problems/id/${e.problem_id}`,{headers:o});if(n.ok){let e=await n.json();Array.isArray(e)&&e.length>0&&(t=e[0])}}}catch(e){console.error(`Failed to auto-activate problem for override review:`,e)}}t&&d.unshift(t)}}i(d),c(null);try{localStorage.setItem(`algospaced_review_queue_${n}`,JSON.stringify(d))}catch{}if(d&&d.length>0){if(t){let e=d[0],t=e.problems,n=t?.problem_number??(/^\d+$/.test(e?.problem_id||``)?parseInt(e.problem_id,10):void 0),r=P(n,t?.id||e?.problem_id,t?.name)?.starter_code||t?.starter_code||``;g(r)}}else try{let e=await fetch(`/api/journey-progress`,{headers:o});if(e.ok){let t=await e.json();v(F(new Set(t))??null)}else v(F(new Set)??null)}catch{v(F(new Set)??null)}}catch(e){console.error(`Error fetching review queue:`,e);let r=e instanceof Error?e.message:`Network error loading review queue.`,a=!1;try{let e=localStorage.getItem(`algospaced_review_queue_${n}`);if(e){let n=JSON.parse(e);if(Array.isArray(n)&&n.length>0&&(i(n),a=!0,c(null),t)){let e=n[0],t=e.problems,r=t?.problem_number??(/^\d+$/.test(e?.problem_id||``)?parseInt(e.problem_id,10):void 0),i=P(r,t?.id||e?.problem_id,t?.name)?.starter_code||t?.starter_code||``;g(i)}}}catch(e){console.warn(`Failed to parse cached review items:`,e)}a||c(r)}finally{o(!1)}},[e,b]);(0,H.useEffect)(()=>{if(w.current){w.current=!1;return}let e=!1,t=setTimeout(()=>{e||T(!0)},0);return()=>{e=!0,clearTimeout(t)}},[T,t]),(0,H.useEffect)(()=>{if(!a&&!s&&r.length===0&&!e&&!S.current){S.current=!0;try{ie({particleCount:90,spread:70,origin:{y:.6}})}catch{}}},[a,s,r.length,e]);let E=(0,H.useCallback)(async t=>{if(r.length===0||l)return;let n=r[0];if(!n||!n.id)return;u(!0),f(t),m(null);let a=[...r];try{let{data:{session:r}}=await A.auth.getSession(),o=r?r.access_token:`sandbox`,s=await fetch(`/api/reviews/complete`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${o}`},body:JSON.stringify({review_id:n.id,fsrs_state:n.fsrs_state??0,fsrs_step:n.fsrs_step??0,fsrs_stability:n.fsrs_stability??0,fsrs_difficulty:n.fsrs_difficulty??0,fsrs_elapsed_days:n.fsrs_elapsed_days??0,fsrs_scheduled_days:n.fsrs_scheduled_days??0,fsrs_reps:n.fsrs_reps??0,fsrs_lapses:n.fsrs_lapses??0,last_reviewed:n.last_reviewed,rating:t})});if(s.ok){let r=n?.problems?.name||``,a=n?.problems?.pattern||``,o=`Correct`;o=t===1?`Incorrect`:t===2?`Mixed`:`Correct`,L.addReviewEvent(o,r,a).catch(()=>{});let s=re(),l=h.trim()||n?.problems?.reference_code||``;s.token&&s.repoName&&s.autoCommit&&l&&ne({token:s.token,repo:s.repoName,branch:s.branch,problem_number:n?.problems?.problem_number,problem_name:r||`Algorithm Problem`,pattern:a||`Algorithms`,difficulty:n?.problems?.difficulty||`Medium`,optimal_time:n?.problems?.optimal_time||`O(N)`,optimal_space:n?.problems?.optimal_space||`O(1)`,description:n?.problems?.description||``,code:l}).catch(e=>{console.warn(`GitHub background auto-commit failed:`,e)}),e&&C.current&&(w.current=!0,C.current()),i(e=>{let t=e.slice(1);try{let e=W(b);localStorage.setItem(`algospaced_review_queue_${e}`,JSON.stringify(t))}catch{}if(t.length>0){let e=t[0],n=e.problems,r=n?.problem_number??(/^\d+$/.test(e?.problem_id||``)?parseInt(e.problem_id,10):void 0),i=P(r,n?.id||e?.problem_id,n?.name)?.starter_code||n?.starter_code||``;g(i)}else g(``);return t}),c(null),T(!1)}else{let e=await s.json().catch(()=>({}));m(e.detail||`Server returned error (${s.status}). Please try again.`),i(a)}}catch(e){console.error(`Error logging review completion:`,e);let t=e instanceof Error?e.message:`Network connection failed while logging review.`;m(t),i(a)}finally{u(!1),f(null)}},[r,l,e,T,h,b]),D=(0,H.useCallback)(async()=>{if(_&&!y){ee(!0);try{await j(_),await T()}catch(e){console.error(`Failed to activate next milestone:`,e)}finally{ee(!1)}}},[_,y,T]),te=(0,H.useCallback)(()=>{let e=r[0],t=e?.problems,n=t?.problem_number??(/^\d+$/.test(e?.problem_id||``)?parseInt(e.problem_id,10):void 0),i=P(n,t?.id||e?.problem_id,t?.name)?.starter_code||t?.starter_code||``;g(i)},[r]);return{reviews:r,setReviews:i,loading:a,queueError:s,submitting:l,submittingRating:d,gradeError:p,setGradeError:m,code:h,setCode:g,nextMilestone:_,activatingMilestone:y,currentUserId:b,fetchQueue:T,handleGrade:E,handleSelectCard:(0,H.useCallback)(t=>{if(t<=0||t>=r.length||l)return;e&&C.current&&(w.current=!0,C.current());let n=r[t];if(!n)return;let a=n.problems,o=a?.problem_number??(/^\d+$/.test(n?.problem_id||``)?parseInt(n.problem_id,10):void 0),s=P(o,a?.id||n?.problem_id,a?.name)?.starter_code||a?.starter_code||``;g(s),i(e=>{let t=e.findIndex(e=>e.id&&e.id===n.id||e===n);return t<=0?e:[e[t],...e.slice(0,t),...e.slice(t+1)]})},[r,l,e]),handleActivateNextMilestone:D,handleResetStarterCode:te}}function pe(){return{sandboxRunning:M(e=>e.sandboxRunning),sandboxResults:M(e=>e.sandboxResults),sandboxError:M(e=>e.sandboxError),savingReference:M(e=>e.savingReference),savedRefSuccess:M(e=>e.savedRefSuccess),saveRefError:M(e=>e.saveRefError),handleRunSandbox:M(e=>e.handleRunSandbox),handleSaveReference:M(e=>e.handleSaveReference),resetSandbox:M(e=>e.resetSandbox)}}function me(){return{aiLoading:M(e=>e.aiLoading),aiResult:M(e=>e.aiResult),aiError:M(e=>e.aiError),explainLoading:M(e=>e.explainLoading),explanationText:M(e=>e.explanationText),explainError:M(e=>e.explainError),aiSolutionLoading:M(e=>e.aiSolutionLoading),aiSolutionError:M(e=>e.aiSolutionError),handleAiEvaluation:M(e=>e.handleAiEvaluation),handleExplainCode:M(e=>e.handleExplainCode),handleFetchAiSolution:M(e=>e.handleFetchAiSolution),resetAiState:M(e=>e.resetAiState)}}var he=({problem:e,totalInQueue:t,reviews:n=[],onSelectCard:r,onOpenCreateProblem:i,onOpenEditProblem:o})=>{let[s,c]=(0,H.useState)(!1),u=(0,H.useRef)(null);(0,H.useEffect)(()=>{let e=e=>{u.current&&!u.current.contains(e.target)&&c(!1)},t=e=>{e.key===`Escape`&&c(!1)};return s&&(document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t)),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[s]);let d=e.problem_number?`https://leetcode.com/problemset/all/?search=${e.problem_number}`:`https://leetcode.com/problemset/all/?search=${encodeURIComponent(e.name||``)}`;return(0,U.jsxs)(`div`,{className:`shrink-0 bg-paper-white border-b-[3px] border-ink-black px-2.5 sm:px-4 py-2 flex flex-wrap items-center justify-between gap-2 shadow-[0_2px_0_0_rgba(30,41,59,0.05)] relative z-40`,children:[(0,U.jsxs)(`div`,{className:`flex items-center gap-1.5 sm:gap-2 flex-wrap min-w-0`,children:[(0,U.jsxs)(`div`,{className:`relative shrink-0`,ref:u,children:[(0,U.jsxs)(`button`,{onClick:()=>c(e=>!e),className:`h-7 inline-flex items-center gap-1.5 px-2 sm:px-2.5 bg-amber-300 hover:bg-amber-200 border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none transition-all cursor-pointer shrink-0`,title:`Click to view all cards due in today's queue`,children:[(0,U.jsx)(`span`,{className:`w-2 h-2 rounded-full bg-emerald-500 animate-ping shrink-0`}),(0,U.jsx)(`span`,{className:`font-arcade text-[8px] sm:text-[9px] font-bold text-ink-black tracking-wide whitespace-nowrap`,children:`CARD 1 OF ${t}`}),t>1&&(0,U.jsx)(te,{className:`w-3 h-3 text-ink-black transition-transform shrink-0 ${s?`rotate-180`:``}`})]}),s&&n.length>0&&(0,U.jsxs)(`div`,{className:`absolute top-9 left-0 z-50 w-64 min-[400px]:w-72 sm:w-80 bg-paper-white border-[3px] border-ink-black gadget-shadow p-3 space-y-2 max-w-[calc(100vw-32px)]`,children:[(0,U.jsxs)(`div`,{className:`flex items-center justify-between border-b-2 border-ink-black pb-1.5 font-arcade text-[9px] font-bold text-ink-black`,children:[(0,U.jsx)(`span`,{children:`DAILY QUEUE (${n.length} CARDS)`}),(0,U.jsx)(`button`,{onClick:()=>c(!1),className:`px-1 hover:text-rose-600 font-bold cursor-pointer`,title:`Close`,children:`✕`})]}),(0,U.jsx)(`div`,{className:`text-[7.5px] font-arcade text-trash-gray uppercase -mt-0.5`,children:`Click any card to solve it now:`}),(0,U.jsx)(`div`,{className:`max-h-60 overflow-y-auto no-scrollbar space-y-1.5 pr-1`,children:n.map((e,t)=>{let n=e.problems,i=n?.problem_number,a=i==null?void 0:N(i),{cleanTitle:o,approachVariant:s}=ue(n?.name||``,a?.name),u=s?`${o} (${s})`:o,d=t===0,f=n?.difficulty,p=f?f.toUpperCase():`EASY`,m=f===`Easy`?`bg-emerald-600 text-white`:f===`Medium`?`bg-amber-400 text-ink-black`:`bg-rose-600 text-white`;return(0,U.jsxs)(`button`,{type:`button`,onClick:()=>{d||r?.(t),c(!1)},className:`group w-full text-left p-2 border-2 border-ink-black text-xs flex items-center justify-between gap-2 cursor-pointer transition-all duration-150 select-none ${d?`bg-amber-100 font-bold shadow-[2px_2px_0px_0px_rgba(30,41,59,1)]`:`bg-white hover:bg-amber-50 hover:translate-x-0.5 active:translate-y-0.5 active:shadow-none shadow-[2px_2px_0px_0px_rgba(30,41,59,0.25)]`}`,title:d?`Currently active card`:`Jump to #${t+1}: ${u}`,children:[(0,U.jsxs)(`div`,{className:`flex items-center gap-1.5 truncate min-w-0`,children:[(0,U.jsxs)(`span`,{className:`font-arcade text-[9px] text-trash-gray shrink-0`,children:[`#`,t+1]}),i!=null&&(0,U.jsxs)(`span`,{className:`font-arcade text-[8px] font-bold px-1 py-0.2 bg-amber-300 border border-ink-black shrink-0`,children:[`LC #`,i]}),(0,U.jsx)(`span`,{className:`truncate`,children:u})]}),(0,U.jsxs)(`div`,{className:`flex items-center gap-1.5 shrink-0`,children:[d?(0,U.jsx)(`span`,{className:`text-[7.5px] font-arcade font-extrabold px-1 py-0.5 bg-amber-300 text-ink-black border border-ink-black shrink-0`,children:`NOW`}):(0,U.jsx)(l,{className:`w-2.5 h-2.5 fill-ink-black text-ink-black opacity-0 group-hover:opacity-100 transition-opacity shrink-0`}),(0,U.jsx)(`span`,{className:`text-[8px] font-arcade font-bold px-1.5 py-0.5 border border-ink-black shrink-0 ${m}`,children:p})]})]},e.id||t)})})]})]}),e.problem_number!==void 0&&e.problem_number!==null&&(0,U.jsx)(`span`,{className:`h-7 inline-flex items-center px-2 font-arcade text-[8px] sm:text-[9px] font-bold bg-amber-200 border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] text-ink-black shrink-0 select-none whitespace-nowrap`,children:e.problem_number>0?`LC #${e.problem_number}`:`CUSTOM`}),(0,U.jsx)(`span`,{className:`h-7 inline-flex items-center px-2 font-arcade text-[8px] sm:text-[9px] font-bold border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] shrink-0 select-none whitespace-nowrap ${e.difficulty===`Easy`?`bg-emerald-600 text-white`:e.difficulty===`Medium`?`bg-amber-400 text-ink-black`:`bg-rose-600 text-white`}`,children:e.difficulty?e.difficulty.toUpperCase():`EASY`})]}),(0,U.jsxs)(`div`,{className:`flex items-center gap-1.5 sm:gap-2 shrink-0 flex-wrap justify-end`,children:[(0,U.jsxs)(`button`,{onClick:i,className:`h-7 inline-flex items-center gap-1 px-2 sm:px-2.5 bg-white hover:bg-purple-50 border-2 border-ink-black text-ink-black text-[8px] sm:text-[9px] font-arcade font-bold shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none transition-all cursor-pointer shrink-0`,title:`Create or Import Problem`,children:[(0,U.jsx)(y,{className:`w-3 h-3 text-purple-600 shrink-0`}),(0,U.jsx)(`span`,{className:`hidden min-[480px]:inline`,children:`ADD`})]}),o&&(0,U.jsxs)(`button`,{onClick:o,className:`h-7 inline-flex items-center gap-1 px-2 sm:px-2.5 bg-white hover:bg-emerald-50 border-2 border-ink-black text-ink-black text-[8px] sm:text-[9px] font-arcade font-bold shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none transition-all cursor-pointer shrink-0`,title:`Edit Problem Specification`,children:[(0,U.jsx)(a,{className:`w-3 h-3 text-emerald-600 shrink-0`}),(0,U.jsx)(`span`,{className:`hidden min-[480px]:inline`,children:`EDIT`})]}),e.google_doc_url&&(0,U.jsxs)(`a`,{href:e.google_doc_url,target:`_blank`,rel:`noreferrer`,className:`h-7 inline-flex items-center gap-1 px-2 sm:px-2.5 bg-white hover:bg-slate-100 border-2 border-ink-black text-ink-black text-[8px] sm:text-[9px] font-arcade font-bold shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none transition-all cursor-pointer shrink-0`,title:`Open Google Doc Notes`,children:[(0,U.jsx)(`span`,{children:`DOC`}),(0,U.jsx)(_,{className:`w-2.5 h-2.5 text-primary shrink-0`})]}),(0,U.jsxs)(`a`,{href:d,target:`_blank`,rel:`noreferrer`,className:`h-7 inline-flex items-center gap-1 px-2 sm:px-2.5 bg-white hover:bg-slate-100 border-2 border-ink-black text-ink-black text-[8px] sm:text-[9px] font-arcade font-bold shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none transition-all cursor-pointer shrink-0`,title:`Search LeetCode`,children:[(0,U.jsx)(`span`,{children:`LC`}),(0,U.jsx)(_,{className:`w-2.5 h-2.5 text-amber-600 shrink-0`})]})]})]})},ge=se.mark({class:`cm-indent-dot cm-indent-dot-primary`}),_e=se.mark({class:`cm-indent-dot cm-indent-dot-secondary`});function G(e){let t=new B;for(let{from:n,to:r}of e.visibleRanges){let i=n;for(;i<r;){let n=e.state.doc.lineAt(i),r=n.text,a=0;for(;a<r.length&&(r[a]===` `||r[a]===` `);){let e=n.from+a,i=e+1,o=a%4==0||r[a]===` `;t.add(e,i,o?ge:_e),a++}i=n.to+1}}return t.finish()}var ve=z.fromClass(class{decorations;constructor(e){this.decorations=G(e)}update(e){(e.docChanged||e.viewportChanged)&&(this.decorations=G(e.view))}},{decorations:e=>e.decorations}),ye=V.theme({"&":{backgroundColor:`#0c111d`,color:`#f1f5f9`,height:`100%`,fontSize:`13px`,fontFamily:`var(--font-code, "JetBrains Mono", "Fira Code", monospace)`},".cm-scroller":{overflow:`auto`,fontFamily:`inherit`,lineHeight:`1.65`},".cm-content":{caretColor:`#4ade80`,padding:`12px 0`},"&.cm-focused .cm-cursor":{borderLeftColor:`#4ade80`,borderLeftWidth:`2px`,filter:`drop-shadow(0 0 5px rgba(74, 222, 128, 0.8))`},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground, ::selection":{backgroundColor:`rgba(56, 189, 248, 0.25) !important`},".cm-gutters":{backgroundColor:`#070a12`,color:`#475569`,borderRight:`2px solid #1e293b`,paddingRight:`6px`,userSelect:`none`},".cm-activeLineGutter":{backgroundColor:`#131b2e`,color:`#38bdf8`,fontWeight:`700`},".cm-activeLine, &.cm-focused .cm-activeLine":{backgroundColor:`#0f172a !important`},".cm-line":{padding:`0 10px`},".cm-indent-dot":{position:`relative`,display:`inline-block`},".cm-indent-dot::before":{position:`absolute`,top:`50%`,left:`50%`,transform:`translate(-50%, -50%)`,pointerEvents:`none`,userSelect:`none`,lineHeight:`0`,fontFamily:`monospace`},".cm-indent-dot-primary::before":{content:`"•"`,color:`#38bdf8`,fontSize:`9px`,opacity:`0.85`},".cm-indent-dot-secondary::before":{content:`"·"`,color:`#64748b`,fontSize:`11px`,opacity:`0.5`},"&.cm-focused .cm-matchingBracket, .cm-matchingBracket":{backgroundColor:`rgba(74, 222, 128, 0.2)`,outline:`1px solid #4ade80`,borderRadius:`2px`,color:`#86efac !important`},".cm-placeholder":{color:`#64748b`,fontStyle:`italic`},".cm-scroller::-webkit-scrollbar":{width:`6px`,height:`6px`},".cm-scroller::-webkit-scrollbar-track":{backgroundColor:`#070a12`},".cm-scroller::-webkit-scrollbar-thumb":{backgroundColor:`#1e293b`,borderRadius:`3px`,border:`1px solid #334155`},".cm-scroller::-webkit-scrollbar-thumb:hover":{backgroundColor:`#38bdf8`}}),be=[oe(),ce.of(` `),R.of([ae]),ve,ye,V.contentAttributes.of({"aria-label":`Python Code Editor`})],K=[{id:`python`,name:`Python`,version:`3.14`}],xe=({className:e=`w-3.5 h-3.5`})=>(0,U.jsxs)(`svg`,{viewBox:`0 0 128 128`,className:e,xmlns:`http://www.w3.org/2000/svg`,children:[(0,U.jsx)(`path`,{d:`M63.454 4.018c-14.775 0-23.774 6.425-23.774 18.775v13.626h24.168v3.424H30.082C17.518 39.843 8 47.962 8 63.673c0 15.65 8.358 23.486 21.056 23.486h11.905v-16.89c0-13.064 11.233-24.113 24.331-24.113h23.773V32.793c0-11.83-9.988-19.775-23.773-19.775H63.454v-9zm-9.845 7.426a3.84 3.84 0 0 1 3.86 3.84 3.84 3.84 0 0 1-3.86 3.841 3.84 3.84 0 0 1-3.86-3.84 3.84 3.84 0 0 1 3.86-3.841z`,fill:`#387eb8`}),(0,U.jsx)(`path`,{d:`M64.546 123.982c14.775 0 23.774-6.425 23.774-18.775V91.581H64.152v-3.424h33.766c12.564 0 22.082-8.119 22.082-23.83 0-15.65-8.358-23.486-21.056-23.486H87.04v16.89c0 13.064-11.234 24.113-24.332 24.113H38.934v13.363c0 11.83 9.989 19.775 23.774 19.775h1.838v9zm9.845-7.426a3.84 3.84 0 0 1-3.86-3.84 3.84 3.84 0 0 1 3.86-3.841 3.84 3.84 0 0 1 3.86 3.84 3.84 3.84 0 0 1-3.86 3.841z`,fill:`#ffe052`})]}),Se=({mobileView:e,isNarrow:t=!1,isAutocompleteEnabled:r,onToggleAutocomplete:a,onResetStarterCode:o,code:d,onChangeCode:p,sandboxRunning:v,sandboxError:y,sandboxResults:x,onRunSandbox:S,savingReference:C,savedRefSuccess:T,saveRefError:E,onSaveReference:O,aiLoading:k,aiError:A,aiResult:j,onAiEvaluation:M,optimalTime:N,optimalSpace:P,onPushToGitHub:F,pushingToGitHub:I,githubPushedUrl:L,githubPushError:ne})=>{let[re,ie]=(0,H.useState)(`python`),[R,z]=(0,H.useState)(!1),B=(0,H.useRef)(null);(0,H.useEffect)(()=>{let e=e=>{B.current&&!B.current.contains(e.target)&&z(!1)},t=e=>{e.key===`Escape`&&z(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[]);let V=K.find(e=>e.id===re)??K[0];return(0,U.jsxs)(`div`,{className:`w-full ${t?`flex flex-1`:`lg:w-[51%] flex`} flex-col bg-[#fffdfa] overflow-y-auto no-scrollbar ${t&&e!==`code`?`hidden`:`flex`}`,children:[(0,U.jsxs)(`div`,{className:`shrink-0 bg-[#f7f5ed] border-b-2 border-ink-black p-2 sm:px-3 flex flex-wrap items-center justify-between gap-1.5 sm:gap-2`,children:[(0,U.jsxs)(`div`,{className:`flex items-center gap-1.5 sm:gap-2 flex-wrap`,children:[(0,U.jsxs)(`div`,{className:`relative`,ref:B,children:[(0,U.jsxs)(`button`,{type:`button`,onClick:()=>z(e=>!e),className:`h-7 px-2.5 bg-white hover:bg-slate-100 border-2 border-ink-black shadow-[1px_1px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none flex items-center gap-1.5 font-arcade text-[9px] font-bold text-ink-black cursor-pointer transition-all select-none`,title:`Select programming language`,"aria-expanded":R,"aria-haspopup":`listbox`,children:[(0,U.jsx)(xe,{className:`w-3.5 h-3.5 shrink-0`}),(0,U.jsx)(`span`,{children:V.name}),(0,U.jsx)(te,{className:`w-3 h-3 text-ink-black transition-transform duration-150 ${R?`rotate-180`:``}`})]}),R&&(0,U.jsxs)(`div`,{className:`absolute top-full mt-1.5 left-0 z-50 w-52 bg-paper-white border-[3px] border-ink-black gadget-shadow p-1.5 space-y-1`,role:`listbox`,children:[(0,U.jsx)(`div`,{className:`px-2 py-1 text-[8px] font-arcade font-bold text-trash-gray uppercase border-b border-slate-200`,children:`SELECT LANGUAGE`}),K.map(e=>{let t=re===e.id;return(0,U.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":t,onClick:()=>{ie(e.id),z(!1)},className:`w-full flex items-center justify-between px-2.5 py-1.5 border-2 border-ink-black text-left transition-all cursor-pointer ${t?`bg-amber-200 shadow-[1px_1px_0px_0px_rgba(30,41,59,1)] font-bold text-ink-black`:`bg-white hover:bg-slate-100 text-slate-800`}`,children:[(0,U.jsxs)(`div`,{className:`flex items-center gap-1.5 font-arcade text-[9px]`,children:[(0,U.jsx)(xe,{className:`w-3.5 h-3.5 shrink-0`}),(0,U.jsx)(`span`,{children:e.name})]}),(0,U.jsxs)(`span`,{className:`font-mono text-[8px] font-bold px-1.5 py-0.5 bg-white border border-ink-black text-slate-700 shadow-[1px_1px_0px_0px_rgba(30,41,59,0.3)]`,children:[`v`,e.version]})]},e.id)})]})]}),(0,U.jsx)(`div`,{className:`h-4 w-[2px] bg-slate-300 mx-0.5 hidden sm:block`}),(0,U.jsxs)(`label`,{className:`inline-flex items-center gap-1.5 cursor-pointer select-none`,children:[(0,U.jsx)(`input`,{type:`checkbox`,checked:r,onChange:e=>a(e.target.checked),className:`sr-only peer`,"aria-label":`Toggle code editor autocompletion`}),(0,U.jsx)(`div`,{className:`relative w-7 h-3.5 bg-slate-300 border border-ink-black rounded-full peer peer-checked:bg-grass-green transition-all after:content-[''] after:absolute after:top-[1px] after:left-[2px] after:bg-white after:border after:border-ink-black after:rounded-full after:h-2 after:w-2 after:transition-all peer-checked:after:translate-x-3`}),(0,U.jsx)(`span`,{className:`text-[7.5px] min-[400px]:text-[8px] font-arcade font-bold text-trash-gray peer-checked:text-ink-black whitespace-nowrap`,children:`AUTOCOMPLETE`})]})]}),(0,U.jsxs)(`div`,{className:`flex items-center gap-1.5 sm:gap-2`,children:[(0,U.jsx)(`button`,{onClick:o,className:`w-7 h-7 bg-white hover:bg-slate-100 border-2 border-ink-black shadow-[1px_1px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none text-ink-black flex items-center justify-center cursor-pointer transition-all`,title:`Reset to starter code`,"aria-label":`Reset to starter code`,children:(0,U.jsx)(n,{className:`w-3.5 h-3.5`})}),(0,U.jsx)(`button`,{onClick:()=>p(``),className:`w-7 h-7 bg-white hover:bg-rose-50 border-2 border-ink-black shadow-[1px_1px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none text-rose-700 flex items-center justify-center cursor-pointer transition-all`,title:`Clear editor`,"aria-label":`Clear editor`,children:(0,U.jsx)(ee,{className:`w-3.5 h-3.5 text-rose-600`})}),O&&(0,U.jsx)(`button`,{onClick:O,disabled:C||!d.trim(),className:`w-7 h-7 border-2 border-ink-black shadow-[1px_1px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none flex items-center justify-center cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed transition-all ${T?`bg-emerald-600 hover:bg-emerald-500 text-white`:`bg-amber-400 hover:bg-amber-300 text-ink-black`}`,title:C?`Saving solution to personal database...`:T?`Saved to personal database!`:`Overwrite saved solution with studio code`,"aria-label":`Overwrite saved solution with studio code`,children:C?(0,U.jsx)(s,{className:`w-3.5 h-3.5 animate-spin text-ink-black`}):T?(0,U.jsx)(g,{className:`w-3.5 h-3.5 text-white`}):(0,U.jsx)(c,{className:`w-3.5 h-3.5 text-ink-black`})}),F&&(0,U.jsx)(`button`,{onClick:F,disabled:I||!d.trim(),className:`w-7 h-7 bg-[#24292e] hover:bg-black border-2 border-ink-black shadow-[1px_1px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none text-white flex items-center justify-center cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed transition-all`,title:I?`Pushing to GitHub...`:`Push solution to GitHub repository`,"aria-label":`Push to GitHub`,children:I?(0,U.jsx)(s,{className:`w-3.5 h-3.5 animate-spin text-yellow-300`}):(0,U.jsx)(h,{className:`w-3.5 h-3.5 text-yellow-300`})})]}),(0,U.jsxs)(`div`,{className:`flex items-center gap-1.5 sm:gap-2`,children:[(0,U.jsx)(`button`,{onClick:S,disabled:v||!d.trim(),className:`w-7 h-7 bg-emerald-600 hover:bg-emerald-500 border-2 border-ink-black shadow-[1px_1px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none text-white flex items-center justify-center cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed transition-all`,title:v?`Running sandbox tests...`:`Run tests in local sandbox`,"aria-label":`Run tests`,children:v?(0,U.jsx)(s,{className:`w-3.5 h-3.5 animate-spin`}):(0,U.jsx)(l,{className:`w-3.5 h-3.5 fill-white text-white ml-0.5`})}),(0,U.jsx)(`button`,{onClick:M,disabled:k||!d.trim(),className:`w-7 h-7 bg-purple-600 hover:bg-purple-500 border-2 border-ink-black shadow-[1px_1px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none text-white flex items-center justify-center cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed transition-all`,title:k?`Evaluating code with Gemini...`:`Gemini Eval (AI code review & complexity)`,"aria-label":`Gemini Eval`,children:k?(0,U.jsx)(s,{className:`w-3.5 h-3.5 animate-spin`}):(0,U.jsx)(D,{className:`w-3.5 h-3.5 text-amber-300`})})]})]}),(0,U.jsxs)(`div`,{className:`p-4 sm:p-5 flex-1 flex flex-col space-y-4`,children:[(0,U.jsx)(`div`,{className:`flex-1 flex flex-col min-h-[300px] sm:min-h-[360px] border-[3px] border-ink-black shadow-[4px_4px_0px_0px_rgba(30,41,59,1)] bg-[#0c111d] overflow-hidden`,children:(0,U.jsx)(`div`,{className:`flex-1 overflow-hidden relative`,children:(0,U.jsx)(w,{value:d,onChange:p,placeholder:`def solve(nums): # Write your solution from memory here...`,height:`100%`,theme:`dark`,extensions:be,basicSetup:{autocompletion:r,lineNumbers:!0,foldGutter:!0,dropCursor:!0,allowMultipleSelections:!0,indentOnInput:!0,bracketMatching:!0,closeBrackets:!0,rectangularSelection:!0,crosshairCursor:!0,highlightActiveLine:!0,highlightSelectionMatches:!0,closeBracketsKeymap:!0,defaultKeymap:!0,searchKeymap:!0,historyKeymap:!0,foldKeymap:!0,completionKeymap:!0,lintKeymap:!0},className:`w-full h-full text-xs font-code-mono`})})}),T&&(0,U.jsxs)(`div`,{className:`p-3 bg-[#f0fdf4] border-2 border-emerald-600 text-emerald-950 text-xs font-semibold flex items-center gap-2 shadow-[2px_2px_0px_0px_rgba(30,41,59,1)]`,children:[(0,U.jsx)(g,{className:`w-4 h-4 text-emerald-600 shrink-0`}),(0,U.jsx)(`span`,{children:`Successfully saved studio code as your personal reference solution!`})]}),E&&(0,U.jsxs)(`div`,{className:`p-3 bg-rose-50 border-2 border-rose-500 text-rose-800 text-xs font-semibold flex items-center gap-2 shadow-[2px_2px_0px_0px_rgba(30,41,59,1)]`,children:[(0,U.jsx)(m,{className:`w-4 h-4 text-rose-600 shrink-0`}),(0,U.jsx)(`span`,{children:E})]}),L&&(0,U.jsxs)(`div`,{className:`p-3 bg-[#f0fdf4] border-2 border-emerald-600 text-emerald-950 text-xs font-semibold flex items-center justify-between shadow-[2px_2px_0px_0px_rgba(30,41,59,1)]`,children:[(0,U.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,U.jsx)(g,{className:`w-4 h-4 text-emerald-600 shrink-0`}),(0,U.jsx)(`span`,{children:`Successfully pushed solution to your GitHub repository!`})]}),(0,U.jsxs)(`a`,{href:L,target:`_blank`,rel:`noopener noreferrer`,className:`text-[11px] font-bold text-blue-700 hover:text-blue-900 underline flex items-center gap-1`,children:[(0,U.jsx)(`span`,{children:`View on GitHub`}),(0,U.jsx)(_,{className:`w-3 h-3`})]})]}),ne&&(0,U.jsxs)(`div`,{className:`p-3 bg-rose-50 border-2 border-rose-500 text-rose-800 text-xs font-semibold flex items-center gap-2 shadow-[2px_2px_0px_0px_rgba(30,41,59,1)]`,children:[(0,U.jsx)(m,{className:`w-4 h-4 text-rose-600 shrink-0`}),(0,U.jsx)(`span`,{children:ne})]}),v&&(0,U.jsxs)(`div`,{className:`p-3 border-2 border-ink-black bg-emerald-50 shadow-[3px_3px_0px_0px_rgba(30,41,59,1)] flex items-center gap-3 animate-pulse`,children:[(0,U.jsx)(s,{className:`w-5 h-5 text-emerald-600 animate-spin shrink-0`}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`h4`,{className:`font-arcade text-[9px] font-bold text-ink-black uppercase`,children:`Running...`}),(0,U.jsx)(`p`,{className:`font-sans text-[11px] text-trash-gray font-semibold mt-0.5`,children:`Executing against test cases...`})]})]}),y&&(0,U.jsxs)(`div`,{className:`p-3 border-2 border-rose-500 bg-rose-50 text-rose-800 text-xs font-semibold shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] flex items-center gap-2`,children:[(0,U.jsx)(m,{className:`w-4 h-4 text-rose-600 shrink-0`}),(0,U.jsx)(`span`,{children:y})]}),x&&(0,U.jsxs)(`div`,{className:`border-[3px] border-ink-black p-4 sm:p-5 shadow-[4px_4px_0px_0px_rgba(30,41,59,1)] space-y-3.5 ${x.status===`passed`?`bg-[#f0fdf4]`:`bg-[#fff1f2]`}`,children:[(0,U.jsxs)(`div`,{className:`flex flex-col sm:flex-row sm:items-center justify-between gap-2 pb-2.5 border-b-2 border-dashed border-ink-black`,children:[(0,U.jsxs)(`div`,{className:`flex items-center gap-2.5`,children:[(0,U.jsx)(`div`,{className:`w-8 h-8 border-2 border-ink-black flex items-center justify-center font-bold shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] ${x.status===`passed`?`bg-grass-green text-ink-black`:`bg-rose-500 text-white`}`,children:x.status===`passed`?(0,U.jsx)(u,{className:`w-5 h-5 stroke-[3]`}):(0,U.jsx)(m,{className:`w-4 h-4`})}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`div`,{className:`font-arcade text-[10px] font-bold text-ink-black flex items-center gap-1.5 uppercase`,children:x.status===`passed`?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`span`,{children:`ALL TESTS PASSED`}),(0,U.jsx)(g,{className:`w-3.5 h-3.5 text-emerald-600 inline`})]}):(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`span`,{children:x.status===`error`?`EXECUTION ERROR`:`TESTS FAILED`}),(0,U.jsx)(b,{className:`w-3.5 h-3.5 text-rose-600 inline`})]})}),(0,U.jsxs)(`div`,{className:`font-sans text-[11px] text-slate-600 font-semibold`,children:[x.passed_count??0,` of `,x.total_tests??0,` test cases passed (`,(x.duration_ms??0).toFixed(1),`ms)`]})]})]}),x.status===`passed`&&(0,U.jsxs)(`button`,{onClick:O,disabled:C,className:`px-3 py-1.5 bg-white hover:bg-emerald-100 border-2 border-ink-black text-ink-black font-arcade text-[8px] font-bold flex items-center gap-1.5 shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none transition-all cursor-pointer shrink-0 disabled:opacity-50`,children:[C?(0,U.jsx)(s,{className:`w-3 h-3 animate-spin`}):T?(0,U.jsx)(g,{className:`w-3.5 h-3.5 text-emerald-600`}):(0,U.jsx)(c,{className:`w-3.5 h-3.5 text-blue-600`}),(0,U.jsx)(`span`,{children:T?`SAVED TO DB!`:`SAVE AS OFFICIAL SOLUTION`})]})]}),E&&(0,U.jsx)(`div`,{className:`p-2 border border-rose-500 bg-rose-100 text-rose-800 text-[11px] font-semibold`,children:E}),x.results&&x.results.length>0&&(0,U.jsxs)(`div`,{className:`space-y-2`,children:[(0,U.jsx)(`span`,{className:`font-arcade text-[8px] text-trash-gray uppercase font-bold block`,children:`TEST CASE BREAKDOWN:`}),(0,U.jsx)(`div`,{className:`space-y-1.5 max-h-56 overflow-y-auto custom-scrollbar`,children:x.results.map((e,t)=>(0,U.jsxs)(`div`,{className:`p-2.5 border-2 border-ink-black text-xs font-mono shadow-[2px_2px_0px_0px_rgba(30,41,59,0.3)] ${e.passed?`bg-white`:`bg-rose-50`}`,children:[(0,U.jsxs)(`div`,{className:`flex items-center justify-between font-arcade text-[8px] mb-1`,children:[(0,U.jsxs)(`span`,{className:`font-bold text-ink-black`,children:[`CASE #`,t+1]}),(0,U.jsx)(`span`,{className:e.passed?`text-emerald-700 font-bold`:`text-rose-700 font-bold`,children:e.passed?`✓ PASSED`:`✗ FAILED`})]}),(0,U.jsxs)(`div`,{className:`grid grid-cols-1 sm:grid-cols-3 gap-1.5 text-[10px]`,children:[(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`span`,{className:`text-slate-500 block`,children:`Input:`}),(0,U.jsx)(`span`,{className:`font-code-mono text-ink-black font-semibold break-all`,children:JSON.stringify(e.input)})]}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`span`,{className:`text-slate-500 block`,children:`Expected:`}),(0,U.jsx)(`span`,{className:`font-code-mono text-emerald-700 font-semibold break-all`,children:JSON.stringify(e.expected)})]}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`span`,{className:`text-slate-500 block`,children:`Output:`}),(0,U.jsx)(`span`,{className:`font-code-mono font-semibold break-all ${e.passed?`text-emerald-700`:`text-rose-700`}`,children:e.output===void 0?`None`:JSON.stringify(e.output)})]})]}),e.error&&(0,U.jsx)(`div`,{className:`mt-1.5 p-1.5 bg-rose-100 text-rose-900 text-[10px] font-mono border border-rose-300 break-all`,children:e.error})]},t))})]}),x.error&&(0,U.jsx)(`div`,{className:`p-3 bg-[#1E293B] text-rose-400 font-code-mono text-[11px] border-2 border-ink-black overflow-x-auto whitespace-pre-wrap select-text`,children:x.error}),x.status===`passed`&&(0,U.jsx)(`div`,{className:`p-2 bg-emerald-100/70 border border-emerald-300 text-emerald-900 text-xs flex items-center justify-between`,children:(0,U.jsx)(`span`,{className:`font-sans font-medium`,children:`✨ All unit tests passed. Rate your recall below.`})})]}),k&&(0,U.jsxs)(`div`,{className:`p-4 border-2 border-ink-black bg-amber-50 shadow-[3px_3px_0px_0px_rgba(30,41,59,1)] flex items-center gap-3 animate-pulse`,children:[(0,U.jsx)(s,{className:`w-6 h-6 text-purple-600 animate-spin shrink-0`}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`h4`,{className:`font-arcade text-[9px] font-bold text-ink-black uppercase`,children:`ANALYZING...`}),(0,U.jsx)(`p`,{className:`font-sans text-[11px] text-trash-gray font-semibold mt-0.5`,children:`Checking edge cases, bounds, and Big-O efficiency against optimal constraints...`})]})]}),A&&(0,U.jsx)(`div`,{className:`p-3 border-2 border-rose-500 bg-rose-50 text-rose-800 text-xs font-semibold shadow-[2px_2px_0px_0px_rgba(30,41,59,1)]`,children:A}),j&&(0,U.jsxs)(`div`,{className:`border-[3px] border-ink-black bg-[#fefce8] p-4 sm:p-5 shadow-[4px_4px_0px_0px_rgba(30,41,59,1)] space-y-4`,children:[(0,U.jsxs)(`div`,{className:`flex items-center justify-between pb-3 border-b-2 border-dashed border-ink-black`,children:[(0,U.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,U.jsx)(`div`,{className:`w-9 h-9 border-2 border-ink-black flex items-center justify-center font-bold shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] ${j.is_correct?`bg-grass-green text-ink-black`:`bg-rose-500 text-white`}`,children:j.is_correct?(0,U.jsx)(u,{className:`w-5 h-5 stroke-[3]`}):(0,U.jsx)(i,{className:`w-5 h-5`})}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`span`,{className:`font-arcade text-[10px] font-bold text-ink-black flex items-center gap-1.5`,children:j.is_correct?(0,U.jsxs)(U.Fragment,{children:[`STATUS: PASSED`,(0,U.jsx)(g,{className:`w-3.5 h-3.5 text-emerald-600 inline`})]}):(0,U.jsxs)(U.Fragment,{children:[`STATUS: FAILED`,(0,U.jsx)(b,{className:`w-3.5 h-3.5 text-rose-600 inline`})]})}),(0,U.jsx)(`span`,{className:`font-sans text-[11px] text-slate-600 font-semibold`,children:j.is_correct?`Algorithm matches expected logic and patterns.`:`Bugs or edge-case failures detected.`})]})]}),(0,U.jsx)(`span`,{className:`font-arcade text-[9px] px-2 py-1 border-2 border-ink-black uppercase font-bold shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] ${j.is_correct?`bg-emerald-100 text-emerald-800`:`bg-rose-100 text-rose-800`}`,children:j.is_correct?`CORRECT`:`INCORRECT`})]}),(0,U.jsxs)(`div`,{className:`grid grid-cols-2 gap-3`,children:[(0,U.jsxs)(`div`,{className:`p-2.5 bg-white border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)]`,children:[(0,U.jsx)(`span`,{className:`font-arcade text-[8px] text-trash-gray block uppercase font-bold`,children:`Time Complexity`}),(0,U.jsxs)(`div`,{className:`flex items-baseline gap-2 mt-1`,children:[(0,U.jsx)(`span`,{className:`font-code-mono text-xs font-bold text-ink-black`,children:j.detected_complexity?.time||`N/A`}),(0,U.jsxs)(`span`,{className:`text-[10px] font-sans text-slate-500 font-semibold`,children:[`(Target: `,N||`O(N)`,`)`]})]})]}),(0,U.jsxs)(`div`,{className:`p-2.5 bg-white border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)]`,children:[(0,U.jsx)(`span`,{className:`font-arcade text-[8px] text-trash-gray block uppercase font-bold`,children:`Space Complexity`}),(0,U.jsxs)(`div`,{className:`flex items-baseline gap-2 mt-1`,children:[(0,U.jsx)(`span`,{className:`font-code-mono text-xs font-bold text-ink-black`,children:j.detected_complexity?.space||`N/A`}),(0,U.jsxs)(`span`,{className:`text-[10px] font-sans text-slate-500 font-semibold`,children:[`(Target: `,P||`O(1)`,`)`]})]})]})]}),j.bugs&&j.bugs.length>0&&(0,U.jsxs)(`div`,{className:`p-3 bg-white border-2 border-ink-black space-y-1.5 shadow-[2px_2px_0px_0px_rgba(30,41,59,1)]`,children:[(0,U.jsxs)(`span`,{className:`font-arcade text-[8px] text-rose-600 uppercase font-bold block flex items-center gap-1`,children:[(0,U.jsx)(m,{className:`w-3 h-3 text-rose-500`}),`TRACES & EDGE CASE ISSUES:`]}),(0,U.jsx)(`ul`,{className:`list-disc list-inside text-xs text-slate-800 space-y-1 font-semibold pl-1`,children:j.bugs.map((e,t)=>(0,U.jsx)(`li`,{className:`leading-relaxed select-text`,children:e},t))})]}),j.key_suggestion&&(0,U.jsxs)(`div`,{className:`p-3 bg-amber-50 border-2 border-ink-black space-y-1 shadow-[2px_2px_0px_0px_rgba(30,41,59,1)]`,children:[(0,U.jsxs)(`span`,{className:`font-arcade text-[8px] text-amber-700 uppercase font-bold block flex items-center gap-1`,children:[(0,U.jsx)(D,{className:`w-3 h-3 text-amber-500`}),`TIP:`]}),(0,U.jsx)(`p`,{className:`text-xs text-slate-800 font-medium leading-relaxed m-0 select-text`,children:j.key_suggestion})]}),(0,U.jsxs)(`div`,{className:`p-2.5 bg-white border-2 border-dashed border-ink-black flex items-center justify-between`,children:[(0,U.jsxs)(`span`,{className:`text-xs font-bold text-ink-black flex items-center gap-1.5`,children:[(0,U.jsx)(f,{className:`w-4 h-4 text-primary`}),`Recommendation:`]}),(0,U.jsx)(`span`,{className:`font-arcade text-[9px] font-bold text-purple-700`,children:j.is_correct?`Rate your recall below.`:`Review issues and rate recall below.`})]})]})]})]})},Ce=({gradeError:e,onDismissGradeError:t,submitting:n,submittingRating:r,onGrade:i})=>(0,U.jsx)(`div`,{className:`shrink-0 bg-[#f8f5eb] border-t-[3px] border-ink-black p-2 sm:p-3 flex flex-col items-stretch gap-1.5 sm:gap-2 shadow-[0_-3px_0_0_rgba(30,41,59,0.08)]`,children:(0,U.jsxs)(`div`,{className:`w-full flex flex-col`,children:[e&&(0,U.jsxs)(`div`,{className:`p-2.5 mb-2 bg-red-100 border-2 border-red-500 text-red-800 text-xs font-semibold shadow-[2px_2px_0px_0px_#1E293B] flex items-center justify-between`,children:[(0,U.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,U.jsx)(m,{className:`w-4 h-4 text-red-600 shrink-0`}),e]}),(0,U.jsx)(`button`,{onClick:t,className:`text-red-900 font-bold hover:underline cursor-pointer ml-2 text-xs`,children:`Dismiss`})]}),(0,U.jsxs)(`div`,{className:`flex gap-1.5 sm:gap-2.5 w-full`,children:[(0,U.jsx)(`button`,{onClick:()=>i(1),disabled:n,className:`flex-1 min-w-0 bg-[#dc2626] hover:bg-[#b91c1c] border-2 sm:border-[3px] border-ink-black py-2 sm:py-2.5 px-1 sm:px-2 arcade-btn cursor-pointer disabled:opacity-60 text-white flex flex-col items-center justify-center font-bold transition-all select-none`,title:`Press 1 on keyboard`,children:r===1?(0,U.jsx)(`div`,{className:`flex items-center gap-1.5 font-arcade text-[10px]`,children:(0,U.jsx)(s,{className:`w-3.5 h-3.5 animate-spin`})}):(0,U.jsxs)(`div`,{className:`flex items-center gap-1 font-headline-md text-[10px] min-[400px]:text-xs sm:text-sm font-extrabold tracking-wide uppercase truncate`,children:[(0,U.jsx)(`span`,{className:`font-arcade text-[8px] sm:text-[9px] px-1 py-0.5 bg-black/20 rounded shrink-0`,children:`1`}),(0,U.jsx)(`span`,{className:`truncate`,children:`Again`})]})}),(0,U.jsx)(`button`,{onClick:()=>i(2),disabled:n,className:`flex-1 min-w-0 bg-[#ff9933] hover:bg-[#ff8000] border-2 sm:border-[3px] border-ink-black py-2 sm:py-2.5 px-1 sm:px-2 arcade-btn cursor-pointer disabled:opacity-60 text-ink-black flex flex-col items-center justify-center font-bold transition-all select-none`,title:`Press 2 on keyboard`,children:r===2?(0,U.jsx)(`div`,{className:`flex items-center gap-1.5 font-arcade text-[10px]`,children:(0,U.jsx)(s,{className:`w-3.5 h-3.5 animate-spin text-ink-black`})}):(0,U.jsxs)(`div`,{className:`flex items-center gap-1 font-headline-md text-[10px] min-[400px]:text-xs sm:text-sm font-extrabold tracking-wide uppercase truncate`,children:[(0,U.jsx)(`span`,{className:`font-arcade text-[8px] sm:text-[9px] px-1 py-0.5 bg-black/10 rounded shrink-0`,children:`2`}),(0,U.jsx)(`span`,{className:`truncate`,children:`Hard`})]})}),(0,U.jsx)(`button`,{onClick:()=>i(3),disabled:n,className:`flex-1 min-w-0 bg-[#4ade80] hover:bg-[#22c55e] border-2 sm:border-[3px] border-ink-black py-2 sm:py-2.5 px-1 sm:px-2 arcade-btn cursor-pointer disabled:opacity-60 text-ink-black flex flex-col items-center justify-center font-bold transition-all select-none`,title:`Press 3 on keyboard`,children:r===3?(0,U.jsx)(`div`,{className:`flex items-center gap-1.5 font-arcade text-[10px]`,children:(0,U.jsx)(s,{className:`w-3.5 h-3.5 animate-spin text-ink-black`})}):(0,U.jsxs)(`div`,{className:`flex items-center gap-1 font-headline-md text-[10px] min-[400px]:text-xs sm:text-sm font-extrabold tracking-wide uppercase truncate`,children:[(0,U.jsx)(`span`,{className:`font-arcade text-[8px] sm:text-[9px] px-1 py-0.5 bg-black/10 rounded shrink-0`,children:`3`}),(0,U.jsx)(`span`,{className:`truncate`,children:`Good`})]})}),(0,U.jsx)(`button`,{onClick:()=>i(4),disabled:n,className:`flex-1 min-w-0 bg-[#60a5fa] hover:bg-[#3b82f6] border-2 sm:border-[3px] border-ink-black py-2 sm:py-2.5 px-1 sm:px-2 arcade-btn cursor-pointer disabled:opacity-60 text-ink-black flex flex-col items-center justify-center font-bold transition-all select-none`,title:`Press 4 on keyboard`,children:r===4?(0,U.jsx)(`div`,{className:`flex items-center gap-1.5 font-arcade text-[10px]`,children:(0,U.jsx)(s,{className:`w-3.5 h-3.5 animate-spin text-ink-black`})}):(0,U.jsxs)(`div`,{className:`flex items-center gap-1 font-headline-md text-[10px] min-[400px]:text-xs sm:text-sm font-extrabold tracking-wide uppercase truncate`,children:[(0,U.jsx)(`span`,{className:`font-arcade text-[8px] sm:text-[9px] px-1 py-0.5 bg-black/10 rounded shrink-0`,children:`4`}),(0,U.jsx)(`span`,{className:`truncate`,children:`Easy`})]})})]})]})}),we=({nextMilestone:e,activatingMilestone:t,onActivateNextMilestone:r,onOpenCardManager:i,onOpenJourney:a,onOpenCreateProblem:o,onOpenWindow:c,overrideProblemId:l,onClearOverride:d})=>(0,U.jsx)(`div`,{className:`w-full h-full flex items-center justify-center bg-[#fdf8e1] p-6 overflow-y-auto custom-scrollbar`,children:(0,U.jsxs)(`div`,{className:`w-full max-w-lg bg-paper-white border-[4px] border-ink-black gadget-shadow p-6 sm:p-8 relative overflow-hidden text-center space-y-6`,children:[(0,U.jsx)(`div`,{className:`absolute top-0 left-0 right-0 h-3 bg-gradient-to-r from-grass-green via-amber-300 to-highlight-pink`}),(0,U.jsxs)(`div`,{className:`relative inline-block mt-2`,children:[(0,U.jsx)(`div`,{className:`w-20 h-20 bg-amber-300 border-[3px] border-ink-black rounded-2xl flex items-center justify-center mx-auto gadget-shadow rotate-[-3deg] hover:rotate-0 transition-transform`,children:(0,U.jsx)(E,{className:`w-10 h-10 text-ink-black stroke-[2.5]`})}),(0,U.jsx)(`div`,{className:`absolute -bottom-2 -right-2 bg-grass-green border-2 border-ink-black px-2 py-0.5 font-arcade text-[8px] text-ink-black font-bold uppercase shadow-[2px_2px_0px_0px_rgba(30,41,59,1)]`,children:`100% DONE`})]}),(0,U.jsxs)(`div`,{className:`space-y-2`,children:[(0,U.jsxs)(`span`,{className:`inline-flex items-center gap-1 px-2.5 py-1 bg-emerald-100 border-2 border-ink-black text-emerald-800 font-arcade text-[9px] font-bold`,children:[(0,U.jsx)(u,{className:`w-3 h-3 stroke-[3]`}),` ALL CARDS COMPLETED FOR TODAY`]}),(0,U.jsx)(`h2`,{className:`text-2xl sm:text-3xl font-extrabold text-ink-black font-headline-md tracking-tight`,children:`You're all caught up for today. Keep it up.`}),(0,U.jsx)(`p`,{className:`text-xs sm:text-sm font-sans text-trash-gray max-w-md mx-auto leading-relaxed font-semibold`,children:`All reviews for today are finished. Next reviews are scheduled for tomorrow.`})]}),e&&(0,U.jsxs)(`div`,{className:`p-4 sm:p-5 bg-gradient-to-br from-amber-50 to-orange-50 border-[3px] border-ink-black gadget-shadow text-left space-y-3`,children:[(0,U.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,U.jsxs)(`span`,{className:`font-arcade text-[9px] font-bold text-amber-800 uppercase tracking-wider flex items-center gap-1.5`,children:[(0,U.jsx)(C,{className:`w-3.5 h-3.5 text-amber-600`}),`NEXT UNEXPLORED MILESTONE`]}),(0,U.jsxs)(`span`,{className:`font-mono text-[10px] font-bold px-2 py-0.5 rounded bg-amber-900/10 text-amber-900 border border-amber-900/20`,children:[`LC #`,e.problem_number]})]}),(0,U.jsxs)(`div`,{className:`flex flex-col sm:flex-row sm:items-center justify-between gap-3`,children:[(0,U.jsxs)(`div`,{className:`min-w-0`,children:[(0,U.jsx)(`h3`,{className:`font-headline-md text-base sm:text-lg font-bold text-ink-black truncate`,children:e.name}),(0,U.jsxs)(`div`,{className:`flex items-center gap-2 mt-1 flex-wrap`,children:[(0,U.jsx)(`span`,{className:`px-2 py-0.5 rounded font-arcade text-[8px] font-bold uppercase text-white ${e.difficulty===`Easy`?`bg-emerald-600`:e.difficulty===`Medium`?`bg-amber-600`:`bg-rose-600`}`,children:e.difficulty}),(0,U.jsx)(`span`,{className:`px-2 py-0.5 rounded font-arcade text-[8px] bg-purple-100 text-purple-800 border border-purple-300 font-bold`,children:e.pattern}),(0,U.jsxs)(`span`,{className:`text-[11px] font-code-mono text-slate-600`,children:[`T: `,e.time_complexity,` | S: `,e.space_complexity]})]})]}),(0,U.jsx)(`button`,{onClick:r,disabled:t,className:`px-4 py-2.5 bg-grass-green hover:bg-emerald-400 text-ink-black font-arcade text-[9px] font-bold border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none transition-all cursor-pointer shrink-0 flex items-center justify-center gap-1.5 disabled:opacity-50`,children:t?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(s,{className:`w-3.5 h-3.5 animate-spin`}),(0,U.jsx)(`span`,{children:`ACTIVATING...`})]}):(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(D,{className:`w-3.5 h-3.5 text-amber-700`}),(0,U.jsx)(`span`,{children:`ACTIVATE & REVIEW NOW`})]})})]})]}),(0,U.jsxs)(`div`,{className:`p-4 sm:p-5 bg-gradient-to-r from-sky-100 via-sky-200 to-indigo-100 border-[3px] border-ink-black gadget-shadow text-left flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3`,children:[(0,U.jsxs)(`div`,{className:`space-y-1`,children:[(0,U.jsxs)(`span`,{className:`font-arcade text-[9px] font-bold text-sky-900 uppercase flex items-center gap-1.5`,children:[(0,U.jsx)(p,{className:`w-3.5 h-3.5 text-sky-700`}),`DECK BROWSER & CARD MANAGER`]}),(0,U.jsx)(`h3`,{className:`font-headline-md text-base sm:text-lg font-bold text-ink-black`,children:`Want to Manage or Reschedule Cards?`}),(0,U.jsx)(`p`,{className:`font-sans text-xs text-trash-gray font-semibold max-w-md`,children:`Browse your full 150-card curriculum, reschedule intervals, or enroll new topics in the Anki-style Card Manager.`})]}),(0,U.jsxs)(`button`,{onClick:()=>{i?i():c?.(`cardManager`)},className:`px-4 py-2.5 bg-sky-400 hover:bg-sky-300 text-ink-black font-arcade text-[9px] font-bold border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none transition-all cursor-pointer shrink-0 flex items-center gap-1.5`,children:[(0,U.jsx)(p,{className:`w-3.5 h-3.5 text-sky-950`}),(0,U.jsx)(`span`,{children:`OPEN CARD MANAGER`})]})]}),(0,U.jsxs)(`div`,{className:`border-t-[3px] border-dashed border-ink-black pt-5 space-y-3`,children:[(0,U.jsx)(`div`,{className:`text-[9px] font-arcade text-trash-gray uppercase font-bold text-left`,children:`CONTINUE PRACTICING:`}),(0,U.jsxs)(`div`,{className:`grid grid-cols-2 sm:grid-cols-4 gap-2.5`,children:[(0,U.jsxs)(`button`,{onClick:a,className:`p-3 bg-amber-100 hover:bg-amber-200 border-[3px] border-ink-black text-left flex flex-col justify-between gadget-shadow active:translate-y-1 active:shadow-none transition-all cursor-pointer`,children:[(0,U.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,U.jsx)(C,{className:`w-4 h-4 text-amber-600`}),(0,U.jsx)(O,{className:`w-3 h-3 text-ink-black`})]}),(0,U.jsxs)(`div`,{className:`mt-2`,children:[(0,U.jsx)(`div`,{className:`font-arcade text-[8px] font-bold text-ink-black uppercase`,children:`Journey Trail`}),(0,U.jsx)(`div`,{className:`font-sans text-[10px] text-trash-gray font-semibold`,children:`150 Curated nodes`})]})]}),(0,U.jsxs)(`button`,{onClick:o,className:`p-3 bg-purple-100 hover:bg-purple-200 border-[3px] border-ink-black text-left flex flex-col justify-between gadget-shadow active:translate-y-1 active:shadow-none transition-all cursor-pointer`,children:[(0,U.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,U.jsx)(y,{className:`w-4 h-4 text-purple-700`}),(0,U.jsx)(O,{className:`w-3 h-3 text-ink-black`})]}),(0,U.jsxs)(`div`,{className:`mt-2`,children:[(0,U.jsx)(`div`,{className:`font-arcade text-[8px] font-bold text-ink-black uppercase`,children:`Add Problem`}),(0,U.jsx)(`div`,{className:`font-sans text-[10px] text-trash-gray font-semibold`,children:`New LeetCode entry`})]})]}),(0,U.jsxs)(`button`,{onClick:()=>c?.(`companion`),className:`p-3 bg-yellow-100 hover:bg-yellow-200 border-[3px] border-ink-black text-left flex flex-col justify-between gadget-shadow active:translate-y-1 active:shadow-none transition-all cursor-pointer`,children:[(0,U.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,U.jsx)(`span`,{className:`material-symbols-outlined text-amber-600 text-lg`,children:`fireplace`}),(0,U.jsx)(O,{className:`w-3 h-3 text-ink-black`})]}),(0,U.jsxs)(`div`,{className:`mt-2`,children:[(0,U.jsx)(`div`,{className:`font-arcade text-[8px] font-bold text-ink-black uppercase`,children:`Princess Camp`}),(0,U.jsx)(`div`,{className:`font-sans text-[10px] text-trash-gray font-semibold`,children:`Rest with Aurelia`})]})]}),(0,U.jsxs)(`button`,{onClick:()=>{i?i():c?.(`cardManager`)},className:`p-3 bg-cyan-100 hover:bg-cyan-200 border-[3px] border-ink-black text-left flex flex-col justify-between gadget-shadow active:translate-y-1 active:shadow-none transition-all cursor-pointer`,children:[(0,U.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,U.jsx)(x,{className:`w-4 h-4 text-cyan-700`}),(0,U.jsx)(O,{className:`w-3 h-3 text-ink-black`})]}),(0,U.jsxs)(`div`,{className:`mt-2`,children:[(0,U.jsx)(`div`,{className:`font-arcade text-[8px] font-bold text-ink-black uppercase`,children:`Card Manager`}),(0,U.jsx)(`div`,{className:`font-sans text-[10px] text-trash-gray font-semibold`,children:`Anki Deck Browser`})]})]})]})]}),l&&d&&(0,U.jsxs)(`button`,{onClick:d,className:`mt-3 bg-white hover:bg-slate-100 border-[3px] border-ink-black text-ink-black font-bold px-4 py-2 text-xs uppercase tracking-wide shadow-[3px_3px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none transition-all cursor-pointer inline-flex items-center gap-2`,children:[(0,U.jsx)(n,{className:`w-3.5 h-3.5`}),` Return to Scheduled Queue`]})]})}),Te=e({default:()=>De}),Ee=(0,H.lazy)(()=>I(()=>import(`./ProblemSpecPanel-C8iV6oe0.js`).then(e=>({default:e.ProblemSpecPanel})),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9])));function De({overrideProblemId:e,onClearOverride:t,onOpenWindow:r,onOpenJourney:i,onOpenCreateProblem:a,onOpenEditProblem:o,onOpenCardManager:c,refreshTrigger:l}){let[u,f]=(0,H.useState)(null),p=u!==null&&u<780,[h,g]=(0,H.useState)(`spec`),[_,y]=(0,H.useState)(`spec`),[ee,b]=(0,H.useState)(null),x=(0,H.useCallback)(e=>{e&&(f(e.clientWidth),new ResizeObserver(e=>{for(let t of e)f(t.contentRect.width)}).observe(e))},[]),[C,w]=(0,H.useState)(()=>localStorage.getItem(`isAutocompleteEnabled`)!==`false`),{reviews:E,setReviews:D,loading:te,queueError:O,submitting:k,submittingRating:A,gradeError:j,setGradeError:M,code:N,setCode:F,nextMilestone:I,activatingMilestone:L,fetchQueue:ie,handleGrade:R,handleSelectCard:z,handleActivateNextMilestone:B,handleResetStarterCode:V}=fe({overrideProblemId:e,refreshTrigger:l,onClearOverride:t}),{sandboxRunning:ae,sandboxResults:oe,sandboxError:se,savingReference:ce,savedRefSuccess:de,saveRefError:W,handleRunSandbox:ge,handleSaveReference:_e,resetSandbox:G}=pe(),{aiLoading:ve,aiResult:ye,aiError:be,explainLoading:K,explanationText:xe,explainError:Te,aiSolutionLoading:De,aiSolutionError:Oe,handleAiEvaluation:ke,handleExplainCode:Ae,handleFetchAiSolution:je,resetAiState:q}=me(),[Me,Ne]=(0,H.useState)(!1),[Pe,Fe]=(0,H.useState)(null),[Ie,J]=(0,H.useState)(null),Le=(0,H.useCallback)(async()=>{if(E.length===0)return;let e=E[0]?.problems||{},t=N.trim()||e.reference_code||``;if(!t){J(`Please write or save code before pushing to GitHub.`),setTimeout(()=>J(null),4e3);return}let n=re();if(!n.token){r&&r(`github`);return}Ne(!0),J(null),Fe(null);try{let r=await ne({token:n.token,repo:n.repoName,branch:n.branch,problem_number:e.problem_number,problem_name:e.name||`Algorithm Problem`,pattern:e.pattern||`Algorithms`,difficulty:e.difficulty||`Medium`,optimal_time:e.optimal_time||`O(N)`,optimal_space:e.optimal_space||`O(1)`,description:e.description||``,code:t});Fe(r.html_url),setTimeout(()=>Fe(null),8e3)}catch(e){J(e.message||`Failed to push solution to GitHub.`),setTimeout(()=>J(null),5e3)}finally{Ne(!1)}},[E,N,r]),Re=E[0]?.id||E[0]?.problem_id,ze=(0,H.useRef)(void 0);(0,H.useEffect)(()=>{Re&&ze.current!==Re&&(ze.current=Re,q(),G())},[Re,q,G]);let Y=(0,H.useCallback)(e=>{q(),G(),R(e)},[R,q,G]),Be=(0,H.useCallback)(e=>{q(),G(),z(e)},[z,q,G]);(0,H.useEffect)(()=>{let e=e=>{let t=e.target;t?.closest(`.cm-editor`)||t?.tagName===`INPUT`||t?.tagName===`TEXTAREA`||t?.isContentEditable||E.length===0||k||(e.key===`1`?(e.preventDefault(),Y(1)):e.key===`2`?(e.preventDefault(),Y(2)):e.key===`3`?(e.preventDefault(),Y(3)):e.key===`4`&&(e.preventDefault(),Y(4)))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[Y,E.length,k]);let Ve=(e,t)=>{navigator.clipboard.writeText(e),b(t),setTimeout(()=>b(null),1800)},He=(0,H.useCallback)(()=>{i?i():r?.(`journey`)},[i,r]),Ue=(0,H.useCallback)(()=>{a?a():r?.(`createProblem`)},[a,r]),We=(0,H.useCallback)(e=>{D(t=>{if(t.length===0)return t;let n=[...t],r=n[0];return r&&r.problems&&(r.problems={...r.problems,solutions:e}),n})},[D]);if(te)return(0,U.jsx)(`div`,{className:`w-full h-full flex items-center justify-center bg-[#fdf8e1] text-ink-black`,children:(0,U.jsxs)(`div`,{className:`flex flex-col items-center gap-4 p-8 bg-paper-white border-[3px] border-ink-black gadget-shadow text-center max-w-xs`,children:[(0,U.jsx)(`div`,{className:`w-12 h-12 bg-amber-200 border-2 border-ink-black flex items-center justify-center animate-spin`,children:(0,U.jsx)(s,{className:`w-6 h-6 text-ink-black`})}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`h3`,{className:`font-arcade text-xs text-ink-black uppercase tracking-wider font-bold`,children:`LOADING QUEUE`}),(0,U.jsx)(`p`,{className:`font-sans text-[11px] text-trash-gray mt-1 font-semibold`,children:`Fetching scheduled FSRS review cards...`})]})]})});if(O&&E.length===0)return(0,U.jsx)(`div`,{className:`w-full h-full flex items-center justify-center bg-[#fdf8e1] p-6 overflow-y-auto custom-scrollbar`,children:(0,U.jsxs)(`div`,{className:`w-full max-w-md bg-paper-white border-[4px] border-ink-black gadget-shadow p-6 sm:p-8 relative overflow-hidden text-center space-y-6`,children:[(0,U.jsx)(`div`,{className:`absolute top-0 left-0 right-0 h-3 bg-gradient-to-r from-red-500 via-amber-400 to-red-500`}),(0,U.jsxs)(`div`,{className:`relative inline-block mt-2`,children:[(0,U.jsx)(`div`,{className:`w-20 h-20 bg-rose-200 border-[3px] border-ink-black rounded-2xl flex items-center justify-center mx-auto gadget-shadow rotate-[-2deg]`,children:(0,U.jsx)(S,{className:`w-10 h-10 text-rose-700 stroke-[2.5]`})}),(0,U.jsx)(`div`,{className:`absolute -bottom-2 -right-2 bg-rose-500 text-white border-2 border-ink-black px-2 py-0.5 font-arcade text-[8px] font-bold uppercase shadow-[2px_2px_0px_0px_rgba(30,41,59,1)]`,children:`OFFLINE`})]}),(0,U.jsxs)(`div`,{className:`space-y-2`,children:[(0,U.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 px-2.5 py-1 bg-rose-100 border-2 border-ink-black text-rose-800 font-arcade text-[9px] font-bold`,children:[(0,U.jsx)(m,{className:`w-3.5 h-3.5 stroke-[2.5] text-rose-600`}),` CONNECTION ERROR`]}),(0,U.jsx)(`h2`,{className:`text-2xl sm:text-3xl font-extrabold text-ink-black font-headline-md tracking-tight`,children:`Queue Unavailable`}),(0,U.jsx)(`p`,{className:`font-sans text-xs sm:text-sm text-trash-gray font-semibold leading-relaxed max-w-sm mx-auto`,children:`Unable to reach the server to fetch your scheduled review cards. Check your connection or retry below.`})]}),(0,U.jsxs)(`div`,{className:`pt-2 flex flex-col sm:flex-row gap-3 justify-center items-center`,children:[(0,U.jsxs)(`button`,{onClick:()=>void ie(!0),className:`w-full sm:w-auto px-6 py-2.5 bg-amber-300 hover:bg-amber-400 border-[3px] border-ink-black font-arcade text-xs font-bold text-ink-black gadget-shadow active:translate-x-0.5 active:translate-y-0.5 active:shadow-none transition-all flex items-center justify-center gap-2 cursor-pointer`,children:[(0,U.jsx)(n,{className:`w-4 h-4`}),(0,U.jsx)(`span`,{children:`RETRY CONNECTION`})]}),(i||r)&&(0,U.jsx)(`button`,{onClick:He,className:`w-full sm:w-auto px-5 py-2.5 bg-paper-white hover:bg-warm-sand-bg border-[3px] border-ink-black font-arcade text-xs font-bold text-ink-black gadget-shadow active:translate-x-0.5 active:translate-y-0.5 active:shadow-none transition-all flex items-center justify-center gap-2 cursor-pointer`,children:(0,U.jsx)(`span`,{children:`OPEN JOURNEY MAP`})})]})]})});if(E.length===0)return(0,U.jsx)(we,{nextMilestone:I,activatingMilestone:L,onActivateNextMilestone:B,onOpenCardManager:c||(()=>r?.(`cardManager`)),onOpenJourney:He,onOpenCreateProblem:Ue,onOpenWindow:r,overrideProblemId:e,onClearOverride:t});let X=E[0],Z=X?.problems,Ge=Z?.problem_number??(/^\d+$/.test(X?.problem_id||``)?parseInt(X.problem_id,10):void 0),Q=P(Ge,Z?.id||X?.problem_id,Z?.name),{cleanTitle:Ke,approachVariant:qe,pattern:Je}=ue(Z?.name,Q?.name,Z?.pattern,Q?.pattern),$={...Q,...Z,id:Z?.id||Q?.id||X?.problem_id,name:Ke,problem_number:Z?.problem_number??Q?.problem_number,pattern:Je,approach_variant:qe,difficulty:Z?.difficulty||Q?.difficulty||`Medium`,reference_code:Z?.reference_code||Q?.reference_solution||``,starter_code:Q?.starter_code||Z?.starter_code||``,description:Z?.description||Q?.description||``,optimal_time:Z?.optimal_time||Q?.time_complexity||`O(N)`,optimal_space:Z?.optimal_space||Q?.space_complexity||`O(1)`,examples:Z?.examples&&Z.examples.length>0?Z.examples:Q?.examples,constraints:Z?.constraints||Q?.constraints,how_to_solve:Z?.how_to_solve||``,solutions:Z?.solutions&&Z.solutions.length>0?Z.solutions:Q?.solutions},Ye=le({...Q,...$,examples:$.examples&&$.examples.length>0?$.examples:Q?.examples,constraints:$.constraints&&(Array.isArray($.constraints)?$.constraints.length>0:$.constraints)?$.constraints:Q?.constraints}),Xe=Q?.reference_solution||``,Ze=Z?.reference_code||``,Qe=Ze&&(!Xe||Ze.trim()!==Xe.trim())?Ze:``,$e=Qe||Xe||Ze||``;return(0,U.jsxs)(`div`,{ref:x,className:`w-full h-full bg-[#fdf8e1] flex flex-col overflow-hidden select-none`,children:[(0,U.jsx)(he,{problem:$,totalInQueue:E.length,reviews:E,overrideProblemId:e,onSelectCard:Be,onOpenCreateProblem:Ue,onOpenEditProblem:()=>{o?o($):r?.(`editProblem`)}}),(0,U.jsxs)(`div`,{className:`${p?`flex`:`hidden`} shrink-0 bg-amber-100 border-b-[3px] border-ink-black px-2.5 sm:px-3 py-1.5 gap-1.5 sm:gap-2 overflow-x-auto no-scrollbar`,children:[(0,U.jsxs)(`button`,{onClick:()=>{y(`spec`),g(`spec`)},className:`px-2.5 sm:px-3 py-1 text-[9px] font-arcade font-bold border-2 border-ink-black transition-all cursor-pointer flex items-center gap-1.5 whitespace-nowrap ${_===`spec`?`bg-paper-white translate-y-0.5 shadow-none text-ink-black`:`bg-white shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] text-trash-gray`}`,children:[(0,U.jsx)(T,{className:`w-3 h-3 shrink-0`}),(0,U.jsx)(`span`,{children:`SPEC`})]}),(0,U.jsxs)(`button`,{onClick:()=>y(`code`),className:`px-2.5 sm:px-3 py-1 text-[9px] font-arcade font-bold border-2 border-ink-black transition-all cursor-pointer flex items-center gap-1.5 whitespace-nowrap ${_===`code`?`bg-paper-white translate-y-0.5 shadow-none text-ink-black`:`bg-white shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] text-trash-gray`}`,children:[(0,U.jsx)(v,{className:`w-3 h-3 shrink-0`}),(0,U.jsx)(`span`,{children:`CODE STUDIO`})]}),(0,U.jsxs)(`button`,{onClick:()=>{y(`ref`),g(`ref`)},className:`px-2.5 sm:px-3 py-1 text-[9px] font-arcade font-bold border-2 border-ink-black transition-all cursor-pointer flex items-center gap-1.5 whitespace-nowrap ${_===`ref`?`bg-paper-white translate-y-0.5 shadow-none text-ink-black`:`bg-white shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] text-trash-gray`}`,children:[(0,U.jsx)(d,{className:`w-3 h-3 shrink-0`}),(0,U.jsx)(`span`,{children:`SOLUTION`})]})]}),(0,U.jsxs)(`div`,{className:`flex-1 flex ${p?`flex-col`:`flex-row`} overflow-hidden min-h-0`,children:[(0,U.jsx)(H.Suspense,{fallback:(0,U.jsx)(`div`,{className:`flex-1 flex flex-col items-center justify-center p-8 bg-paper-white ${p?`h-64`:`border-r-[4px] border-ink-black`} font-sans text-xs text-trash-gray select-none`,children:(0,U.jsxs)(`div`,{className:`flex items-center gap-2 font-arcade text-[10px] text-ink-black`,children:[(0,U.jsx)(s,{className:`w-4 h-4 animate-spin text-[#0ea5e9]`}),(0,U.jsx)(`span`,{children:`Loading Problem Spec...`})]})}),children:(0,U.jsx)(Ee,{leftTab:h,onSelectLeftTab:e=>{g(e),e===`ref`?y(`ref`):e===`spec`&&y(`spec`)},mobileView:_,isNarrow:p,problem:$,parsed:Ye,userSolution:Qe,officialSolution:Xe,effectiveReferenceCode:$e,copiedSnippet:ee,onCopyText:Ve,saveRefError:W,aiSolutionLoading:De,aiSolutionError:Oe,onFetchAiSolution:()=>je(X,e=>{D(t=>t.map((t,n)=>n===0?{...t,problems:{...$||{},...t.problems||{},reference_code:e}}:t))}),explainLoading:K,explainError:Te,explanationText:xe,onExplainCode:(e,t,n,r)=>Ae(X,e,t,n,r),activeReview:X,onUpdateSolutions:We,onEditProblem:()=>{o?o($):r?.(`editProblem`)}})}),(0,U.jsx)(Se,{mobileView:_,isNarrow:p,isAutocompleteEnabled:C,onToggleAutocomplete:e=>{w(e),localStorage.setItem(`isAutocompleteEnabled`,String(e))},onResetStarterCode:V,code:N,onChangeCode:F,sandboxRunning:ae,sandboxError:se,sandboxResults:oe,onRunSandbox:()=>ge(X,N),savingReference:ce,savedRefSuccess:de,saveRefError:W,onSaveReference:()=>_e(X,N,(e,t)=>{D(n=>n.map((n,r)=>r===0?{...n,problem_id:t||n.problem_id,problems:{...$||{},...n.problems||{},id:t||n.problems?.id||n.problem_id,reference_code:e}}:n))}),aiLoading:ve,aiError:be,aiResult:ye,onAiEvaluation:()=>ke(X,N),optimalTime:$.optimal_time||`O(N)`,optimalSpace:$.optimal_space||`O(1)`,onPushToGitHub:Le,pushingToGitHub:Me,githubPushedUrl:Pe,githubPushError:Ie})]}),(0,U.jsx)(Ce,{gradeError:j,onDismissGradeError:()=>M(null),submitting:k,submittingRating:A,onGrade:Y})]})}export{De as default,de as n,Te as t};12345const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ProblemSpecPanel-BRW8UyO6.js","assets/rolldown-runtime-hePW80VL.js","assets/vendor-react-hnaVBnLv.js","assets/vendor-codemirror-By0wlJeM.js","assets/index-DVWZ15xt.js","assets/firebaseClient-DZobvwSx.js","assets/vendor-firebase-DSIO3PIf.js","assets/vendor-ui-ZXcm-2wU.js","assets/index-BsU9BpJx.css","assets/MarkdownRenderer-D8UdFpnD.js"])))=>i.map(i=>d[i]);import{n as e,r as t}from"./rolldown-runtime-hePW80VL.js";import{A as n,Bt as r,Et as i,F as a,Ht as o,M as s,O as c,P as l,St as u,Tt as d,X as f,a as p,d as m,et as h,ht as g,it as _,lt as v,mt as y,p as b,pt as x,q as S,s as C,st as w,t as T,tt as E,u as D,x as O,xt as ee,yt as k}from"./vendor-react-hnaVBnLv.js";import{r as A,s as j}from"./firebaseClient-DZobvwSx.js";import{b as M,c as N,n as P,o as te,r as F,s as I,t as L}from"./index-DVWZ15xt.js";import{o as ne,r as re}from"./githubSyncService-x0Mm_uEl.js";import{t as ie}from"./confetti.module-Uxh4CK4s.js";import"./MarkdownRenderer-D8UdFpnD.js";import"./PrincessChamber-abJShfI5.js";import{A as R,C as z,I as B,S as V,p as ae,t as oe,x as se,y as ce}from"./vendor-codemirror-By0wlJeM.js";var H=t(o(),1),U=r();function le(e){if(!e)return{description:``,examples:[],constraints:[]};let t=e.description||``,n=[],r=[];if(Array.isArray(e.examples)&&e.examples.length>0&&(n=e.examples.map(e=>typeof e==`string`?{input:e,output:``}:{input:e?.input||``,output:e?.output||``,explanation:e?.explanation||``})),Array.isArray(e.constraints)&&e.constraints.length>0?r=e.constraints.map(e=>String(e).replace(/^[\u2022\-*]\s*/,``).trim()).filter(Boolean):typeof e.constraints==`string`&&e.constraints.trim()&&(r=e.constraints.split(``).map(e=>e.replace(/^[\u2022\-*]\s*/,``).trim()).filter(Boolean)),n.length===0||r.length===0){let e=t.search(/\bExample\s*\d*:/i),i=t.search(/\bConstraints\s*:/i),a=-1;if(e!==-1&&i!==-1?a=Math.min(e,i):e===-1?i!==-1&&(a=i):a=e,a!==-1){let e=t.substring(0,a).trim(),i=t.substring(a),o=i,s=``,c=i.search(/\bConstraints\s*:/i);if(c!==-1&&(o=i.substring(0,c).trim(),s=i.substring(c).replace(/\bConstraints\s*:/i,``).trim()),n.length===0&&o){let e=/\bExample\s*(\d*)\s*:/gi,t=[],r;for(;(r=e.exec(o))!==null;)t.push({index:r.index,text:r[0]});for(let e=0;e<t.length;e++){let r=t[e].index+t[e].text.length,i=e+1<t.length?t[e+1].index:o.length,a=o.substring(r,i).trim(),s=a.match(/Input:\s*([\s\S]+?)(?=(?:Output:|Explanation:|$))/i),c=a.match(/Output:\s*([\s\S]+?)(?=(?:Explanation:|$))/i),l=a.match(/Explanation:\s*([\s\S]+)/i),u=s?s[1].trim():``,d=c?c[1].trim():``,f=l?l[1].trim():``;u||d?n.push({input:u,output:d,explanation:f}):a&&n.push({input:a,output:``,explanation:``})}}r.length===0&&s&&(r=s.split(``).map(e=>e.replace(/^[\u2022\-*]\s*/,``).trim()).filter(Boolean)),(n.length>0||r.length>0)&&(t=e)}}return{description:t,examples:n,constraints:r}}function ue(e,t,n,r){let i=e=>!e||/^Method\s*\d*$/i.test(e.trim())||e.trim().toLowerCase()===`standard`,a=(e||t||`Algorithm Problem`).trim(),o=null;if(t&&a.toLowerCase().startsWith(t.toLowerCase())){let e=a.slice(t.length).trim();if(a=t,e){let t=e.match(/^[-\s]*Method\s*(\d+)\s*\((.+)\)$/i);if(t){let e=parseInt(t[1],10),n=t[2].trim();i(n)?e>1&&(o=`Method ${e}`):o=n}else{let t=e.match(/^[-\s]*Method\s*(\d+)/i);if(t){let e=parseInt(t[1],10);e>1&&(o=`Method ${e}`)}else{let t=e.match(/^[-\s]*\((.+)\)$/);if(t){let e=t[1].trim();i(e)||(o=e)}else{let t=e.match(/^[-\s]+([^-]+)$/);t&&!i(t[1])&&(o=t[1].trim())}}}}}else{let e=a.match(/^(.*?)\s*-\s*Method\s*(\d+)\s*\((.+)\)$/i);if(e){a=e[1].trim();let t=parseInt(e[2],10),n=e[3].trim();i(n)?t>1&&(o=`Method ${t}`):o=n}else{let e=a.match(/^(.*?)\s*-\s*Method\s*(\d+)$/i);if(e){a=e[1].trim();let t=parseInt(e[2],10);t>1&&(o=`Method ${t}`)}else{let e=a.match(/^(.*?)\s*\(\s*Method\s*(\d+)\s*\)$/i);if(e){a=e[1].trim();let t=parseInt(e[2],10);t>1&&(o=`Method ${t}`)}}}}let s=`General Algorithm`;return i(n)?i(r)?o&&!i(o)&&(s=o):s=r.trim():s=n.trim(),{cleanTitle:a,approachVariant:o,pattern:s}}function de(e,t,n){if(!e)return[];if(Array.isArray(e.solutions)&&e.solutions.length>0)return e.solutions;let r=[],i=t||e.reference_code||``,a=e.pattern||`General Algorithm`,o=e.optimal_time||`O(N)`,s=e.optimal_space||`O(1)`;return(i||a)&&r.push({id:`sol-1`,name:e.approach_variant||`Optimal Solution`,pattern:a,time_complexity:o,space_complexity:s,code:i,explanation:e.how_to_solve||``,is_optimal:!0}),n&&n.trim()&&n.trim()!==i.trim()&&r.push({id:`sol-2`,name:`Personal Solution`,pattern:a,time_complexity:o,space_complexity:s,code:n,is_optimal:!1}),r}function W(e){if(e&&e!==`sandbox-user-id`)return e;try{let e=A();if(e?.user?.id&&e.user.id!==`sandbox-user-id`)return e.user.id}catch{}return`guest`}function fe({overrideProblemId:e,refreshTrigger:t,onClearOverride:n}){let[r,i]=(0,H.useState)([]),[a,o]=(0,H.useState)(!0),[s,c]=(0,H.useState)(null),[l,u]=(0,H.useState)(!1),[d,f]=(0,H.useState)(null),[p,m]=(0,H.useState)(null),[h,g]=(0,H.useState)(``),[_,v]=(0,H.useState)(null),[y,b]=(0,H.useState)(!1),[x,S]=(0,H.useState)(()=>{try{return A()?.user?.id}catch{return}}),C=(0,H.useRef)(!1),w=(0,H.useRef)(n),T=(0,H.useRef)(!1);(0,H.useEffect)(()=>{w.current=n});let E=(0,H.useCallback)(async(t=!0)=>{t?(o(!0),m(null),c(null),g(``),C.current=!1):m(null);let n=W(x);try{if(typeof navigator<`u`&&!navigator.onLine)throw Error(`Network connection offline.`);let{data:{session:r}}=await j.auth.getSession(),a=r?r.access_token:`sandbox`;r?.user?.id&&(S(r.user.id),n=W(r.user.id));let o={Authorization:`Bearer ${a}`},s=new AbortController,l=setTimeout(()=>s.abort(),4e3),u;try{u=await fetch(`/api/reviews/due`,{headers:o,signal:s.signal})}finally{clearTimeout(l)}if(!u.ok)throw Error(`Failed to load review queue: HTTP ${u.status}`);let d=await u.json();if(Array.isArray(d)||(d=[]),e){let t=String(e).trim().toLowerCase(),n=d.findIndex(e=>{let n=e.problems;return!!(e.problem_id&&String(e.problem_id).trim().toLowerCase()===t||n?.id&&String(n.id).trim().toLowerCase()===t||n?.problem_number!==void 0&&n?.problem_number!==null&&String(n.problem_number)===t||n?.name&&n.name.trim().toLowerCase()===t)});if(n>0){let[e]=d.splice(n,1);d.unshift(e)}else if(n===-1){let t=null,n=await fetch(`/api/reviews/problems/id/${e}`,{headers:o});if(n.ok){let e=await n.json();Array.isArray(e)&&e.length>0&&(t=e[0])}if(!t){let n=/^\d+$/.test(e),r=F(n?parseInt(e,10):void 0,e);if(r)try{let e=await N(r);if(e?.problem_id){let n=await fetch(`/api/reviews/problems/id/${e.problem_id}`,{headers:o});if(n.ok){let e=await n.json();Array.isArray(e)&&e.length>0&&(t=e[0])}}}catch(e){console.error(`Failed to auto-activate problem for override review:`,e)}}t&&d.unshift(t)}}i(d),c(null);try{localStorage.setItem(`algospaced_review_queue_${n}`,JSON.stringify(d))}catch{}if(d&&d.length>0){if(t){let e=d[0],t=e.problems,n=t?.problem_number??(/^\d+$/.test(e?.problem_id||``)?parseInt(e.problem_id,10):void 0),r=F(n,t?.id||e?.problem_id,t?.name)?.starter_code||t?.starter_code||``;g(r)}}else try{let e=await fetch(`/api/journey-progress`,{headers:o});if(e.ok){let t=await e.json();v(I(new Set(t))??null)}else v(I(new Set)??null)}catch{v(I(new Set)??null)}}catch(e){console.error(`Error fetching review queue:`,e);let r=e instanceof Error?e.message:`Network error loading review queue.`,a=!1;try{let e=localStorage.getItem(`algospaced_review_queue_${n}`);if(e){let n=JSON.parse(e);if(Array.isArray(n)&&n.length>0&&(i(n),a=!0,c(null),t)){let e=n[0],t=e.problems,r=t?.problem_number??(/^\d+$/.test(e?.problem_id||``)?parseInt(e.problem_id,10):void 0),i=F(r,t?.id||e?.problem_id,t?.name)?.starter_code||t?.starter_code||``;g(i)}}}catch(e){console.warn(`Failed to parse cached review items:`,e)}a||c(r)}finally{o(!1)}},[e,x]);(0,H.useEffect)(()=>{if(T.current){T.current=!1;return}let e=!1,t=setTimeout(()=>{e||E(!0)},0);return()=>{e=!0,clearTimeout(t)}},[E,t]),(0,H.useEffect)(()=>{if(!a&&!s&&r.length===0&&!e&&!C.current){C.current=!0;try{ie({particleCount:90,spread:70,origin:{y:.6}})}catch{}}},[a,s,r.length,e]);let D=(0,H.useCallback)(async t=>{if(r.length===0||l)return;let n=r[0];if(!n||!n.id)return;u(!0),f(t),m(null);let a=[...r];try{let{data:{session:r}}=await j.auth.getSession(),o=r?r.access_token:`sandbox`,s=await fetch(`/api/reviews/complete`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${o}`},body:JSON.stringify({review_id:n.id,fsrs_state:n.fsrs_state??0,fsrs_step:n.fsrs_step??0,fsrs_stability:n.fsrs_stability??0,fsrs_difficulty:n.fsrs_difficulty??0,fsrs_elapsed_days:n.fsrs_elapsed_days??0,fsrs_scheduled_days:n.fsrs_scheduled_days??0,fsrs_reps:n.fsrs_reps??0,fsrs_lapses:n.fsrs_lapses??0,last_reviewed:n.last_reviewed,rating:t})});if(s.ok){let r=n?.problems?.name||``,a=n?.problems?.pattern||``,o=`Correct`;o=t===1?`Incorrect`:t===2?`Mixed`:`Correct`,M.addReviewEvent(o,r,a).catch(()=>{});let s=re(),l=h.trim()||n?.problems?.reference_code||``;s.token&&s.repoName&&s.autoCommit&&l&&ne({token:s.token,repo:s.repoName,branch:s.branch,problem_number:n?.problems?.problem_number,problem_name:r||`Algorithm Problem`,pattern:a||`Algorithms`,difficulty:n?.problems?.difficulty||`Medium`,optimal_time:n?.problems?.optimal_time||`O(N)`,optimal_space:n?.problems?.optimal_space||`O(1)`,description:n?.problems?.description||``,code:l}).catch(e=>{console.warn(`GitHub background auto-commit failed:`,e)}),e&&w.current&&(T.current=!0,w.current()),i(e=>{let t=e.slice(1);try{let e=W(x);localStorage.setItem(`algospaced_review_queue_${e}`,JSON.stringify(t))}catch{}if(t.length>0){let e=t[0],n=e.problems,r=n?.problem_number??(/^\d+$/.test(e?.problem_id||``)?parseInt(e.problem_id,10):void 0),i=F(r,n?.id||e?.problem_id,n?.name)?.starter_code||n?.starter_code||``;g(i)}else g(``);return t}),c(null),E(!1)}else{let e=await s.json().catch(()=>({}));m(e.detail||`Server returned error (${s.status}). Please try again.`),i(a)}}catch(e){console.error(`Error logging review completion:`,e);let t=e instanceof Error?e.message:`Network connection failed while logging review.`;m(t),i(a)}finally{u(!1),f(null)}},[r,l,e,E,h,x]),O=(0,H.useCallback)(async()=>{if(_&&!y){b(!0);try{await N(_),await E()}catch(e){console.error(`Failed to activate next milestone:`,e)}finally{b(!1)}}},[_,y,E]),ee=(0,H.useCallback)(()=>{let e=r[0],t=e?.problems,n=t?.problem_number??(/^\d+$/.test(e?.problem_id||``)?parseInt(e.problem_id,10):void 0),i=F(n,t?.id||e?.problem_id,t?.name)?.starter_code||t?.starter_code||``;g(i)},[r]);return{reviews:r,setReviews:i,loading:a,queueError:s,submitting:l,submittingRating:d,gradeError:p,setGradeError:m,code:h,setCode:g,nextMilestone:_,activatingMilestone:y,currentUserId:x,fetchQueue:E,handleGrade:D,handleSelectCard:(0,H.useCallback)(t=>{if(t<=0||t>=r.length||l)return;e&&w.current&&(T.current=!0,w.current());let n=r[t];if(!n)return;let a=n.problems,o=a?.problem_number??(/^\d+$/.test(n?.problem_id||``)?parseInt(n.problem_id,10):void 0),s=F(o,a?.id||n?.problem_id,a?.name)?.starter_code||a?.starter_code||``;g(s),i(e=>{let t=e.findIndex(e=>e.id&&e.id===n.id||e===n);return t<=0?e:[e[t],...e.slice(0,t),...e.slice(t+1)]})},[r,l,e]),handleActivateNextMilestone:O,handleResetStarterCode:ee}}function pe(){return{sandboxRunning:P(e=>e.sandboxRunning),sandboxResults:P(e=>e.sandboxResults),sandboxError:P(e=>e.sandboxError),savingReference:P(e=>e.savingReference),savedRefSuccess:P(e=>e.savedRefSuccess),saveRefError:P(e=>e.saveRefError),handleRunSandbox:P(e=>e.handleRunSandbox),handleSaveReference:P(e=>e.handleSaveReference),resetSandbox:P(e=>e.resetSandbox)}}function me(){return{aiLoading:P(e=>e.aiLoading),aiResult:P(e=>e.aiResult),aiError:P(e=>e.aiError),explainLoading:P(e=>e.explainLoading),explanationText:P(e=>e.explanationText),explainError:P(e=>e.explainError),aiSolutionLoading:P(e=>e.aiSolutionLoading),aiSolutionError:P(e=>e.aiSolutionError),handleAiEvaluation:P(e=>e.handleAiEvaluation),handleExplainCode:P(e=>e.handleExplainCode),handleFetchAiSolution:P(e=>e.handleFetchAiSolution),resetAiState:P(e=>e.resetAiState)}}var he=({problem:e,totalInQueue:t,reviews:n=[],onSelectCard:r,onOpenCreateProblem:i,onOpenEditProblem:o})=>{let[s,c]=(0,H.useState)(!1),u=(0,H.useRef)(null);(0,H.useEffect)(()=>{let e=e=>{u.current&&!u.current.contains(e.target)&&c(!1)},t=e=>{e.key===`Escape`&&c(!1)};return s&&(document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t)),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[s]);let d=e.problem_number?`https://leetcode.com/problemset/all/?search=${e.problem_number}`:`https://leetcode.com/problemset/all/?search=${encodeURIComponent(e.name||``)}`;return(0,U.jsxs)(`div`,{className:`shrink-0 bg-paper-white border-b-[3px] border-ink-black px-2.5 sm:px-4 py-2 flex flex-wrap items-center justify-between gap-2 shadow-[0_2px_0_0_rgba(30,41,59,0.05)] relative z-40`,children:[(0,U.jsxs)(`div`,{className:`flex items-center gap-1.5 sm:gap-2 flex-wrap min-w-0`,children:[(0,U.jsxs)(`div`,{className:`relative shrink-0`,ref:u,children:[(0,U.jsxs)(`button`,{onClick:()=>c(e=>!e),className:`h-7 inline-flex items-center gap-1.5 px-2 sm:px-2.5 bg-amber-300 hover:bg-amber-200 border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none transition-all cursor-pointer shrink-0`,title:`Click to view all cards due in today's queue`,children:[(0,U.jsx)(`span`,{className:`w-2 h-2 rounded-full bg-emerald-500 animate-ping shrink-0`}),(0,U.jsx)(`span`,{className:`font-arcade text-[8px] sm:text-[9px] font-bold text-ink-black tracking-wide whitespace-nowrap`,children:`CARD 1 OF ${t}`}),t>1&&(0,U.jsx)(ee,{className:`w-3 h-3 text-ink-black transition-transform shrink-0 ${s?`rotate-180`:``}`})]}),s&&n.length>0&&(0,U.jsxs)(`div`,{className:`absolute top-9 left-0 z-50 w-64 min-[400px]:w-72 sm:w-80 bg-paper-white border-[3px] border-ink-black gadget-shadow p-3 space-y-2 max-w-[calc(100vw-32px)]`,children:[(0,U.jsxs)(`div`,{className:`flex items-center justify-between border-b-2 border-ink-black pb-1.5 font-arcade text-[9px] font-bold text-ink-black`,children:[(0,U.jsx)(`span`,{children:`DAILY QUEUE (${n.length} CARDS)`}),(0,U.jsx)(`button`,{onClick:()=>c(!1),className:`px-1 hover:text-rose-600 font-bold cursor-pointer`,title:`Close`,children:`✕`})]}),(0,U.jsx)(`div`,{className:`text-[7.5px] font-arcade text-trash-gray uppercase -mt-0.5`,children:`Click any card to solve it now:`}),(0,U.jsx)(`div`,{className:`max-h-60 overflow-y-auto no-scrollbar space-y-1.5 pr-1`,children:n.map((e,t)=>{let n=e.problems,i=n?.problem_number,a=i==null?void 0:te(i),{cleanTitle:o,approachVariant:s}=ue(n?.name||``,a?.name),u=s?`${o} (${s})`:o,d=t===0,f=n?.difficulty,p=f?f.toUpperCase():`EASY`,m=f===`Easy`?`bg-emerald-600 text-white`:f===`Medium`?`bg-amber-400 text-ink-black`:`bg-rose-600 text-white`;return(0,U.jsxs)(`button`,{type:`button`,onClick:()=>{d||r?.(t),c(!1)},className:`group w-full text-left p-2 border-2 border-ink-black text-xs flex items-center justify-between gap-2 cursor-pointer transition-all duration-150 select-none ${d?`bg-amber-100 font-bold shadow-[2px_2px_0px_0px_rgba(30,41,59,1)]`:`bg-white hover:bg-amber-50 hover:translate-x-0.5 active:translate-y-0.5 active:shadow-none shadow-[2px_2px_0px_0px_rgba(30,41,59,0.25)]`}`,title:d?`Currently active card`:`Jump to #${t+1}: ${u}`,children:[(0,U.jsxs)(`div`,{className:`flex items-center gap-1.5 truncate min-w-0`,children:[(0,U.jsxs)(`span`,{className:`font-arcade text-[9px] text-trash-gray shrink-0`,children:[`#`,t+1]}),i!=null&&(0,U.jsxs)(`span`,{className:`font-arcade text-[8px] font-bold px-1 py-0.2 bg-amber-300 border border-ink-black shrink-0`,children:[`LC #`,i]}),(0,U.jsx)(`span`,{className:`truncate`,children:u})]}),(0,U.jsxs)(`div`,{className:`flex items-center gap-1.5 shrink-0`,children:[d?(0,U.jsx)(`span`,{className:`text-[7.5px] font-arcade font-extrabold px-1 py-0.5 bg-amber-300 text-ink-black border border-ink-black shrink-0`,children:`NOW`}):(0,U.jsx)(l,{className:`w-2.5 h-2.5 fill-ink-black text-ink-black opacity-0 group-hover:opacity-100 transition-opacity shrink-0`}),(0,U.jsx)(`span`,{className:`text-[8px] font-arcade font-bold px-1.5 py-0.5 border border-ink-black shrink-0 ${m}`,children:p})]})]},e.id||t)})})]})]}),e.problem_number!==void 0&&e.problem_number!==null&&(0,U.jsx)(`span`,{className:`h-7 inline-flex items-center px-2 font-arcade text-[8px] sm:text-[9px] font-bold bg-amber-200 border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] text-ink-black shrink-0 select-none whitespace-nowrap`,children:e.problem_number>0?`LC #${e.problem_number}`:`CUSTOM`}),(0,U.jsx)(`span`,{className:`h-7 inline-flex items-center px-2 font-arcade text-[8px] sm:text-[9px] font-bold border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] shrink-0 select-none whitespace-nowrap ${e.difficulty===`Easy`?`bg-emerald-600 text-white`:e.difficulty===`Medium`?`bg-amber-400 text-ink-black`:`bg-rose-600 text-white`}`,children:e.difficulty?e.difficulty.toUpperCase():`EASY`})]}),(0,U.jsxs)(`div`,{className:`flex items-center gap-1.5 sm:gap-2 shrink-0 flex-wrap justify-end`,children:[(0,U.jsxs)(`button`,{onClick:i,className:`h-7 inline-flex items-center gap-1 px-2 sm:px-2.5 bg-white hover:bg-purple-50 border-2 border-ink-black text-ink-black text-[8px] sm:text-[9px] font-arcade font-bold shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none transition-all cursor-pointer shrink-0`,title:`Create or Import Problem`,children:[(0,U.jsx)(y,{className:`w-3 h-3 text-purple-600 shrink-0`}),(0,U.jsx)(`span`,{className:`hidden min-[480px]:inline`,children:`ADD`})]}),o&&(0,U.jsxs)(`button`,{onClick:o,className:`h-7 inline-flex items-center gap-1 px-2 sm:px-2.5 bg-white hover:bg-emerald-50 border-2 border-ink-black text-ink-black text-[8px] sm:text-[9px] font-arcade font-bold shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none transition-all cursor-pointer shrink-0`,title:`Edit Problem Specification`,children:[(0,U.jsx)(a,{className:`w-3 h-3 text-emerald-600 shrink-0`}),(0,U.jsx)(`span`,{className:`hidden min-[480px]:inline`,children:`EDIT`})]}),e.google_doc_url&&(0,U.jsxs)(`a`,{href:e.google_doc_url,target:`_blank`,rel:`noreferrer`,className:`h-7 inline-flex items-center gap-1 px-2 sm:px-2.5 bg-white hover:bg-slate-100 border-2 border-ink-black text-ink-black text-[8px] sm:text-[9px] font-arcade font-bold shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none transition-all cursor-pointer shrink-0`,title:`Open Google Doc Notes`,children:[(0,U.jsx)(`span`,{children:`DOC`}),(0,U.jsx)(_,{className:`w-2.5 h-2.5 text-primary shrink-0`})]}),(0,U.jsxs)(`a`,{href:d,target:`_blank`,rel:`noreferrer`,className:`h-7 inline-flex items-center gap-1 px-2 sm:px-2.5 bg-white hover:bg-slate-100 border-2 border-ink-black text-ink-black text-[8px] sm:text-[9px] font-arcade font-bold shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none transition-all cursor-pointer shrink-0`,title:`Search LeetCode`,children:[(0,U.jsx)(`span`,{children:`LC`}),(0,U.jsx)(_,{className:`w-2.5 h-2.5 text-amber-600 shrink-0`})]})]})]})},ge=se.mark({class:`cm-indent-dot cm-indent-dot-primary`}),_e=se.mark({class:`cm-indent-dot cm-indent-dot-secondary`});function G(e){let t=new B;for(let{from:n,to:r}of e.visibleRanges){let i=n;for(;i<r;){let n=e.state.doc.lineAt(i),r=n.text,a=0;for(;a<r.length&&(r[a]===` `||r[a]===` `);){let e=n.from+a,i=e+1,o=a%4==0||r[a]===` `;t.add(e,i,o?ge:_e),a++}i=n.to+1}}return t.finish()}var ve=z.fromClass(class{decorations;constructor(e){this.decorations=G(e)}update(e){(e.docChanged||e.viewportChanged)&&(this.decorations=G(e.view))}},{decorations:e=>e.decorations}),ye=V.theme({"&":{backgroundColor:`#0c111d`,color:`#f1f5f9`,height:`100%`,fontSize:`13px`,fontFamily:`var(--font-code, "JetBrains Mono", "Fira Code", monospace)`},".cm-scroller":{overflow:`auto`,fontFamily:`inherit`,lineHeight:`1.65`},".cm-content":{caretColor:`#4ade80`,padding:`12px 0`},"&.cm-focused .cm-cursor":{borderLeftColor:`#4ade80`,borderLeftWidth:`2px`,filter:`drop-shadow(0 0 5px rgba(74, 222, 128, 0.8))`},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground, ::selection":{backgroundColor:`rgba(56, 189, 248, 0.25) !important`},".cm-gutters":{backgroundColor:`#070a12`,color:`#475569`,borderRight:`2px solid #1e293b`,paddingRight:`6px`,userSelect:`none`},".cm-activeLineGutter":{backgroundColor:`#131b2e`,color:`#38bdf8`,fontWeight:`700`},".cm-activeLine, &.cm-focused .cm-activeLine":{backgroundColor:`#0f172a !important`},".cm-line":{padding:`0 10px`},".cm-indent-dot":{position:`relative`,display:`inline-block`},".cm-indent-dot::before":{position:`absolute`,top:`50%`,left:`50%`,transform:`translate(-50%, -50%)`,pointerEvents:`none`,userSelect:`none`,lineHeight:`0`,fontFamily:`monospace`},".cm-indent-dot-primary::before":{content:`"•"`,color:`#38bdf8`,fontSize:`9px`,opacity:`0.85`},".cm-indent-dot-secondary::before":{content:`"·"`,color:`#64748b`,fontSize:`11px`,opacity:`0.5`},"&.cm-focused .cm-matchingBracket, .cm-matchingBracket":{backgroundColor:`rgba(74, 222, 128, 0.2)`,outline:`1px solid #4ade80`,borderRadius:`2px`,color:`#86efac !important`},".cm-placeholder":{color:`#64748b`,fontStyle:`italic`},".cm-scroller::-webkit-scrollbar":{width:`6px`,height:`6px`},".cm-scroller::-webkit-scrollbar-track":{backgroundColor:`#070a12`},".cm-scroller::-webkit-scrollbar-thumb":{backgroundColor:`#1e293b`,borderRadius:`3px`,border:`1px solid #334155`},".cm-scroller::-webkit-scrollbar-thumb:hover":{backgroundColor:`#38bdf8`}}),be=[oe(),ce.of(` `),R.of([ae]),ve,ye,V.contentAttributes.of({"aria-label":`Python Code Editor`})],K=[{id:`python`,name:`Python`,version:`3.14`}],xe=({className:e=`w-3.5 h-3.5`})=>(0,U.jsxs)(`svg`,{viewBox:`0 0 128 128`,className:e,xmlns:`http://www.w3.org/2000/svg`,children:[(0,U.jsx)(`path`,{d:`M63.454 4.018c-14.775 0-23.774 6.425-23.774 18.775v13.626h24.168v3.424H30.082C17.518 39.843 8 47.962 8 63.673c0 15.65 8.358 23.486 21.056 23.486h11.905v-16.89c0-13.064 11.233-24.113 24.331-24.113h23.773V32.793c0-11.83-9.988-19.775-23.773-19.775H63.454v-9zm-9.845 7.426a3.84 3.84 0 0 1 3.86 3.84 3.84 3.84 0 0 1-3.86 3.841 3.84 3.84 0 0 1-3.86-3.84 3.84 3.84 0 0 1 3.86-3.841z`,fill:`#387eb8`}),(0,U.jsx)(`path`,{d:`M64.546 123.982c14.775 0 23.774-6.425 23.774-18.775V91.581H64.152v-3.424h33.766c12.564 0 22.082-8.119 22.082-23.83 0-15.65-8.358-23.486-21.056-23.486H87.04v16.89c0 13.064-11.234 24.113-24.332 24.113H38.934v13.363c0 11.83 9.989 19.775 23.774 19.775h1.838v9zm9.845-7.426a3.84 3.84 0 0 1-3.86-3.84 3.84 3.84 0 0 1 3.86-3.841 3.84 3.84 0 0 1 3.86 3.84 3.84 3.84 0 0 1-3.86 3.841z`,fill:`#ffe052`})]}),Se=({mobileView:e,isNarrow:t=!1,isAutocompleteEnabled:r,onToggleAutocomplete:a,onResetStarterCode:o,code:d,onChangeCode:p,sandboxRunning:v,sandboxError:y,sandboxResults:S,onRunSandbox:C,savingReference:w,savedRefSuccess:E,saveRefError:D,onSaveReference:k,aiLoading:A,aiError:j,aiResult:M,onAiEvaluation:N,optimalTime:P,optimalSpace:te,onPushToGitHub:F,pushingToGitHub:I,githubPushedUrl:L,githubPushError:ne})=>{let[re,ie]=(0,H.useState)(`python`),[R,z]=(0,H.useState)(!1),B=(0,H.useRef)(null);(0,H.useEffect)(()=>{let e=e=>{B.current&&!B.current.contains(e.target)&&z(!1)},t=e=>{e.key===`Escape`&&z(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[]);let V=K.find(e=>e.id===re)??K[0];return(0,U.jsxs)(`div`,{className:`w-full ${t?`flex flex-1`:`lg:w-[51%] flex`} flex-col bg-[#fffdfa] overflow-y-auto no-scrollbar ${t&&e!==`code`?`hidden`:`flex`}`,children:[(0,U.jsxs)(`div`,{className:`shrink-0 bg-[#f7f5ed] border-b-2 border-ink-black p-2 sm:px-3 flex flex-wrap items-center justify-between gap-1.5 sm:gap-2`,children:[(0,U.jsxs)(`div`,{className:`flex items-center gap-1.5 sm:gap-2 flex-wrap`,children:[(0,U.jsxs)(`div`,{className:`relative`,ref:B,children:[(0,U.jsxs)(`button`,{type:`button`,onClick:()=>z(e=>!e),className:`h-7 px-2.5 bg-white hover:bg-slate-100 border-2 border-ink-black shadow-[1px_1px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none flex items-center gap-1.5 font-arcade text-[9px] font-bold text-ink-black cursor-pointer transition-all select-none`,title:`Select programming language`,"aria-expanded":R,"aria-haspopup":`listbox`,children:[(0,U.jsx)(xe,{className:`w-3.5 h-3.5 shrink-0`}),(0,U.jsx)(`span`,{children:V.name}),(0,U.jsx)(ee,{className:`w-3 h-3 text-ink-black transition-transform duration-150 ${R?`rotate-180`:``}`})]}),R&&(0,U.jsxs)(`div`,{className:`absolute top-full mt-1.5 left-0 z-50 w-52 bg-paper-white border-[3px] border-ink-black gadget-shadow p-1.5 space-y-1`,role:`listbox`,children:[(0,U.jsx)(`div`,{className:`px-2 py-1 text-[8px] font-arcade font-bold text-trash-gray uppercase border-b border-slate-200`,children:`SELECT LANGUAGE`}),K.map(e=>{let t=re===e.id;return(0,U.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":t,onClick:()=>{ie(e.id),z(!1)},className:`w-full flex items-center justify-between px-2.5 py-1.5 border-2 border-ink-black text-left transition-all cursor-pointer ${t?`bg-amber-200 shadow-[1px_1px_0px_0px_rgba(30,41,59,1)] font-bold text-ink-black`:`bg-white hover:bg-slate-100 text-slate-800`}`,children:[(0,U.jsxs)(`div`,{className:`flex items-center gap-1.5 font-arcade text-[9px]`,children:[(0,U.jsx)(xe,{className:`w-3.5 h-3.5 shrink-0`}),(0,U.jsx)(`span`,{children:e.name})]}),(0,U.jsxs)(`span`,{className:`font-mono text-[8px] font-bold px-1.5 py-0.5 bg-white border border-ink-black text-slate-700 shadow-[1px_1px_0px_0px_rgba(30,41,59,0.3)]`,children:[`v`,e.version]})]},e.id)})]})]}),(0,U.jsx)(`div`,{className:`h-4 w-[2px] bg-slate-300 mx-0.5 hidden sm:block`}),(0,U.jsxs)(`label`,{className:`inline-flex items-center gap-1.5 cursor-pointer select-none`,children:[(0,U.jsx)(`input`,{type:`checkbox`,checked:r,onChange:e=>a(e.target.checked),className:`sr-only peer`,"aria-label":`Toggle code editor autocompletion`}),(0,U.jsx)(`div`,{className:`relative w-7 h-3.5 bg-slate-300 border border-ink-black rounded-full peer peer-checked:bg-grass-green transition-all after:content-[''] after:absolute after:top-[1px] after:left-[2px] after:bg-white after:border after:border-ink-black after:rounded-full after:h-2 after:w-2 after:transition-all peer-checked:after:translate-x-3`}),(0,U.jsx)(`span`,{className:`text-[7.5px] min-[400px]:text-[8px] font-arcade font-bold text-trash-gray peer-checked:text-ink-black whitespace-nowrap`,children:`AUTOCOMPLETE`})]})]}),(0,U.jsxs)(`div`,{className:`flex items-center gap-1.5 sm:gap-2`,children:[(0,U.jsx)(`button`,{onClick:o,className:`w-7 h-7 bg-white hover:bg-slate-100 border-2 border-ink-black shadow-[1px_1px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none text-ink-black flex items-center justify-center cursor-pointer transition-all`,title:`Reset to starter code`,"aria-label":`Reset to starter code`,children:(0,U.jsx)(n,{className:`w-3.5 h-3.5`})}),(0,U.jsx)(`button`,{onClick:()=>p(``),className:`w-7 h-7 bg-white hover:bg-rose-50 border-2 border-ink-black shadow-[1px_1px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none text-rose-700 flex items-center justify-center cursor-pointer transition-all`,title:`Clear editor`,"aria-label":`Clear editor`,children:(0,U.jsx)(b,{className:`w-3.5 h-3.5 text-rose-600`})}),k&&(0,U.jsx)(`button`,{onClick:k,disabled:w||!d.trim(),className:`w-7 h-7 border-2 border-ink-black shadow-[1px_1px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none flex items-center justify-center cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed transition-all ${E?`bg-emerald-600 hover:bg-emerald-500 text-white`:`bg-amber-400 hover:bg-amber-300 text-ink-black`}`,title:w?`Saving solution to personal database...`:E?`Saved to personal database!`:`Overwrite saved solution with studio code`,"aria-label":`Overwrite saved solution with studio code`,children:w?(0,U.jsx)(s,{className:`w-3.5 h-3.5 animate-spin text-ink-black`}):E?(0,U.jsx)(g,{className:`w-3.5 h-3.5 text-white`}):(0,U.jsx)(c,{className:`w-3.5 h-3.5 text-ink-black`})}),F&&(0,U.jsx)(`button`,{onClick:F,disabled:I||!d.trim(),className:`w-7 h-7 bg-[#24292e] hover:bg-black border-2 border-ink-black shadow-[1px_1px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none text-white flex items-center justify-center cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed transition-all`,title:I?`Pushing to GitHub...`:`Push solution to GitHub repository`,"aria-label":`Push to GitHub`,children:I?(0,U.jsx)(s,{className:`w-3.5 h-3.5 animate-spin text-yellow-300`}):(0,U.jsx)(h,{className:`w-3.5 h-3.5 text-yellow-300`})})]}),(0,U.jsxs)(`div`,{className:`flex items-center gap-1.5 sm:gap-2`,children:[(0,U.jsx)(`button`,{onClick:C,disabled:v||!d.trim(),className:`w-7 h-7 bg-emerald-600 hover:bg-emerald-500 border-2 border-ink-black shadow-[1px_1px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none text-white flex items-center justify-center cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed transition-all`,title:v?`Running sandbox tests...`:`Run tests in local sandbox`,"aria-label":`Run tests`,children:v?(0,U.jsx)(s,{className:`w-3.5 h-3.5 animate-spin`}):(0,U.jsx)(l,{className:`w-3.5 h-3.5 fill-white text-white ml-0.5`})}),(0,U.jsx)(`button`,{onClick:N,disabled:A||!d.trim(),className:`w-7 h-7 bg-purple-600 hover:bg-purple-500 border-2 border-ink-black shadow-[1px_1px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none text-white flex items-center justify-center cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed transition-all`,title:A?`Evaluating code with Gemini...`:`Gemini Eval (AI code review & complexity)`,"aria-label":`Gemini Eval`,children:A?(0,U.jsx)(s,{className:`w-3.5 h-3.5 animate-spin`}):(0,U.jsx)(O,{className:`w-3.5 h-3.5 text-amber-300`})})]})]}),(0,U.jsxs)(`div`,{className:`p-4 sm:p-5 flex-1 flex flex-col space-y-4`,children:[(0,U.jsx)(`div`,{className:`flex-1 flex flex-col min-h-[300px] sm:min-h-[360px] border-[3px] border-ink-black shadow-[4px_4px_0px_0px_rgba(30,41,59,1)] bg-[#0c111d] overflow-hidden`,children:(0,U.jsx)(`div`,{className:`flex-1 overflow-hidden relative`,children:(0,U.jsx)(T,{value:d,onChange:p,placeholder:`def solve(nums): # Write your solution from memory here...`,height:`100%`,theme:`dark`,extensions:be,basicSetup:{autocompletion:r,lineNumbers:!0,foldGutter:!0,dropCursor:!0,allowMultipleSelections:!0,indentOnInput:!0,bracketMatching:!0,closeBrackets:!0,rectangularSelection:!0,crosshairCursor:!0,highlightActiveLine:!0,highlightSelectionMatches:!0,closeBracketsKeymap:!0,defaultKeymap:!0,searchKeymap:!0,historyKeymap:!0,foldKeymap:!0,completionKeymap:!0,lintKeymap:!0},className:`w-full h-full text-xs font-code-mono`})})}),E&&(0,U.jsxs)(`div`,{className:`p-3 bg-[#f0fdf4] border-2 border-emerald-600 text-emerald-950 text-xs font-semibold flex items-center gap-2 shadow-[2px_2px_0px_0px_rgba(30,41,59,1)]`,children:[(0,U.jsx)(g,{className:`w-4 h-4 text-emerald-600 shrink-0`}),(0,U.jsx)(`span`,{children:`Successfully saved studio code as your personal reference solution!`})]}),D&&(0,U.jsxs)(`div`,{className:`p-3 bg-rose-50 border-2 border-rose-500 text-rose-800 text-xs font-semibold flex items-center gap-2 shadow-[2px_2px_0px_0px_rgba(30,41,59,1)]`,children:[(0,U.jsx)(m,{className:`w-4 h-4 text-rose-600 shrink-0`}),(0,U.jsx)(`span`,{children:D})]}),L&&(0,U.jsxs)(`div`,{className:`p-3 bg-[#f0fdf4] border-2 border-emerald-600 text-emerald-950 text-xs font-semibold flex items-center justify-between shadow-[2px_2px_0px_0px_rgba(30,41,59,1)]`,children:[(0,U.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,U.jsx)(g,{className:`w-4 h-4 text-emerald-600 shrink-0`}),(0,U.jsx)(`span`,{children:`Successfully pushed solution to your GitHub repository!`})]}),(0,U.jsxs)(`a`,{href:L,target:`_blank`,rel:`noopener noreferrer`,className:`text-[11px] font-bold text-blue-700 hover:text-blue-900 underline flex items-center gap-1`,children:[(0,U.jsx)(`span`,{children:`View on GitHub`}),(0,U.jsx)(_,{className:`w-3 h-3`})]})]}),ne&&(0,U.jsxs)(`div`,{className:`p-3 bg-rose-50 border-2 border-rose-500 text-rose-800 text-xs font-semibold flex items-center gap-2 shadow-[2px_2px_0px_0px_rgba(30,41,59,1)]`,children:[(0,U.jsx)(m,{className:`w-4 h-4 text-rose-600 shrink-0`}),(0,U.jsx)(`span`,{children:ne})]}),v&&(0,U.jsxs)(`div`,{className:`p-3 border-2 border-ink-black bg-emerald-50 shadow-[3px_3px_0px_0px_rgba(30,41,59,1)] flex items-center gap-3 animate-pulse`,children:[(0,U.jsx)(s,{className:`w-5 h-5 text-emerald-600 animate-spin shrink-0`}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`h4`,{className:`font-arcade text-[9px] font-bold text-ink-black uppercase`,children:`Running...`}),(0,U.jsx)(`p`,{className:`font-sans text-[11px] text-trash-gray font-semibold mt-0.5`,children:`Executing against test cases...`})]})]}),y&&(0,U.jsxs)(`div`,{className:`p-3 border-2 border-rose-500 bg-rose-50 text-rose-800 text-xs font-semibold shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] flex items-center gap-2`,children:[(0,U.jsx)(m,{className:`w-4 h-4 text-rose-600 shrink-0`}),(0,U.jsx)(`span`,{children:y})]}),S&&(0,U.jsxs)(`div`,{className:`border-[3px] border-ink-black p-4 sm:p-5 shadow-[4px_4px_0px_0px_rgba(30,41,59,1)] space-y-3.5 ${S.status===`passed`?`bg-[#f0fdf4]`:`bg-[#fff1f2]`}`,children:[(0,U.jsxs)(`div`,{className:`flex flex-col sm:flex-row sm:items-center justify-between gap-2 pb-2.5 border-b-2 border-dashed border-ink-black`,children:[(0,U.jsxs)(`div`,{className:`flex items-center gap-2.5`,children:[(0,U.jsx)(`div`,{className:`w-8 h-8 border-2 border-ink-black flex items-center justify-center font-bold shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] ${S.status===`passed`?`bg-grass-green text-ink-black`:`bg-rose-500 text-white`}`,children:S.status===`passed`?(0,U.jsx)(u,{className:`w-5 h-5 stroke-[3]`}):(0,U.jsx)(m,{className:`w-4 h-4`})}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`div`,{className:`font-arcade text-[10px] font-bold text-ink-black flex items-center gap-1.5 uppercase`,children:S.status===`passed`?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`span`,{children:`ALL TESTS PASSED`}),(0,U.jsx)(g,{className:`w-3.5 h-3.5 text-emerald-600 inline`})]}):(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`span`,{children:S.status===`error`?`EXECUTION ERROR`:`TESTS FAILED`}),(0,U.jsx)(x,{className:`w-3.5 h-3.5 text-rose-600 inline`})]})}),(0,U.jsxs)(`div`,{className:`font-sans text-[11px] text-slate-600 font-semibold`,children:[S.passed_count??0,` of `,S.total_tests??0,` test cases passed (`,(S.duration_ms??0).toFixed(1),`ms)`]})]})]}),S.status===`passed`&&(0,U.jsxs)(`button`,{onClick:k,disabled:w,className:`px-3 py-1.5 bg-white hover:bg-emerald-100 border-2 border-ink-black text-ink-black font-arcade text-[8px] font-bold flex items-center gap-1.5 shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none transition-all cursor-pointer shrink-0 disabled:opacity-50`,children:[w?(0,U.jsx)(s,{className:`w-3 h-3 animate-spin`}):E?(0,U.jsx)(g,{className:`w-3.5 h-3.5 text-emerald-600`}):(0,U.jsx)(c,{className:`w-3.5 h-3.5 text-blue-600`}),(0,U.jsx)(`span`,{children:E?`SAVED TO DB!`:`SAVE AS OFFICIAL SOLUTION`})]})]}),D&&(0,U.jsx)(`div`,{className:`p-2 border border-rose-500 bg-rose-100 text-rose-800 text-[11px] font-semibold`,children:D}),S.results&&S.results.length>0&&(0,U.jsxs)(`div`,{className:`space-y-2`,children:[(0,U.jsx)(`span`,{className:`font-arcade text-[8px] text-trash-gray uppercase font-bold block`,children:`TEST CASE BREAKDOWN:`}),(0,U.jsx)(`div`,{className:`space-y-1.5 max-h-56 overflow-y-auto custom-scrollbar`,children:S.results.map((e,t)=>(0,U.jsxs)(`div`,{className:`p-2.5 border-2 border-ink-black text-xs font-mono shadow-[2px_2px_0px_0px_rgba(30,41,59,0.3)] ${e.passed?`bg-white`:`bg-rose-50`}`,children:[(0,U.jsxs)(`div`,{className:`flex items-center justify-between font-arcade text-[8px] mb-1`,children:[(0,U.jsxs)(`span`,{className:`font-bold text-ink-black`,children:[`CASE #`,t+1]}),(0,U.jsx)(`span`,{className:e.passed?`text-emerald-700 font-bold`:`text-rose-700 font-bold`,children:e.passed?`✓ PASSED`:`✗ FAILED`})]}),(0,U.jsxs)(`div`,{className:`grid grid-cols-1 sm:grid-cols-3 gap-1.5 text-[10px]`,children:[(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`span`,{className:`text-slate-500 block`,children:`Input:`}),(0,U.jsx)(`span`,{className:`font-code-mono text-ink-black font-semibold break-all`,children:JSON.stringify(e.input)})]}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`span`,{className:`text-slate-500 block`,children:`Expected:`}),(0,U.jsx)(`span`,{className:`font-code-mono text-emerald-700 font-semibold break-all`,children:JSON.stringify(e.expected)})]}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`span`,{className:`text-slate-500 block`,children:`Output:`}),(0,U.jsx)(`span`,{className:`font-code-mono font-semibold break-all ${e.passed?`text-emerald-700`:`text-rose-700`}`,children:e.output===void 0?`None`:JSON.stringify(e.output)})]})]}),e.error&&(0,U.jsx)(`div`,{className:`mt-1.5 p-1.5 bg-rose-100 text-rose-900 text-[10px] font-mono border border-rose-300 break-all`,children:e.error})]},t))})]}),S.error&&(0,U.jsx)(`div`,{className:`p-3 bg-[#1E293B] text-rose-400 font-code-mono text-[11px] border-2 border-ink-black overflow-x-auto whitespace-pre-wrap select-text`,children:S.error}),S.status===`passed`&&(0,U.jsx)(`div`,{className:`p-2 bg-emerald-100/70 border border-emerald-300 text-emerald-900 text-xs flex items-center justify-between`,children:(0,U.jsx)(`span`,{className:`font-sans font-medium`,children:`✨ All unit tests passed. Rate your recall below.`})})]}),A&&(0,U.jsxs)(`div`,{className:`p-4 border-2 border-ink-black bg-amber-50 shadow-[3px_3px_0px_0px_rgba(30,41,59,1)] flex items-center gap-3 animate-pulse`,children:[(0,U.jsx)(s,{className:`w-6 h-6 text-purple-600 animate-spin shrink-0`}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`h4`,{className:`font-arcade text-[9px] font-bold text-ink-black uppercase`,children:`ANALYZING...`}),(0,U.jsx)(`p`,{className:`font-sans text-[11px] text-trash-gray font-semibold mt-0.5`,children:`Checking edge cases, bounds, and Big-O efficiency against optimal constraints...`})]})]}),j&&(0,U.jsx)(`div`,{className:`p-3 border-2 border-rose-500 bg-rose-50 text-rose-800 text-xs font-semibold shadow-[2px_2px_0px_0px_rgba(30,41,59,1)]`,children:j}),M&&(0,U.jsxs)(`div`,{className:`border-[3px] border-ink-black bg-[#fefce8] p-4 sm:p-5 shadow-[4px_4px_0px_0px_rgba(30,41,59,1)] space-y-4`,children:[(0,U.jsxs)(`div`,{className:`flex items-center justify-between pb-3 border-b-2 border-dashed border-ink-black`,children:[(0,U.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,U.jsx)(`div`,{className:`w-9 h-9 border-2 border-ink-black flex items-center justify-center font-bold shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] ${M.is_correct?`bg-grass-green text-ink-black`:`bg-rose-500 text-white`}`,children:M.is_correct?(0,U.jsx)(u,{className:`w-5 h-5 stroke-[3]`}):(0,U.jsx)(i,{className:`w-5 h-5`})}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`span`,{className:`font-arcade text-[10px] font-bold text-ink-black flex items-center gap-1.5`,children:M.is_correct?(0,U.jsxs)(U.Fragment,{children:[`STATUS: PASSED`,(0,U.jsx)(g,{className:`w-3.5 h-3.5 text-emerald-600 inline`})]}):(0,U.jsxs)(U.Fragment,{children:[`STATUS: FAILED`,(0,U.jsx)(x,{className:`w-3.5 h-3.5 text-rose-600 inline`})]})}),(0,U.jsx)(`span`,{className:`font-sans text-[11px] text-slate-600 font-semibold`,children:M.is_correct?`Algorithm matches expected logic and patterns.`:`Bugs or edge-case failures detected.`})]})]}),(0,U.jsx)(`span`,{className:`font-arcade text-[9px] px-2 py-1 border-2 border-ink-black uppercase font-bold shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] ${M.is_correct?`bg-emerald-100 text-emerald-800`:`bg-rose-100 text-rose-800`}`,children:M.is_correct?`CORRECT`:`INCORRECT`})]}),(0,U.jsxs)(`div`,{className:`grid grid-cols-2 gap-3`,children:[(0,U.jsxs)(`div`,{className:`p-2.5 bg-white border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)]`,children:[(0,U.jsx)(`span`,{className:`font-arcade text-[8px] text-trash-gray block uppercase font-bold`,children:`Time Complexity`}),(0,U.jsxs)(`div`,{className:`flex items-baseline gap-2 mt-1`,children:[(0,U.jsx)(`span`,{className:`font-code-mono text-xs font-bold text-ink-black`,children:M.detected_complexity?.time||`N/A`}),(0,U.jsxs)(`span`,{className:`text-[10px] font-sans text-slate-500 font-semibold`,children:[`(Target: `,P||`O(N)`,`)`]})]})]}),(0,U.jsxs)(`div`,{className:`p-2.5 bg-white border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)]`,children:[(0,U.jsx)(`span`,{className:`font-arcade text-[8px] text-trash-gray block uppercase font-bold`,children:`Space Complexity`}),(0,U.jsxs)(`div`,{className:`flex items-baseline gap-2 mt-1`,children:[(0,U.jsx)(`span`,{className:`font-code-mono text-xs font-bold text-ink-black`,children:M.detected_complexity?.space||`N/A`}),(0,U.jsxs)(`span`,{className:`text-[10px] font-sans text-slate-500 font-semibold`,children:[`(Target: `,te||`O(1)`,`)`]})]})]})]}),M.bugs&&M.bugs.length>0&&(0,U.jsxs)(`div`,{className:`p-3 bg-white border-2 border-ink-black space-y-1.5 shadow-[2px_2px_0px_0px_rgba(30,41,59,1)]`,children:[(0,U.jsxs)(`span`,{className:`font-arcade text-[8px] text-rose-600 uppercase font-bold block flex items-center gap-1`,children:[(0,U.jsx)(m,{className:`w-3 h-3 text-rose-500`}),`TRACES & EDGE CASE ISSUES:`]}),(0,U.jsx)(`ul`,{className:`list-disc list-inside text-xs text-slate-800 space-y-1 font-semibold pl-1`,children:M.bugs.map((e,t)=>(0,U.jsx)(`li`,{className:`leading-relaxed select-text`,children:e},t))})]}),M.key_suggestion&&(0,U.jsxs)(`div`,{className:`p-3 bg-amber-50 border-2 border-ink-black space-y-1 shadow-[2px_2px_0px_0px_rgba(30,41,59,1)]`,children:[(0,U.jsxs)(`span`,{className:`font-arcade text-[8px] text-amber-700 uppercase font-bold block flex items-center gap-1`,children:[(0,U.jsx)(O,{className:`w-3 h-3 text-amber-500`}),`TIP:`]}),(0,U.jsx)(`p`,{className:`text-xs text-slate-800 font-medium leading-relaxed m-0 select-text`,children:M.key_suggestion})]}),(0,U.jsxs)(`div`,{className:`p-2.5 bg-white border-2 border-dashed border-ink-black flex items-center justify-between`,children:[(0,U.jsxs)(`span`,{className:`text-xs font-bold text-ink-black flex items-center gap-1.5`,children:[(0,U.jsx)(f,{className:`w-4 h-4 text-primary`}),`Recommendation:`]}),(0,U.jsx)(`span`,{className:`font-arcade text-[9px] font-bold text-purple-700`,children:M.is_correct?`Rate your recall below.`:`Review issues and rate recall below.`})]})]})]})]})},Ce=({gradeError:e,onDismissGradeError:t,submitting:n,submittingRating:r,onGrade:i})=>(0,U.jsx)(`div`,{className:`shrink-0 bg-[#f8f5eb] border-t-[3px] border-ink-black p-2 sm:p-3 flex flex-col items-stretch gap-1.5 sm:gap-2 shadow-[0_-3px_0_0_rgba(30,41,59,0.08)]`,children:(0,U.jsxs)(`div`,{className:`w-full flex flex-col`,children:[e&&(0,U.jsxs)(`div`,{className:`p-2.5 mb-2 bg-red-100 border-2 border-red-500 text-red-800 text-xs font-semibold shadow-[2px_2px_0px_0px_#1E293B] flex items-center justify-between`,children:[(0,U.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,U.jsx)(m,{className:`w-4 h-4 text-red-600 shrink-0`}),e]}),(0,U.jsx)(`button`,{onClick:t,className:`text-red-900 font-bold hover:underline cursor-pointer ml-2 text-xs`,children:`Dismiss`})]}),(0,U.jsxs)(`div`,{className:`flex gap-1.5 sm:gap-2.5 w-full`,children:[(0,U.jsx)(`button`,{onClick:()=>i(1),disabled:n,className:`flex-1 min-w-0 bg-[#dc2626] hover:bg-[#b91c1c] border-2 sm:border-[3px] border-ink-black py-2 sm:py-2.5 px-1 sm:px-2 arcade-btn cursor-pointer disabled:opacity-60 text-white flex flex-col items-center justify-center font-bold transition-all select-none`,title:`Press 1 on keyboard`,children:r===1?(0,U.jsx)(`div`,{className:`flex items-center gap-1.5 font-arcade text-[10px]`,children:(0,U.jsx)(s,{className:`w-3.5 h-3.5 animate-spin`})}):(0,U.jsxs)(`div`,{className:`flex items-center gap-1 font-headline-md text-[10px] min-[400px]:text-xs sm:text-sm font-extrabold tracking-wide uppercase truncate`,children:[(0,U.jsx)(`span`,{className:`font-arcade text-[8px] sm:text-[9px] px-1 py-0.5 bg-black/20 rounded shrink-0`,children:`1`}),(0,U.jsx)(`span`,{className:`truncate`,children:`Again`})]})}),(0,U.jsx)(`button`,{onClick:()=>i(2),disabled:n,className:`flex-1 min-w-0 bg-[#ff9933] hover:bg-[#ff8000] border-2 sm:border-[3px] border-ink-black py-2 sm:py-2.5 px-1 sm:px-2 arcade-btn cursor-pointer disabled:opacity-60 text-ink-black flex flex-col items-center justify-center font-bold transition-all select-none`,title:`Press 2 on keyboard`,children:r===2?(0,U.jsx)(`div`,{className:`flex items-center gap-1.5 font-arcade text-[10px]`,children:(0,U.jsx)(s,{className:`w-3.5 h-3.5 animate-spin text-ink-black`})}):(0,U.jsxs)(`div`,{className:`flex items-center gap-1 font-headline-md text-[10px] min-[400px]:text-xs sm:text-sm font-extrabold tracking-wide uppercase truncate`,children:[(0,U.jsx)(`span`,{className:`font-arcade text-[8px] sm:text-[9px] px-1 py-0.5 bg-black/10 rounded shrink-0`,children:`2`}),(0,U.jsx)(`span`,{className:`truncate`,children:`Hard`})]})}),(0,U.jsx)(`button`,{onClick:()=>i(3),disabled:n,className:`flex-1 min-w-0 bg-[#4ade80] hover:bg-[#22c55e] border-2 sm:border-[3px] border-ink-black py-2 sm:py-2.5 px-1 sm:px-2 arcade-btn cursor-pointer disabled:opacity-60 text-ink-black flex flex-col items-center justify-center font-bold transition-all select-none`,title:`Press 3 on keyboard`,children:r===3?(0,U.jsx)(`div`,{className:`flex items-center gap-1.5 font-arcade text-[10px]`,children:(0,U.jsx)(s,{className:`w-3.5 h-3.5 animate-spin text-ink-black`})}):(0,U.jsxs)(`div`,{className:`flex items-center gap-1 font-headline-md text-[10px] min-[400px]:text-xs sm:text-sm font-extrabold tracking-wide uppercase truncate`,children:[(0,U.jsx)(`span`,{className:`font-arcade text-[8px] sm:text-[9px] px-1 py-0.5 bg-black/10 rounded shrink-0`,children:`3`}),(0,U.jsx)(`span`,{className:`truncate`,children:`Good`})]})}),(0,U.jsx)(`button`,{onClick:()=>i(4),disabled:n,className:`flex-1 min-w-0 bg-[#60a5fa] hover:bg-[#3b82f6] border-2 sm:border-[3px] border-ink-black py-2 sm:py-2.5 px-1 sm:px-2 arcade-btn cursor-pointer disabled:opacity-60 text-ink-black flex flex-col items-center justify-center font-bold transition-all select-none`,title:`Press 4 on keyboard`,children:r===4?(0,U.jsx)(`div`,{className:`flex items-center gap-1.5 font-arcade text-[10px]`,children:(0,U.jsx)(s,{className:`w-3.5 h-3.5 animate-spin text-ink-black`})}):(0,U.jsxs)(`div`,{className:`flex items-center gap-1 font-headline-md text-[10px] min-[400px]:text-xs sm:text-sm font-extrabold tracking-wide uppercase truncate`,children:[(0,U.jsx)(`span`,{className:`font-arcade text-[8px] sm:text-[9px] px-1 py-0.5 bg-black/10 rounded shrink-0`,children:`4`}),(0,U.jsx)(`span`,{className:`truncate`,children:`Easy`})]})})]})]})}),we=({nextMilestone:e,activatingMilestone:t,onActivateNextMilestone:r,onOpenCardManager:i,onOpenJourney:a,onOpenCreateProblem:o,onOpenWindow:c,overrideProblemId:l,onClearOverride:d})=>(0,U.jsx)(`div`,{className:`w-full h-full flex items-center justify-center bg-[#fdf8e1] p-6 overflow-y-auto custom-scrollbar`,children:(0,U.jsxs)(`div`,{className:`w-full max-w-lg bg-paper-white border-[4px] border-ink-black gadget-shadow p-6 sm:p-8 relative overflow-hidden text-center space-y-6`,children:[(0,U.jsx)(`div`,{className:`absolute top-0 left-0 right-0 h-3 bg-gradient-to-r from-grass-green via-amber-300 to-highlight-pink`}),(0,U.jsxs)(`div`,{className:`relative inline-block mt-2`,children:[(0,U.jsx)(`div`,{className:`w-20 h-20 bg-amber-300 border-[3px] border-ink-black rounded-2xl flex items-center justify-center mx-auto gadget-shadow rotate-[-3deg] hover:rotate-0 transition-transform`,children:(0,U.jsx)(D,{className:`w-10 h-10 text-ink-black stroke-[2.5]`})}),(0,U.jsx)(`div`,{className:`absolute -bottom-2 -right-2 bg-grass-green border-2 border-ink-black px-2 py-0.5 font-arcade text-[8px] text-ink-black font-bold uppercase shadow-[2px_2px_0px_0px_rgba(30,41,59,1)]`,children:`100% DONE`})]}),(0,U.jsxs)(`div`,{className:`space-y-2`,children:[(0,U.jsxs)(`span`,{className:`inline-flex items-center gap-1 px-2.5 py-1 bg-emerald-100 border-2 border-ink-black text-emerald-800 font-arcade text-[9px] font-bold`,children:[(0,U.jsx)(u,{className:`w-3 h-3 stroke-[3]`}),` ALL CARDS COMPLETED FOR TODAY`]}),(0,U.jsx)(`h2`,{className:`text-2xl sm:text-3xl font-extrabold text-ink-black font-headline-md tracking-tight`,children:`You're all caught up for today. Keep it up.`}),(0,U.jsx)(`p`,{className:`text-xs sm:text-sm font-sans text-trash-gray max-w-md mx-auto leading-relaxed font-semibold`,children:`All reviews for today are finished. Next reviews are scheduled for tomorrow.`})]}),e&&(0,U.jsxs)(`div`,{className:`p-4 sm:p-5 bg-gradient-to-br from-amber-50 to-orange-50 border-[3px] border-ink-black gadget-shadow text-left space-y-3`,children:[(0,U.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,U.jsxs)(`span`,{className:`font-arcade text-[9px] font-bold text-amber-800 uppercase tracking-wider flex items-center gap-1.5`,children:[(0,U.jsx)(w,{className:`w-3.5 h-3.5 text-amber-600`}),`NEXT UNEXPLORED MILESTONE`]}),(0,U.jsxs)(`span`,{className:`font-mono text-[10px] font-bold px-2 py-0.5 rounded bg-amber-900/10 text-amber-900 border border-amber-900/20`,children:[`LC #`,e.problem_number]})]}),(0,U.jsxs)(`div`,{className:`flex flex-col sm:flex-row sm:items-center justify-between gap-3`,children:[(0,U.jsxs)(`div`,{className:`min-w-0`,children:[(0,U.jsx)(`h3`,{className:`font-headline-md text-base sm:text-lg font-bold text-ink-black truncate`,children:e.name}),(0,U.jsxs)(`div`,{className:`flex items-center gap-2 mt-1 flex-wrap`,children:[(0,U.jsx)(`span`,{className:`px-2 py-0.5 rounded font-arcade text-[8px] font-bold uppercase text-white ${e.difficulty===`Easy`?`bg-emerald-600`:e.difficulty===`Medium`?`bg-amber-600`:`bg-rose-600`}`,children:e.difficulty}),(0,U.jsx)(`span`,{className:`px-2 py-0.5 rounded font-arcade text-[8px] bg-purple-100 text-purple-800 border border-purple-300 font-bold`,children:e.pattern}),(0,U.jsxs)(`span`,{className:`text-[11px] font-code-mono text-slate-600`,children:[`T: `,e.time_complexity,` | S: `,e.space_complexity]})]})]}),(0,U.jsx)(`button`,{onClick:r,disabled:t,className:`px-4 py-2.5 bg-grass-green hover:bg-emerald-400 text-ink-black font-arcade text-[9px] font-bold border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none transition-all cursor-pointer shrink-0 flex items-center justify-center gap-1.5 disabled:opacity-50`,children:t?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(s,{className:`w-3.5 h-3.5 animate-spin`}),(0,U.jsx)(`span`,{children:`ACTIVATING...`})]}):(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(O,{className:`w-3.5 h-3.5 text-amber-700`}),(0,U.jsx)(`span`,{children:`ACTIVATE & REVIEW NOW`})]})})]})]}),(0,U.jsxs)(`div`,{className:`p-4 sm:p-5 bg-gradient-to-r from-sky-100 via-sky-200 to-indigo-100 border-[3px] border-ink-black gadget-shadow text-left flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3`,children:[(0,U.jsxs)(`div`,{className:`space-y-1`,children:[(0,U.jsxs)(`span`,{className:`font-arcade text-[9px] font-bold text-sky-900 uppercase flex items-center gap-1.5`,children:[(0,U.jsx)(p,{className:`w-3.5 h-3.5 text-sky-700`}),`DECK BROWSER & CARD MANAGER`]}),(0,U.jsx)(`h3`,{className:`font-headline-md text-base sm:text-lg font-bold text-ink-black`,children:`Want to Manage or Reschedule Cards?`}),(0,U.jsx)(`p`,{className:`font-sans text-xs text-trash-gray font-semibold max-w-md`,children:`Browse your full 150-card curriculum, reschedule intervals, or enroll new topics in the Anki-style Card Manager.`})]}),(0,U.jsxs)(`button`,{onClick:()=>{i?i():c?.(`cardManager`)},className:`px-4 py-2.5 bg-sky-400 hover:bg-sky-300 text-ink-black font-arcade text-[9px] font-bold border-2 border-ink-black shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none transition-all cursor-pointer shrink-0 flex items-center gap-1.5`,children:[(0,U.jsx)(p,{className:`w-3.5 h-3.5 text-sky-950`}),(0,U.jsx)(`span`,{children:`OPEN CARD MANAGER`})]})]}),(0,U.jsxs)(`div`,{className:`border-t-[3px] border-dashed border-ink-black pt-5 space-y-3`,children:[(0,U.jsx)(`div`,{className:`text-[9px] font-arcade text-trash-gray uppercase font-bold text-left`,children:`CONTINUE PRACTICING:`}),(0,U.jsxs)(`div`,{className:`grid grid-cols-2 sm:grid-cols-4 gap-2.5`,children:[(0,U.jsxs)(`button`,{onClick:a,className:`p-3 bg-amber-100 hover:bg-amber-200 border-[3px] border-ink-black text-left flex flex-col justify-between gadget-shadow active:translate-y-1 active:shadow-none transition-all cursor-pointer`,children:[(0,U.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,U.jsx)(w,{className:`w-4 h-4 text-amber-600`}),(0,U.jsx)(k,{className:`w-3 h-3 text-ink-black`})]}),(0,U.jsxs)(`div`,{className:`mt-2`,children:[(0,U.jsx)(`div`,{className:`font-arcade text-[8px] font-bold text-ink-black uppercase`,children:`Journey Trail`}),(0,U.jsx)(`div`,{className:`font-sans text-[10px] text-trash-gray font-semibold`,children:`150 Curated nodes`})]})]}),(0,U.jsxs)(`button`,{onClick:o,className:`p-3 bg-purple-100 hover:bg-purple-200 border-[3px] border-ink-black text-left flex flex-col justify-between gadget-shadow active:translate-y-1 active:shadow-none transition-all cursor-pointer`,children:[(0,U.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,U.jsx)(y,{className:`w-4 h-4 text-purple-700`}),(0,U.jsx)(k,{className:`w-3 h-3 text-ink-black`})]}),(0,U.jsxs)(`div`,{className:`mt-2`,children:[(0,U.jsx)(`div`,{className:`font-arcade text-[8px] font-bold text-ink-black uppercase`,children:`Add Problem`}),(0,U.jsx)(`div`,{className:`font-sans text-[10px] text-trash-gray font-semibold`,children:`New LeetCode entry`})]})]}),(0,U.jsxs)(`button`,{onClick:()=>c?.(`companion`),className:`p-3 bg-yellow-100 hover:bg-yellow-200 border-[3px] border-ink-black text-left flex flex-col justify-between gadget-shadow active:translate-y-1 active:shadow-none transition-all cursor-pointer`,children:[(0,U.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,U.jsx)(`span`,{className:`material-symbols-outlined text-amber-600 text-lg`,children:`castle`}),(0,U.jsx)(k,{className:`w-3 h-3 text-ink-black`})]}),(0,U.jsxs)(`div`,{className:`mt-2`,children:[(0,U.jsx)(`div`,{className:`font-arcade text-[8px] font-bold text-ink-black uppercase`,children:`Princess Tower`}),(0,U.jsx)(`div`,{className:`font-sans text-[10px] text-trash-gray font-semibold`,children:`Visit Aurelia`})]})]}),(0,U.jsxs)(`button`,{onClick:()=>{i?i():c?.(`cardManager`)},className:`p-3 bg-cyan-100 hover:bg-cyan-200 border-[3px] border-ink-black text-left flex flex-col justify-between gadget-shadow active:translate-y-1 active:shadow-none transition-all cursor-pointer`,children:[(0,U.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,U.jsx)(S,{className:`w-4 h-4 text-cyan-700`}),(0,U.jsx)(k,{className:`w-3 h-3 text-ink-black`})]}),(0,U.jsxs)(`div`,{className:`mt-2`,children:[(0,U.jsx)(`div`,{className:`font-arcade text-[8px] font-bold text-ink-black uppercase`,children:`Card Manager`}),(0,U.jsx)(`div`,{className:`font-sans text-[10px] text-trash-gray font-semibold`,children:`Anki Deck Browser`})]})]})]})]}),l&&d&&(0,U.jsxs)(`button`,{onClick:d,className:`mt-3 bg-white hover:bg-slate-100 border-[3px] border-ink-black text-ink-black font-bold px-4 py-2 text-xs uppercase tracking-wide shadow-[3px_3px_0px_0px_rgba(30,41,59,1)] active:translate-y-0.5 active:shadow-none transition-all cursor-pointer inline-flex items-center gap-2`,children:[(0,U.jsx)(n,{className:`w-3.5 h-3.5`}),` Return to Scheduled Queue`]})]})}),Te=e({default:()=>De}),Ee=(0,H.lazy)(()=>L(()=>import(`./ProblemSpecPanel-BRW8UyO6.js`).then(e=>({default:e.ProblemSpecPanel})),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9])));function De({overrideProblemId:e,onClearOverride:t,onOpenWindow:r,onOpenJourney:i,onOpenCreateProblem:a,onOpenEditProblem:o,onOpenCardManager:c,refreshTrigger:l}){let[u,f]=(0,H.useState)(null),p=u!==null&&u<780,[h,g]=(0,H.useState)(`spec`),[_,y]=(0,H.useState)(`spec`),[b,x]=(0,H.useState)(null),S=(0,H.useCallback)(e=>{e&&(f(e.clientWidth),new ResizeObserver(e=>{for(let t of e)f(t.contentRect.width)}).observe(e))},[]),[w,T]=(0,H.useState)(()=>localStorage.getItem(`isAutocompleteEnabled`)!==`false`),{reviews:D,setReviews:O,loading:ee,queueError:k,submitting:A,submittingRating:j,gradeError:M,setGradeError:N,code:P,setCode:te,nextMilestone:I,activatingMilestone:L,fetchQueue:ie,handleGrade:R,handleSelectCard:z,handleActivateNextMilestone:B,handleResetStarterCode:V}=fe({overrideProblemId:e,refreshTrigger:l,onClearOverride:t}),{sandboxRunning:ae,sandboxResults:oe,sandboxError:se,savingReference:ce,savedRefSuccess:de,saveRefError:W,handleRunSandbox:ge,handleSaveReference:_e,resetSandbox:G}=pe(),{aiLoading:ve,aiResult:ye,aiError:be,explainLoading:K,explanationText:xe,explainError:Te,aiSolutionLoading:De,aiSolutionError:Oe,handleAiEvaluation:ke,handleExplainCode:Ae,handleFetchAiSolution:je,resetAiState:q}=me(),[Me,Ne]=(0,H.useState)(!1),[Pe,Fe]=(0,H.useState)(null),[Ie,J]=(0,H.useState)(null),Le=(0,H.useCallback)(async()=>{if(D.length===0)return;let e=D[0]?.problems||{},t=P.trim()||e.reference_code||``;if(!t){J(`Please write or save code before pushing to GitHub.`),setTimeout(()=>J(null),4e3);return}let n=re();if(!n.token){r&&r(`github`);return}Ne(!0),J(null),Fe(null);try{let r=await ne({token:n.token,repo:n.repoName,branch:n.branch,problem_number:e.problem_number,problem_name:e.name||`Algorithm Problem`,pattern:e.pattern||`Algorithms`,difficulty:e.difficulty||`Medium`,optimal_time:e.optimal_time||`O(N)`,optimal_space:e.optimal_space||`O(1)`,description:e.description||``,code:t});Fe(r.html_url),setTimeout(()=>Fe(null),8e3)}catch(e){J(e.message||`Failed to push solution to GitHub.`),setTimeout(()=>J(null),5e3)}finally{Ne(!1)}},[D,P,r]),Re=D[0]?.id||D[0]?.problem_id,ze=(0,H.useRef)(void 0);(0,H.useEffect)(()=>{Re&&ze.current!==Re&&(ze.current=Re,q(),G())},[Re,q,G]);let Y=(0,H.useCallback)(e=>{q(),G(),R(e)},[R,q,G]),Be=(0,H.useCallback)(e=>{q(),G(),z(e)},[z,q,G]);(0,H.useEffect)(()=>{let e=e=>{let t=e.target;t?.closest(`.cm-editor`)||t?.tagName===`INPUT`||t?.tagName===`TEXTAREA`||t?.isContentEditable||D.length===0||A||(e.key===`1`?(e.preventDefault(),Y(1)):e.key===`2`?(e.preventDefault(),Y(2)):e.key===`3`?(e.preventDefault(),Y(3)):e.key===`4`&&(e.preventDefault(),Y(4)))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[Y,D.length,A]);let Ve=(e,t)=>{navigator.clipboard.writeText(e),x(t),setTimeout(()=>x(null),1800)},He=(0,H.useCallback)(()=>{i?i():r?.(`journey`)},[i,r]),Ue=(0,H.useCallback)(()=>{a?a():r?.(`createProblem`)},[a,r]),We=(0,H.useCallback)(e=>{O(t=>{if(t.length===0)return t;let n=[...t],r=n[0];return r&&r.problems&&(r.problems={...r.problems,solutions:e}),n})},[O]);if(ee)return(0,U.jsx)(`div`,{className:`w-full h-full flex items-center justify-center bg-[#fdf8e1] text-ink-black`,children:(0,U.jsxs)(`div`,{className:`flex flex-col items-center gap-4 p-8 bg-paper-white border-[3px] border-ink-black gadget-shadow text-center max-w-xs`,children:[(0,U.jsx)(`div`,{className:`w-12 h-12 bg-amber-200 border-2 border-ink-black flex items-center justify-center animate-spin`,children:(0,U.jsx)(s,{className:`w-6 h-6 text-ink-black`})}),(0,U.jsxs)(`div`,{children:[(0,U.jsx)(`h3`,{className:`font-arcade text-xs text-ink-black uppercase tracking-wider font-bold`,children:`LOADING QUEUE`}),(0,U.jsx)(`p`,{className:`font-sans text-[11px] text-trash-gray mt-1 font-semibold`,children:`Fetching scheduled FSRS review cards...`})]})]})});if(k&&D.length===0)return(0,U.jsx)(`div`,{className:`w-full h-full flex items-center justify-center bg-[#fdf8e1] p-6 overflow-y-auto custom-scrollbar`,children:(0,U.jsxs)(`div`,{className:`w-full max-w-md bg-paper-white border-[4px] border-ink-black gadget-shadow p-6 sm:p-8 relative overflow-hidden text-center space-y-6`,children:[(0,U.jsx)(`div`,{className:`absolute top-0 left-0 right-0 h-3 bg-gradient-to-r from-red-500 via-amber-400 to-red-500`}),(0,U.jsxs)(`div`,{className:`relative inline-block mt-2`,children:[(0,U.jsx)(`div`,{className:`w-20 h-20 bg-rose-200 border-[3px] border-ink-black rounded-2xl flex items-center justify-center mx-auto gadget-shadow rotate-[-2deg]`,children:(0,U.jsx)(C,{className:`w-10 h-10 text-rose-700 stroke-[2.5]`})}),(0,U.jsx)(`div`,{className:`absolute -bottom-2 -right-2 bg-rose-500 text-white border-2 border-ink-black px-2 py-0.5 font-arcade text-[8px] font-bold uppercase shadow-[2px_2px_0px_0px_rgba(30,41,59,1)]`,children:`OFFLINE`})]}),(0,U.jsxs)(`div`,{className:`space-y-2`,children:[(0,U.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 px-2.5 py-1 bg-rose-100 border-2 border-ink-black text-rose-800 font-arcade text-[9px] font-bold`,children:[(0,U.jsx)(m,{className:`w-3.5 h-3.5 stroke-[2.5] text-rose-600`}),` CONNECTION ERROR`]}),(0,U.jsx)(`h2`,{className:`text-2xl sm:text-3xl font-extrabold text-ink-black font-headline-md tracking-tight`,children:`Queue Unavailable`}),(0,U.jsx)(`p`,{className:`font-sans text-xs sm:text-sm text-trash-gray font-semibold leading-relaxed max-w-sm mx-auto`,children:`Unable to reach the server to fetch your scheduled review cards. Check your connection or retry below.`})]}),(0,U.jsxs)(`div`,{className:`pt-2 flex flex-col sm:flex-row gap-3 justify-center items-center`,children:[(0,U.jsxs)(`button`,{onClick:()=>void ie(!0),className:`w-full sm:w-auto px-6 py-2.5 bg-amber-300 hover:bg-amber-400 border-[3px] border-ink-black font-arcade text-xs font-bold text-ink-black gadget-shadow active:translate-x-0.5 active:translate-y-0.5 active:shadow-none transition-all flex items-center justify-center gap-2 cursor-pointer`,children:[(0,U.jsx)(n,{className:`w-4 h-4`}),(0,U.jsx)(`span`,{children:`RETRY CONNECTION`})]}),(i||r)&&(0,U.jsx)(`button`,{onClick:He,className:`w-full sm:w-auto px-5 py-2.5 bg-paper-white hover:bg-warm-sand-bg border-[3px] border-ink-black font-arcade text-xs font-bold text-ink-black gadget-shadow active:translate-x-0.5 active:translate-y-0.5 active:shadow-none transition-all flex items-center justify-center gap-2 cursor-pointer`,children:(0,U.jsx)(`span`,{children:`OPEN JOURNEY MAP`})})]})]})});if(D.length===0)return(0,U.jsx)(we,{nextMilestone:I,activatingMilestone:L,onActivateNextMilestone:B,onOpenCardManager:c||(()=>r?.(`cardManager`)),onOpenJourney:He,onOpenCreateProblem:Ue,onOpenWindow:r,overrideProblemId:e,onClearOverride:t});let X=D[0],Z=X?.problems,Ge=Z?.problem_number??(/^\d+$/.test(X?.problem_id||``)?parseInt(X.problem_id,10):void 0),Q=F(Ge,Z?.id||X?.problem_id,Z?.name),{cleanTitle:Ke,approachVariant:qe,pattern:Je}=ue(Z?.name,Q?.name,Z?.pattern,Q?.pattern),$={...Q,...Z,id:Z?.id||Q?.id||X?.problem_id,name:Ke,problem_number:Z?.problem_number??Q?.problem_number,pattern:Je,approach_variant:qe,difficulty:Z?.difficulty||Q?.difficulty||`Medium`,reference_code:Z?.reference_code||Q?.reference_solution||``,starter_code:Q?.starter_code||Z?.starter_code||``,description:Z?.description||Q?.description||``,optimal_time:Z?.optimal_time||Q?.time_complexity||`O(N)`,optimal_space:Z?.optimal_space||Q?.space_complexity||`O(1)`,examples:Z?.examples&&Z.examples.length>0?Z.examples:Q?.examples,constraints:Z?.constraints||Q?.constraints,how_to_solve:Z?.how_to_solve||``,solutions:Z?.solutions&&Z.solutions.length>0?Z.solutions:Q?.solutions},Ye=le({...Q,...$,examples:$.examples&&$.examples.length>0?$.examples:Q?.examples,constraints:$.constraints&&(Array.isArray($.constraints)?$.constraints.length>0:$.constraints)?$.constraints:Q?.constraints}),Xe=Q?.reference_solution||``,Ze=Z?.reference_code||``,Qe=Ze&&(!Xe||Ze.trim()!==Xe.trim())?Ze:``,$e=Qe||Xe||Ze||``;return(0,U.jsxs)(`div`,{ref:S,className:`w-full h-full bg-[#fdf8e1] flex flex-col overflow-hidden select-none`,children:[(0,U.jsx)(he,{problem:$,totalInQueue:D.length,reviews:D,overrideProblemId:e,onSelectCard:Be,onOpenCreateProblem:Ue,onOpenEditProblem:()=>{o?o($):r?.(`editProblem`)}}),(0,U.jsxs)(`div`,{className:`${p?`flex`:`hidden`} shrink-0 bg-amber-100 border-b-[3px] border-ink-black px-2.5 sm:px-3 py-1.5 gap-1.5 sm:gap-2 overflow-x-auto no-scrollbar`,children:[(0,U.jsxs)(`button`,{onClick:()=>{y(`spec`),g(`spec`)},className:`px-2.5 sm:px-3 py-1 text-[9px] font-arcade font-bold border-2 border-ink-black transition-all cursor-pointer flex items-center gap-1.5 whitespace-nowrap ${_===`spec`?`bg-paper-white translate-y-0.5 shadow-none text-ink-black`:`bg-white shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] text-trash-gray`}`,children:[(0,U.jsx)(E,{className:`w-3 h-3 shrink-0`}),(0,U.jsx)(`span`,{children:`SPEC`})]}),(0,U.jsxs)(`button`,{onClick:()=>y(`code`),className:`px-2.5 sm:px-3 py-1 text-[9px] font-arcade font-bold border-2 border-ink-black transition-all cursor-pointer flex items-center gap-1.5 whitespace-nowrap ${_===`code`?`bg-paper-white translate-y-0.5 shadow-none text-ink-black`:`bg-white shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] text-trash-gray`}`,children:[(0,U.jsx)(v,{className:`w-3 h-3 shrink-0`}),(0,U.jsx)(`span`,{children:`CODE STUDIO`})]}),(0,U.jsxs)(`button`,{onClick:()=>{y(`ref`),g(`ref`)},className:`px-2.5 sm:px-3 py-1 text-[9px] font-arcade font-bold border-2 border-ink-black transition-all cursor-pointer flex items-center gap-1.5 whitespace-nowrap ${_===`ref`?`bg-paper-white translate-y-0.5 shadow-none text-ink-black`:`bg-white shadow-[2px_2px_0px_0px_rgba(30,41,59,1)] text-trash-gray`}`,children:[(0,U.jsx)(d,{className:`w-3 h-3 shrink-0`}),(0,U.jsx)(`span`,{children:`SOLUTION`})]})]}),(0,U.jsxs)(`div`,{className:`flex-1 flex ${p?`flex-col`:`flex-row`} overflow-hidden min-h-0`,children:[(0,U.jsx)(H.Suspense,{fallback:(0,U.jsx)(`div`,{className:`flex-1 flex flex-col items-center justify-center p-8 bg-paper-white ${p?`h-64`:`border-r-[4px] border-ink-black`} font-sans text-xs text-trash-gray select-none`,children:(0,U.jsxs)(`div`,{className:`flex items-center gap-2 font-arcade text-[10px] text-ink-black`,children:[(0,U.jsx)(s,{className:`w-4 h-4 animate-spin text-[#0ea5e9]`}),(0,U.jsx)(`span`,{children:`Loading Problem Spec...`})]})}),children:(0,U.jsx)(Ee,{leftTab:h,onSelectLeftTab:e=>{g(e),e===`ref`?y(`ref`):e===`spec`&&y(`spec`)},mobileView:_,isNarrow:p,problem:$,parsed:Ye,userSolution:Qe,officialSolution:Xe,effectiveReferenceCode:$e,copiedSnippet:b,onCopyText:Ve,saveRefError:W,aiSolutionLoading:De,aiSolutionError:Oe,onFetchAiSolution:()=>je(X,e=>{O(t=>t.map((t,n)=>n===0?{...t,problems:{...$||{},...t.problems||{},reference_code:e}}:t))}),explainLoading:K,explainError:Te,explanationText:xe,onExplainCode:(e,t,n,r)=>Ae(X,e,t,n,r),activeReview:X,onUpdateSolutions:We,onEditProblem:()=>{o?o($):r?.(`editProblem`)}})}),(0,U.jsx)(Se,{mobileView:_,isNarrow:p,isAutocompleteEnabled:w,onToggleAutocomplete:e=>{T(e),localStorage.setItem(`isAutocompleteEnabled`,String(e))},onResetStarterCode:V,code:P,onChangeCode:te,sandboxRunning:ae,sandboxError:se,sandboxResults:oe,onRunSandbox:()=>ge(X,P),savingReference:ce,savedRefSuccess:de,saveRefError:W,onSaveReference:()=>_e(X,P,(e,t)=>{O(n=>n.map((n,r)=>r===0?{...n,problem_id:t||n.problem_id,problems:{...$||{},...n.problems||{},id:t||n.problems?.id||n.problem_id,reference_code:e}}:n))}),aiLoading:ve,aiError:be,aiResult:ye,onAiEvaluation:()=>ke(X,P),optimalTime:$.optimal_time||`O(N)`,optimalSpace:$.optimal_space||`O(1)`,onPushToGitHub:Le,pushingToGitHub:Me,githubPushedUrl:Pe,githubPushError:Ie})]}),(0,U.jsx)(Ce,{gradeError:M,onDismissGradeError:()=>N(null),submitting:A,submittingRating:j,onGrade:Y})]})}export{De as default,de as n,Te as t};1import{r as e}from"./rolldown-runtime-hePW80VL.js";import{A as t,Bt as n,C as r,Ht as i,J as a,M as ee,O as o,X as s,_t as c,a as l,at as u,ct as d,d as te,et as f,ht as p,it as m,nt as h,rt as g,x as _}from"./vendor-react-hnaVBnLv.js";import{_ as v,d as ne,f as re,h as y,m as b,p as x}from"./index-DVWZ15xt.js";import{a as S,i as C,n as w,r as T,s as E,t as D}from"./githubSyncService-x0Mm_uEl.js";var O=e(i(),1),k=n(),A=[{id:`default`,name:`Default`,desc:`Subject to Availability`},{id:`groq`,name:`Groq`,badge:`Fastest`,desc:`Llama 3.3 & Qwen`,keyPrefix:`gsk_...`,portalUrl:`https://console.groq.com/keys`},{id:`gemini`,name:`Google Gemini`,desc:`Gemini 2.5 / 3.5`,keyPrefix:`AIzaSy...`,portalUrl:`https://aistudio.google.com/app/apikey`},{id:`openrouter`,name:`OpenRouter`,desc:`Multi-Provider`,keyPrefix:`sk-or-v1-...`,portalUrl:`https://openrouter.ai/keys`}];function j(){let[e,n]=(0,O.useState)(()=>localStorage.getItem(`algospaced_custom_ai_provider`)||`default`),[i,j]=(0,O.useState)(()=>localStorage.getItem(`algospaced_custom_api_key`)||localStorage.getItem(`sandbox_gemini_api_key`)||``),[M,ie]=(0,O.useState)(!1),[N,P]=(0,O.useState)(null),[F,I]=(0,O.useState)(()=>ne()),[L,R]=(0,O.useState)(null),[z,B]=(0,O.useState)(()=>re().currentFloor),[V,H]=(0,O.useState)(()=>T()),[U,W]=(0,O.useState)(()=>C()),[G,K]=(0,O.useState)(!1),[q,J]=(0,O.useState)(null),Y=!!(V.token&&(V.username||U?.login)),X=!!(i.trim()&&e!=="default"),Z=e!=="default"&&!i.trim(),Q=A.find(t=>t.id===e),ae=e=>{n(e),localStorage.setItem(`algospaced_custom_ai_provider`,e),P(e==="default"?{type:`info`,text:`Switched to Server Default (Shared Pool).`}:{type:`info`,text:`Switched to ${e.toUpperCase()}.`}),setTimeout(()=>P(null),3e3)},oe=()=>{let t=i.trim();if(!t){P({type:`error`,text:`Please enter an API key for ${e.toUpperCase()}.`}),setTimeout(()=>P(null),3e3);return}localStorage.setItem(`algospaced_custom_api_key`,t),localStorage.setItem(`sandbox_gemini_api_key`,t),localStorage.setItem(`algospaced_custom_ai_provider`,e),P({type:`success`,text:`${e.toUpperCase()} API key saved successfully.`}),setTimeout(()=>P(null),3e3)},$=()=>{localStorage.removeItem(`algospaced_custom_api_key`),localStorage.removeItem(`sandbox_gemini_api_key`),j(``),P({type:`info`,text:`Cleared custom API key.`}),setTimeout(()=>P(null),3e3)},se=()=>{localStorage.removeItem(`algospaced_custom_api_key`),localStorage.removeItem(`sandbox_gemini_api_key`),localStorage.setItem(`algospaced_custom_ai_provider`,`default`),j(``),n(`default`),P({type:`info`,text:`Reset to Server Default provider.`}),setTimeout(()=>P(null),3e3)},ce=()=>{b(F),R({type:`success`,text:`Princess Companion settings saved!`}),setTimeout(()=>R(null),3e3)},le=()=>{I(y),b(y),R({type:`info`,text:`Reset companion to default settings.`}),setTimeout(()=>R(null),3e3)},ue=()=>{if(window.confirm(`Are you sure you want to reset your Spire Journey progress back to 0 problems?`)){let e=x();B(e.currentFloor),R({type:`info`,text:`Spire journey progress reset to 0 problems.`}),setTimeout(()=>R(null),3e3)}},de=async()=>{K(!0),J(null);try{let{token:e,user:t}=await w();W(t);let n=T();H(n);try{await S(e,n.repoName,n.isPrivate)}catch{}J({type:`success`,text:`Connected to GitHub as @${t.login}!`}),setTimeout(()=>J(null),4e3)}catch(e){J({type:`error`,text:e.message||`GitHub connection failed.`}),setTimeout(()=>J(null),5e3)}finally{K(!1)}},fe=()=>{D(),H(T()),W(null),J({type:`info`,text:`Disconnected from GitHub.`}),setTimeout(()=>J(null),3e3)},pe=e=>{E({autoCommit:e}),H(t=>({...t,autoCommit:e})),J({type:`info`,text:e?`Auto-commit enabled for review submissions.`:`Auto-commit disabled.`}),setTimeout(()=>J(null),3e3)};return(0,k.jsxs)(`div`,{className:`w-full h-full bg-[#fdf8e1] p-5 sm:p-6 flex flex-col gap-4 select-none font-sans text-ink-black overflow-y-auto custom-scrollbar`,children:[(0,k.jsxs)(`div`,{className:`flex flex-col gap-0.5 border-b-[3px] border-ink-black pb-2.5`,children:[(0,k.jsxs)(`h3`,{className:`font-headline-md font-bold text-sm m-0 flex items-center gap-2 tracking-wide`,children:[(0,k.jsx)(a,{className:`w-4 h-4 text-ink-black`}),`API & AI Configuration`]}),(0,k.jsx)(`p`,{className:`text-[11px] text-trash-gray font-medium m-0`,children:`Configure your AI model provider..`})]}),(0,k.jsx)(`div`,{className:`px-4 py-3 border-[3px] border-ink-black shadow-[3px_3px_0px_0px_rgba(30,41,59,1)] transition-all ${X?`bg-emerald-50`:Z?`bg-rose-50`:`bg-amber-50/70`}`,children:(0,k.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,k.jsxs)(`div`,{className:`flex items-center gap-2.5`,children:[X?(0,k.jsx)(l,{className:`w-4 h-4 text-emerald-600 shrink-0`}):Z?(0,k.jsx)(c,{className:`w-4 h-4 text-rose-600 shrink-0`}):(0,k.jsx)(u,{className:`w-4 h-4 text-amber-600 shrink-0`}),(0,k.jsxs)(`div`,{children:[(0,k.jsx)(`div`,{className:`text-xs font-bold font-headline-md text-ink-black flex items-center gap-1.5`,children:(0,k.jsxs)(`span`,{children:[`Active:`,` `,X?`${e.toUpperCase()} (Custom Key)`:Z?`${e.toUpperCase()} (Key Required)`:`Default`]})}),(0,k.jsx)(`div`,{className:`text-[10px] text-trash-gray font-medium`,children:X?`Requests are routed directly through your personal API key.`:Z?`Enter your API key below to activate this provider.`:`Using basic, free built-in developer keys with auto-failover.`})]})]}),(0,k.jsx)(`span`,{className:`px-2 py-0.5 text-[9px] font-bold font-arcade uppercase border-2 border-ink-black shrink-0 ${X?`bg-emerald-300 text-emerald-950`:Z?`bg-rose-300 text-rose-950`:`bg-amber-200 text-amber-950`}`,children:X?`ACTIVE`:Z?`NEEDS KEY`:`LIMITED`})]})}),(0,k.jsxs)(`div`,{className:`bg-white border-[3px] border-ink-black p-4 sm:p-5 shadow-[4px_4px_0px_0px_rgba(30,41,59,1)] flex flex-col gap-4`,children:[(0,k.jsxs)(`div`,{children:[(0,k.jsxs)(`label`,{className:`block text-xs font-bold text-ink-black uppercase tracking-wider mb-2 font-headline-md flex items-center gap-1.5`,children:[(0,k.jsx)(u,{className:`w-3.5 h-3.5 text-ink-black`}),`Select Provider`]}),(0,k.jsx)(`div`,{className:`grid grid-cols-2 sm:grid-cols-4 gap-2`,children:A.map(t=>{let n=e===t.id;return(0,k.jsxs)(`button`,{type:`button`,onClick:()=>ae(t.id),className:`p-2.5 border-[2px] text-left transition-all cursor-pointer flex flex-col justify-between rounded ${n?`border-ink-black bg-[#ffe24c] shadow-[2px_2px_0px_0px_#1E293B] font-bold`:`border-slate-300 bg-slate-50 hover:bg-slate-100 text-slate-700`}`,children:[(0,k.jsxs)(`div`,{className:`flex items-center justify-between w-full`,children:[(0,k.jsx)(`span`,{className:`text-xs font-bold font-headline-md`,children:t.name}),t.badge&&(0,k.jsx)(`span`,{className:`text-[8px] font-bold uppercase px-1 py-0.2 bg-orange-100 text-orange-700 rounded border border-orange-300`,children:t.badge})]}),(0,k.jsx)(`span`,{className:`text-[9px] mt-1 text-slate-600 leading-tight block`,children:t.desc})]},t.id)})})]}),e==="default"?(0,k.jsxs)(`div`,{className:`p-3.5 bg-slate-50 border border-slate-200 rounded flex items-start gap-3`,children:[(0,k.jsx)(te,{className:`w-4 h-4 text-amber-500 shrink-0 mt-0.5`}),(0,k.jsxs)(`div`,{className:`flex flex-col gap-1 text-xs text-slate-700`,children:[(0,k.jsxs)(`span`,{className:`font-bold text-ink-black`,children:[`Shared Quotas (`,(0,k.jsx)(`i`,{children:`limited`}),`)`]}),(0,k.jsx)(`p`,{className:`text-[11px] text-trash-gray m-0 leading-relaxed`,children:`Powered by shared, basic developer keys. Because limits are shared with everyone, requests may fail. Use your own provider keys above for stable performance.`})]})]}):(0,k.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,k.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,k.jsxs)(`label`,{className:`block text-xs font-bold text-ink-black uppercase tracking-wider font-headline-md flex items-center gap-1.5`,children:[(0,k.jsx)(a,{className:`w-3.5 h-3.5 text-ink-black`}),Q?.name,` API Key`]}),Q?.portalUrl&&(0,k.jsxs)(`a`,{href:Q.portalUrl,target:`_blank`,rel:`noopener noreferrer`,className:`text-[10px] text-sky-600 hover:text-sky-800 font-medium flex items-center gap-1 no-underline`,children:[(0,k.jsx)(`span`,{children:`Get API Key`}),(0,k.jsx)(m,{className:`w-3 h-3`})]})]}),(0,k.jsxs)(`div`,{className:`relative`,children:[(0,k.jsx)(`input`,{type:M?`text`:`password`,value:i,onChange:e=>j(e.target.value),placeholder:`Enter ${Q?.keyPrefix||`API Key`}`,className:`w-full bg-white border-[2px] border-ink-black rounded py-2 pl-3 pr-9 text-ink-black placeholder-slate-400 focus:outline-none focus:border-sky-600 text-xs font-code-mono`}),(0,k.jsx)(`button`,{type:`button`,onClick:()=>ie(!M),className:`absolute right-2.5 top-1/2 -translate-y-1/2 text-trash-gray hover:text-ink-black cursor-pointer bg-transparent border-0 outline-none p-1`,title:M?`Hide API key`:`Show API key`,children:M?(0,k.jsx)(g,{className:`w-3.5 h-3.5`}):(0,k.jsx)(h,{className:`w-3.5 h-3.5`})})]}),(0,k.jsxs)(`div`,{className:`flex items-center gap-1.5 text-[10px] text-trash-gray font-medium`,children:[(0,k.jsx)(r,{className:`w-3.5 h-3.5 text-emerald-600 shrink-0`}),(0,k.jsx)(`span`,{children:`Stored locally in your browser. Sent directly via request headers.`})]}),(0,k.jsxs)(`div`,{className:`flex gap-2 pt-1`,children:[(0,k.jsxs)(`button`,{onClick:oe,className:`flex-1 flex items-center justify-center gap-1.5 py-2 border-[2px] border-ink-black bg-[#ffe24c] hover:bg-yellow-300 text-xs font-bold text-ink-black shadow-[2px_2px_0px_0px_#1E293B] active:translate-y-0.5 active:shadow-none transition-all cursor-pointer rounded uppercase`,children:[(0,k.jsx)(o,{className:`w-3.5 h-3.5`}),`Save Key`]}),i&&(0,k.jsx)(`button`,{onClick:$,className:`px-3 py-2 border-[2px] border-slate-300 bg-white hover:bg-slate-50 text-xs font-bold text-slate-700 hover:text-rose-600 shadow-[2px_2px_0px_0px_rgba(0,0,0,0.05)] active:translate-y-0.5 active:shadow-none transition-all cursor-pointer rounded uppercase`,children:`Clear Key`})]})]}),N&&(0,k.jsxs)(`div`,{className:`p-2.5 border-[2px] border-ink-black text-xs font-medium rounded flex items-center gap-2 ${N.type===`success`?`bg-emerald-100 border-emerald-600 text-emerald-900`:N.type===`error`?`bg-rose-100 border-rose-600 text-rose-900`:`bg-sky-100 border-sky-600 text-sky-900`}`,children:[N.type===`success`?(0,k.jsx)(p,{className:`w-3.5 h-3.5 shrink-0`}):N.type===`error`?(0,k.jsx)(c,{className:`w-3.5 h-3.5 shrink-0`}):(0,k.jsx)(s,{className:`w-3.5 h-3.5 shrink-0`}),N.text]}),e!=="default"&&(0,k.jsx)(`div`,{className:`pt-2 border-t border-slate-200 flex justify-end`,children:(0,k.jsxs)(`button`,{onClick:se,className:`flex items-center gap-1.5 py-1.5 px-3 border border-slate-300 bg-slate-50 hover:bg-slate-100 text-[11px] font-bold text-slate-600 hover:text-ink-black transition-all cursor-pointer rounded`,children:[(0,k.jsx)(t,{className:`w-3 h-3 text-slate-500`}),`Reset to Server Default`]})})]}),(0,k.jsxs)(`div`,{className:`bg-white border-[3px] border-ink-black p-4 sm:p-5 shadow-[4px_4px_0px_0px_rgba(30,41,59,1)] flex flex-col gap-4`,children:[(0,k.jsxs)(`div`,{className:`flex items-center justify-between border-b-[2px] border-ink-black pb-3`,children:[(0,k.jsxs)(`div`,{className:`flex items-center gap-2.5`,children:[(0,k.jsx)(`div`,{className:`w-8 h-8 rounded bg-[#24292e] border-[2px] border-ink-black flex items-center justify-center text-white shadow-[1px_1px_0px_0px_#1E293B]`,children:(0,k.jsx)(f,{className:`w-4 h-4 text-white`})}),(0,k.jsxs)(`div`,{children:[(0,k.jsx)(`h4`,{className:`font-headline-md font-bold text-xs uppercase text-ink-black m-0 flex items-center gap-2`,children:`GitHub Solutions Sync & Auto-Commit`}),(0,k.jsx)(`p`,{className:`text-[10px] text-trash-gray font-medium m-0`,children:`Sync solutions to personal GitHub repository and commit automatically on submission`})]})]}),(0,k.jsx)(`span`,{className:`px-2 py-0.5 text-[9px] font-bold font-arcade uppercase border-2 border-ink-black shrink-0 ${Y?`bg-emerald-300 text-emerald-950`:`bg-slate-200 text-slate-800`}`,children:Y?`CONNECTED`:`DISCONNECTED`})]}),Y?(0,k.jsxs)(`div`,{className:`space-y-3`,children:[(0,k.jsxs)(`div`,{className:`flex flex-col sm:flex-row sm:items-center justify-between gap-2 p-3 bg-slate-50 border border-slate-200 rounded`,children:[(0,k.jsxs)(`div`,{className:`flex items-center gap-2.5`,children:[U?.avatar_url&&(0,k.jsx)(`img`,{src:U.avatar_url,alt:U.login,className:`w-7 h-7 rounded-full border border-ink-black`}),(0,k.jsxs)(`div`,{children:[(0,k.jsxs)(`span`,{className:`text-xs font-bold text-ink-black`,children:[`@`,U?.login||V.username]}),(0,k.jsxs)(`span`,{className:`text-[11px] text-slate-600 font-mono block`,children:[V.username,`/`,V.repoName,` (`,V.branch,`)`]})]})]}),(0,k.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,k.jsxs)(`a`,{href:`https://github.com/${V.username}/${V.repoName}`,target:`_blank`,rel:`noopener noreferrer`,className:`px-2.5 py-1 text-[11px] font-bold bg-white hover:bg-slate-100 text-ink-black border border-slate-300 rounded no-underline flex items-center gap-1 cursor-pointer`,children:[(0,k.jsx)(m,{className:`w-3 h-3`}),(0,k.jsx)(`span`,{children:`View Repo`})]}),(0,k.jsx)(`button`,{type:`button`,onClick:fe,className:`px-2.5 py-1 text-[11px] font-bold bg-white hover:bg-rose-50 text-rose-700 border border-rose-300 rounded cursor-pointer`,children:`Disconnect`})]})]}),(0,k.jsxs)(`label`,{className:`flex items-center gap-2.5 p-2.5 bg-emerald-50/50 border border-emerald-300 rounded cursor-pointer`,children:[(0,k.jsx)(`input`,{type:`checkbox`,checked:V.autoCommit,onChange:e=>pe(e.target.checked),className:`w-4 h-4 accent-emerald-600 cursor-pointer`}),(0,k.jsxs)(`div`,{className:`text-xs`,children:[(0,k.jsx)(`span`,{className:`font-bold text-ink-black block`,children:`Auto-commit on every submission`}),(0,k.jsxs)(`span`,{className:`text-[10px] text-trash-gray`,children:[`Automatically pushes your code to `,V.repoName,` whenever you grade a review card.`]})]})]})]}):(0,k.jsxs)(`div`,{className:`flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 p-3.5 bg-slate-50 border border-slate-200 rounded`,children:[(0,k.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,k.jsx)(`span`,{className:`text-xs font-bold text-ink-black block`,children:`Connect your GitHub Account (1-Click OAuth)`}),(0,k.jsx)(`p`,{className:`text-[11px] text-trash-gray m-0`,children:`Grant repository access to automatically sync your DSA problem solutions as you study.`})]}),(0,k.jsx)(`button`,{type:`button`,onClick:de,disabled:G,className:`px-4 py-2 bg-[#24292e] hover:bg-black text-white text-xs font-bold uppercase rounded border-2 border-ink-black shadow-[2px_2px_0px_0px_#1E293B] active:translate-y-0.5 active:shadow-none flex items-center gap-2 shrink-0 cursor-pointer disabled:opacity-50`,children:G?(0,k.jsxs)(k.Fragment,{children:[(0,k.jsx)(ee,{className:`w-3.5 h-3.5 animate-spin`}),(0,k.jsx)(`span`,{children:`CONNECTING...`})]}):(0,k.jsxs)(k.Fragment,{children:[(0,k.jsx)(f,{className:`w-3.5 h-3.5 text-yellow-300`}),(0,k.jsx)(`span`,{children:`CONNECT GITHUB`})]})})]}),q&&(0,k.jsxs)(`div`,{className:`p-2.5 border-[2px] border-ink-black text-xs font-medium rounded flex items-center gap-2 ${q.type===`success`?`bg-emerald-100 border-emerald-600 text-emerald-900`:q.type===`error`?`bg-rose-100 border-rose-600 text-rose-900`:`bg-sky-100 border-sky-600 text-sky-900`}`,children:[q.type===`success`?(0,k.jsx)(p,{className:`w-3.5 h-3.5 shrink-0`}):q.type===`error`?(0,k.jsx)(c,{className:`w-3.5 h-3.5 shrink-0`}):(0,k.jsx)(s,{className:`w-3.5 h-3.5 shrink-0`}),q.text]})]}),(0,k.jsxs)(`div`,{className:`bg-[#FFFDF0] border-[3px] border-ink-black p-4 sm:p-5 shadow-[4px_4px_0px_0px_rgba(30,41,59,1)] flex flex-col gap-4`,children:[(0,k.jsxs)(`div`,{className:`flex items-center justify-between border-b-[2px] border-ink-black pb-3`,children:[(0,k.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,k.jsx)(`div`,{className:`w-7 h-7 rounded bg-[#FFE24C] border-[2px] border-ink-black flex items-center justify-center shadow-[1px_1px_0px_0px_#1E293B]`,children:(0,k.jsx)(_,{className:`w-4 h-4 text-ink-black`})}),(0,k.jsxs)(`div`,{children:[(0,k.jsx)(`h4`,{className:`font-headline-md font-bold text-xs uppercase text-ink-black m-0`,children:`Princess AI Companion & RPG Settings`}),(0,k.jsx)(`p`,{className:`text-[10px] text-trash-gray font-medium m-0`,children:`Trapped Princess Persona, Study Break Timer & 8-bit RPG Audio`})]})]}),(0,k.jsxs)(`label`,{className:`flex items-center gap-2 cursor-pointer`,children:[(0,k.jsx)(`span`,{className:`text-[11px] font-bold text-ink-black font-headline-md uppercase`,children:F.enabled?`Enabled`:`Disabled`}),(0,k.jsx)(`input`,{type:`checkbox`,checked:F.enabled,onChange:e=>I(t=>({...t,enabled:e.target.checked})),className:`w-4 h-4 accent-amber-500 cursor-pointer`})]})]}),(0,k.jsxs)(`div`,{className:`grid grid-cols-1 md:grid-cols-2 gap-4`,children:[(0,k.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,k.jsx)(`label`,{className:`block text-xs font-bold text-ink-black uppercase tracking-wider font-headline-md`,children:`Companion Name`}),(0,k.jsx)(`input`,{type:`text`,value:F.name,onChange:e=>I(t=>({...t,name:e.target.value})),placeholder:`e.g. Princess Aurelia`,className:`bg-white border-[2px] border-ink-black rounded py-2 px-3 text-ink-black text-xs font-sans font-medium focus:outline-none focus:border-amber-600`})]}),(0,k.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,k.jsxs)(`label`,{className:`block text-xs font-bold text-ink-black uppercase tracking-wider font-headline-md flex items-center gap-1`,children:[(0,k.jsx)(d,{className:`w-3.5 h-3.5 text-amber-700`}),`Study Break Reminder`]}),(0,k.jsxs)(`select`,{value:F.breakIntervalMinutes,onChange:e=>I(t=>({...t,breakIntervalMinutes:Number(e.target.value)})),className:`bg-white border-[2px] border-ink-black rounded py-2 px-3 text-ink-black text-xs font-sans font-medium focus:outline-none focus:border-amber-600 cursor-pointer`,children:[(0,k.jsx)(`option`,{value:25,children:`Every 25 Minutes (Classic Pomodoro)`}),(0,k.jsx)(`option`,{value:45,children:`Every 45 Minutes`}),(0,k.jsx)(`option`,{value:60,children:`Every 60 Minutes`}),(0,k.jsx)(`option`,{value:0,children:`Disabled (No automatic break popups)`})]})]})]}),(0,k.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,k.jsx)(`label`,{className:`block text-xs font-bold text-ink-black uppercase tracking-wider font-headline-md`,children:`Princess Backstory & Persona Prompt`}),(0,k.jsx)(`textarea`,{rows:2,value:F.backstory,onChange:e=>I(t=>({...t,backstory:e.target.value})),placeholder:`Describe her background, tone, and connection to your DSA studies...`,className:`bg-white border-[2px] border-ink-black rounded p-2.5 text-ink-black text-xs font-sans font-medium focus:outline-none focus:border-amber-600 resize-y`})]}),(0,k.jsxs)(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3 pt-1`,children:[(0,k.jsxs)(`label`,{className:`flex items-center gap-2.5 p-2.5 bg-white border border-slate-300 rounded cursor-pointer hover:border-ink-black transition-all`,children:[(0,k.jsx)(`input`,{type:`checkbox`,checked:F.soundEnabled,onChange:e=>{let t=e.target.checked;I(e=>({...e,soundEnabled:t})),v(!t)},className:`w-4 h-4 accent-amber-500 cursor-pointer`}),(0,k.jsxs)(`div`,{className:`text-xs`,children:[(0,k.jsx)(`span`,{className:`font-bold text-ink-black block`,children:`8-bit Sound Effects`}),(0,k.jsx)(`span`,{className:`text-[10px] text-trash-gray`,children:`Audio chimes & fanfare`})]})]}),(0,k.jsxs)(`label`,{className:`flex items-center gap-2.5 p-2.5 bg-white border border-slate-300 rounded cursor-pointer hover:border-ink-black transition-all`,children:[(0,k.jsx)(`input`,{type:`checkbox`,checked:F.autoPopupEnabled,onChange:e=>I(t=>({...t,autoPopupEnabled:e.target.checked})),className:`w-4 h-4 accent-amber-500 cursor-pointer`}),(0,k.jsxs)(`div`,{className:`text-xs`,children:[(0,k.jsx)(`span`,{className:`font-bold text-ink-black block`,children:`Spontaneous RPG Popups`}),(0,k.jsx)(`span`,{className:`text-[10px] text-trash-gray`,children:`Speech bubbles for breaks & milestones`})]})]})]}),(0,k.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2 pt-2 border-t border-slate-200`,children:[(0,k.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,k.jsxs)(`button`,{type:`button`,onClick:ce,className:`flex items-center gap-1.5 py-2 px-4 border-[2px] border-ink-black bg-[#ffe24c] hover:bg-yellow-300 text-xs font-bold text-ink-black shadow-[2px_2px_0px_0px_#1E293B] active:translate-y-0.5 active:shadow-none transition-all cursor-pointer rounded uppercase`,children:[(0,k.jsx)(o,{className:`w-3.5 h-3.5`}),`Save Companion Settings`]}),(0,k.jsx)(`button`,{type:`button`,onClick:le,className:`py-2 px-3 border border-slate-300 bg-white hover:bg-slate-50 text-xs font-bold text-slate-700 transition-all cursor-pointer rounded`,children:`Default Persona`})]}),(0,k.jsxs)(`button`,{type:`button`,onClick:ue,className:`flex items-center gap-1 py-1.5 px-3 border border-rose-300 bg-rose-50 hover:bg-rose-100 text-rose-700 text-[11px] font-bold transition-all cursor-pointer rounded`,children:[(0,k.jsx)(t,{className:`w-3 h-3 text-rose-500`}),(0,k.jsxs)(`span`,{children:[`Reset Journey (`,z,`/150 LC)`]})]})]}),L&&(0,k.jsxs)(`div`,{className:`p-2.5 border-[2px] border-ink-black text-xs font-medium rounded flex items-center gap-2 ${L.type===`success`?`bg-emerald-100 border-emerald-600 text-emerald-900`:`bg-sky-100 border-sky-600 text-sky-900`}`,children:[(0,k.jsx)(p,{className:`w-3.5 h-3.5 shrink-0`}),L.text]})]}),(0,k.jsxs)(`div`,{className:`bg-white border-[3px] border-ink-black p-4 shadow-[4px_4px_0px_0px_rgba(30,41,59,1)] flex flex-col gap-2.5`,children:[(0,k.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,k.jsx)(s,{className:`w-3.5 h-3.5 text-[#0ea5e9]`}),(0,k.jsx)(`h4`,{className:`text-xs font-bold uppercase font-headline-md m-0`,children:`Get Free API Keys`})]}),(0,k.jsxs)(`div`,{className:`grid grid-cols-1 md:grid-cols-3 gap-2 text-[10px]`,children:[(0,k.jsxs)(`a`,{href:`https://console.groq.com/keys`,target:`_blank`,rel:`noopener noreferrer`,className:`p-2.5 border border-slate-200 hover:border-ink-black hover:bg-slate-50 rounded flex flex-col justify-between gap-1 transition-all no-underline text-inherit cursor-pointer`,children:[(0,k.jsxs)(`div`,{className:`flex items-center justify-between font-bold text-ink-black`,children:[(0,k.jsx)(`span`,{children:`Groq Cloud`}),(0,k.jsx)(m,{className:`w-3 h-3 text-slate-400`})]}),(0,k.jsx)(`p`,{className:`m-0 text-trash-gray leading-normal`,children:`Fast inference with generous free rate limits.`})]}),(0,k.jsxs)(`a`,{href:`https://aistudio.google.com/app/apikey`,target:`_blank`,rel:`noopener noreferrer`,className:`p-2.5 border border-slate-200 hover:border-ink-black hover:bg-slate-50 rounded flex flex-col justify-between gap-1 transition-all no-underline text-inherit cursor-pointer`,children:[(0,k.jsxs)(`div`,{className:`flex items-center justify-between font-bold text-ink-black`,children:[(0,k.jsx)(`span`,{children:`Google AI Studio`}),(0,k.jsx)(m,{className:`w-3 h-3 text-slate-400`})]}),(0,k.jsx)(`p`,{className:`m-0 text-trash-gray leading-normal`,children:`Free Gemini Flash API quota.`})]}),(0,k.jsxs)(`a`,{href:`https://openrouter.ai/keys`,target:`_blank`,rel:`noopener noreferrer`,className:`p-2.5 border border-slate-200 hover:border-ink-black hover:bg-slate-50 rounded flex flex-col justify-between gap-1 transition-all no-underline text-inherit cursor-pointer`,children:[(0,k.jsxs)(`div`,{className:`flex items-center justify-between font-bold text-ink-black`,children:[(0,k.jsx)(`span`,{children:`OpenRouter`}),(0,k.jsx)(m,{className:`w-3 h-3 text-slate-400`})]}),(0,k.jsx)(`p`,{className:`m-0 text-trash-gray leading-normal`,children:`Unified API for open-weights models.`})]})]})]})]})}export{j as default};1import{r as e}from"./rolldown-runtime-hePW80VL.js";import{A as t,Bt as n,C as r,Ht as i,J as a,M as ee,O as o,X as s,_t as c,a as l,at as u,ct as d,d as te,et as f,ht as p,it as m,nt as h,rt as g,x as _}from"./vendor-react-hnaVBnLv.js";import{_ as v,d as ne,f as re,h as y,m as b,p as x}from"./index-Q9onQHft.js";import{a as S,i as C,n as w,r as T,s as E,t as D}from"./githubSyncService-x0Mm_uEl.js";var O=e(i(),1),k=n(),A=[{id:`default`,name:`Default`,desc:`Subject to Availability`},{id:`groq`,name:`Groq`,badge:`Fastest`,desc:`Llama 3.3 & Qwen`,keyPrefix:`gsk_...`,portalUrl:`https://console.groq.com/keys`},{id:`gemini`,name:`Google Gemini`,desc:`Gemini 2.5 / 3.5`,keyPrefix:`AIzaSy...`,portalUrl:`https://aistudio.google.com/app/apikey`},{id:`openrouter`,name:`OpenRouter`,desc:`Multi-Provider`,keyPrefix:`sk-or-v1-...`,portalUrl:`https://openrouter.ai/keys`}];function j(){let[e,n]=(0,O.useState)(()=>localStorage.getItem(`algospaced_custom_ai_provider`)||`default`),[i,j]=(0,O.useState)(()=>localStorage.getItem(`algospaced_custom_api_key`)||localStorage.getItem(`sandbox_gemini_api_key`)||``),[M,ie]=(0,O.useState)(!1),[N,P]=(0,O.useState)(null),[F,I]=(0,O.useState)(()=>ne()),[L,R]=(0,O.useState)(null),[z,B]=(0,O.useState)(()=>re().currentFloor),[V,H]=(0,O.useState)(()=>T()),[U,W]=(0,O.useState)(()=>C()),[G,K]=(0,O.useState)(!1),[q,J]=(0,O.useState)(null),Y=!!(V.token&&(V.username||U?.login)),X=!!(i.trim()&&e!=="default"),Z=e!=="default"&&!i.trim(),Q=A.find(t=>t.id===e),ae=e=>{n(e),localStorage.setItem(`algospaced_custom_ai_provider`,e),P(e==="default"?{type:`info`,text:`Switched to Server Default (Shared Pool).`}:{type:`info`,text:`Switched to ${e.toUpperCase()}.`}),setTimeout(()=>P(null),3e3)},oe=()=>{let t=i.trim();if(!t){P({type:`error`,text:`Please enter an API key for ${e.toUpperCase()}.`}),setTimeout(()=>P(null),3e3);return}localStorage.setItem(`algospaced_custom_api_key`,t),localStorage.setItem(`sandbox_gemini_api_key`,t),localStorage.setItem(`algospaced_custom_ai_provider`,e),P({type:`success`,text:`${e.toUpperCase()} API key saved successfully.`}),setTimeout(()=>P(null),3e3)},$=()=>{localStorage.removeItem(`algospaced_custom_api_key`),localStorage.removeItem(`sandbox_gemini_api_key`),j(``),P({type:`info`,text:`Cleared custom API key.`}),setTimeout(()=>P(null),3e3)},se=()=>{localStorage.removeItem(`algospaced_custom_api_key`),localStorage.removeItem(`sandbox_gemini_api_key`),localStorage.setItem(`algospaced_custom_ai_provider`,`default`),j(``),n(`default`),P({type:`info`,text:`Reset to Server Default provider.`}),setTimeout(()=>P(null),3e3)},ce=()=>{b(F),R({type:`success`,text:`Princess Companion settings saved!`}),setTimeout(()=>R(null),3e3)},le=()=>{I(y),b(y),R({type:`info`,text:`Reset companion to default settings.`}),setTimeout(()=>R(null),3e3)},ue=()=>{if(window.confirm(`Are you sure you want to reset your journey progress back to 0 leagues?`)){let e=x();B(e.currentFloor),R({type:`info`,text:`Journey progress reset to 0 leagues.`}),setTimeout(()=>R(null),3e3)}},de=async()=>{K(!0),J(null);try{let{token:e,user:t}=await w();W(t);let n=T();H(n);try{await S(e,n.repoName,n.isPrivate)}catch{}J({type:`success`,text:`Connected to GitHub as @${t.login}!`}),setTimeout(()=>J(null),4e3)}catch(e){J({type:`error`,text:e.message||`GitHub connection failed.`}),setTimeout(()=>J(null),5e3)}finally{K(!1)}},fe=()=>{D(),H(T()),W(null),J({type:`info`,text:`Disconnected from GitHub.`}),setTimeout(()=>J(null),3e3)},pe=e=>{E({autoCommit:e}),H(t=>({...t,autoCommit:e})),J({type:`info`,text:e?`Auto-commit enabled for review submissions.`:`Auto-commit disabled.`}),setTimeout(()=>J(null),3e3)};return(0,k.jsxs)(`div`,{className:`w-full h-full bg-[#fdf8e1] p-5 sm:p-6 flex flex-col gap-4 select-none font-sans text-ink-black overflow-y-auto custom-scrollbar`,children:[(0,k.jsxs)(`div`,{className:`flex flex-col gap-0.5 border-b-[3px] border-ink-black pb-2.5`,children:[(0,k.jsxs)(`h3`,{className:`font-headline-md font-bold text-sm m-0 flex items-center gap-2 tracking-wide`,children:[(0,k.jsx)(a,{className:`w-4 h-4 text-ink-black`}),`API & AI Configuration`]}),(0,k.jsx)(`p`,{className:`text-[11px] text-trash-gray font-medium m-0`,children:`Configure your AI model provider..`})]}),(0,k.jsx)(`div`,{className:`px-4 py-3 border-[3px] border-ink-black shadow-[3px_3px_0px_0px_rgba(30,41,59,1)] transition-all ${X?`bg-emerald-50`:Z?`bg-rose-50`:`bg-amber-50/70`}`,children:(0,k.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,k.jsxs)(`div`,{className:`flex items-center gap-2.5`,children:[X?(0,k.jsx)(l,{className:`w-4 h-4 text-emerald-600 shrink-0`}):Z?(0,k.jsx)(c,{className:`w-4 h-4 text-rose-600 shrink-0`}):(0,k.jsx)(u,{className:`w-4 h-4 text-amber-600 shrink-0`}),(0,k.jsxs)(`div`,{children:[(0,k.jsx)(`div`,{className:`text-xs font-bold font-headline-md text-ink-black flex items-center gap-1.5`,children:(0,k.jsxs)(`span`,{children:[`Active:`,` `,X?`${e.toUpperCase()} (Custom Key)`:Z?`${e.toUpperCase()} (Key Required)`:`Default`]})}),(0,k.jsx)(`div`,{className:`text-[10px] text-trash-gray font-medium`,children:X?`Requests are routed directly through your personal API key.`:Z?`Enter your API key below to activate this provider.`:`Using basic, free built-in developer keys with auto-failover.`})]})]}),(0,k.jsx)(`span`,{className:`px-2 py-0.5 text-[9px] font-bold font-arcade uppercase border-2 border-ink-black shrink-0 ${X?`bg-emerald-300 text-emerald-950`:Z?`bg-rose-300 text-rose-950`:`bg-amber-200 text-amber-950`}`,children:X?`ACTIVE`:Z?`NEEDS KEY`:`LIMITED`})]})}),(0,k.jsxs)(`div`,{className:`bg-white border-[3px] border-ink-black p-4 sm:p-5 shadow-[4px_4px_0px_0px_rgba(30,41,59,1)] flex flex-col gap-4`,children:[(0,k.jsxs)(`div`,{children:[(0,k.jsxs)(`label`,{className:`block text-xs font-bold text-ink-black uppercase tracking-wider mb-2 font-headline-md flex items-center gap-1.5`,children:[(0,k.jsx)(u,{className:`w-3.5 h-3.5 text-ink-black`}),`Select Provider`]}),(0,k.jsx)(`div`,{className:`grid grid-cols-2 sm:grid-cols-4 gap-2`,children:A.map(t=>{let n=e===t.id;return(0,k.jsxs)(`button`,{type:`button`,onClick:()=>ae(t.id),className:`p-2.5 border-[2px] text-left transition-all cursor-pointer flex flex-col justify-between rounded ${n?`border-ink-black bg-[#ffe24c] shadow-[2px_2px_0px_0px_#1E293B] font-bold`:`border-slate-300 bg-slate-50 hover:bg-slate-100 text-slate-700`}`,children:[(0,k.jsxs)(`div`,{className:`flex items-center justify-between w-full`,children:[(0,k.jsx)(`span`,{className:`text-xs font-bold font-headline-md`,children:t.name}),t.badge&&(0,k.jsx)(`span`,{className:`text-[8px] font-bold uppercase px-1 py-0.2 bg-orange-100 text-orange-700 rounded border border-orange-300`,children:t.badge})]}),(0,k.jsx)(`span`,{className:`text-[9px] mt-1 text-slate-600 leading-tight block`,children:t.desc})]},t.id)})})]}),e==="default"?(0,k.jsxs)(`div`,{className:`p-3.5 bg-slate-50 border border-slate-200 rounded flex items-start gap-3`,children:[(0,k.jsx)(te,{className:`w-4 h-4 text-amber-500 shrink-0 mt-0.5`}),(0,k.jsxs)(`div`,{className:`flex flex-col gap-1 text-xs text-slate-700`,children:[(0,k.jsxs)(`span`,{className:`font-bold text-ink-black`,children:[`Shared Quotas (`,(0,k.jsx)(`i`,{children:`limited`}),`)`]}),(0,k.jsx)(`p`,{className:`text-[11px] text-trash-gray m-0 leading-relaxed`,children:`Powered by shared, basic developer keys. Because limits are shared with everyone, requests may fail. Use your own provider keys above for stable performance.`})]})]}):(0,k.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,k.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,k.jsxs)(`label`,{className:`block text-xs font-bold text-ink-black uppercase tracking-wider font-headline-md flex items-center gap-1.5`,children:[(0,k.jsx)(a,{className:`w-3.5 h-3.5 text-ink-black`}),Q?.name,` API Key`]}),Q?.portalUrl&&(0,k.jsxs)(`a`,{href:Q.portalUrl,target:`_blank`,rel:`noopener noreferrer`,className:`text-[10px] text-sky-600 hover:text-sky-800 font-medium flex items-center gap-1 no-underline`,children:[(0,k.jsx)(`span`,{children:`Get API Key`}),(0,k.jsx)(m,{className:`w-3 h-3`})]})]}),(0,k.jsxs)(`div`,{className:`relative`,children:[(0,k.jsx)(`input`,{type:M?`text`:`password`,value:i,onChange:e=>j(e.target.value),placeholder:`Enter ${Q?.keyPrefix||`API Key`}`,className:`w-full bg-white border-[2px] border-ink-black rounded py-2 pl-3 pr-9 text-ink-black placeholder-slate-400 focus:outline-none focus:border-sky-600 text-xs font-code-mono`}),(0,k.jsx)(`button`,{type:`button`,onClick:()=>ie(!M),className:`absolute right-2.5 top-1/2 -translate-y-1/2 text-trash-gray hover:text-ink-black cursor-pointer bg-transparent border-0 outline-none p-1`,title:M?`Hide API key`:`Show API key`,children:M?(0,k.jsx)(g,{className:`w-3.5 h-3.5`}):(0,k.jsx)(h,{className:`w-3.5 h-3.5`})})]}),(0,k.jsxs)(`div`,{className:`flex items-center gap-1.5 text-[10px] text-trash-gray font-medium`,children:[(0,k.jsx)(r,{className:`w-3.5 h-3.5 text-emerald-600 shrink-0`}),(0,k.jsx)(`span`,{children:`Stored locally in your browser. Sent directly via request headers.`})]}),(0,k.jsxs)(`div`,{className:`flex gap-2 pt-1`,children:[(0,k.jsxs)(`button`,{onClick:oe,className:`flex-1 flex items-center justify-center gap-1.5 py-2 border-[2px] border-ink-black bg-[#ffe24c] hover:bg-yellow-300 text-xs font-bold text-ink-black shadow-[2px_2px_0px_0px_#1E293B] active:translate-y-0.5 active:shadow-none transition-all cursor-pointer rounded uppercase`,children:[(0,k.jsx)(o,{className:`w-3.5 h-3.5`}),`Save Key`]}),i&&(0,k.jsx)(`button`,{onClick:$,className:`px-3 py-2 border-[2px] border-slate-300 bg-white hover:bg-slate-50 text-xs font-bold text-slate-700 hover:text-rose-600 shadow-[2px_2px_0px_0px_rgba(0,0,0,0.05)] active:translate-y-0.5 active:shadow-none transition-all cursor-pointer rounded uppercase`,children:`Clear Key`})]})]}),N&&(0,k.jsxs)(`div`,{className:`p-2.5 border-[2px] border-ink-black text-xs font-medium rounded flex items-center gap-2 ${N.type===`success`?`bg-emerald-100 border-emerald-600 text-emerald-900`:N.type===`error`?`bg-rose-100 border-rose-600 text-rose-900`:`bg-sky-100 border-sky-600 text-sky-900`}`,children:[N.type===`success`?(0,k.jsx)(p,{className:`w-3.5 h-3.5 shrink-0`}):N.type===`error`?(0,k.jsx)(c,{className:`w-3.5 h-3.5 shrink-0`}):(0,k.jsx)(s,{className:`w-3.5 h-3.5 shrink-0`}),N.text]}),e!=="default"&&(0,k.jsx)(`div`,{className:`pt-2 border-t border-slate-200 flex justify-end`,children:(0,k.jsxs)(`button`,{onClick:se,className:`flex items-center gap-1.5 py-1.5 px-3 border border-slate-300 bg-slate-50 hover:bg-slate-100 text-[11px] font-bold text-slate-600 hover:text-ink-black transition-all cursor-pointer rounded`,children:[(0,k.jsx)(t,{className:`w-3 h-3 text-slate-500`}),`Reset to Server Default`]})})]}),(0,k.jsxs)(`div`,{className:`bg-white border-[3px] border-ink-black p-4 sm:p-5 shadow-[4px_4px_0px_0px_rgba(30,41,59,1)] flex flex-col gap-4`,children:[(0,k.jsxs)(`div`,{className:`flex items-center justify-between border-b-[2px] border-ink-black pb-3`,children:[(0,k.jsxs)(`div`,{className:`flex items-center gap-2.5`,children:[(0,k.jsx)(`div`,{className:`w-8 h-8 rounded bg-[#24292e] border-[2px] border-ink-black flex items-center justify-center text-white shadow-[1px_1px_0px_0px_#1E293B]`,children:(0,k.jsx)(f,{className:`w-4 h-4 text-white`})}),(0,k.jsxs)(`div`,{children:[(0,k.jsx)(`h4`,{className:`font-headline-md font-bold text-xs uppercase text-ink-black m-0 flex items-center gap-2`,children:`GitHub Solutions Sync & Auto-Commit`}),(0,k.jsx)(`p`,{className:`text-[10px] text-trash-gray font-medium m-0`,children:`Sync solutions to personal GitHub repository and commit automatically on submission`})]})]}),(0,k.jsx)(`span`,{className:`px-2 py-0.5 text-[9px] font-bold font-arcade uppercase border-2 border-ink-black shrink-0 ${Y?`bg-emerald-300 text-emerald-950`:`bg-slate-200 text-slate-800`}`,children:Y?`CONNECTED`:`DISCONNECTED`})]}),Y?(0,k.jsxs)(`div`,{className:`space-y-3`,children:[(0,k.jsxs)(`div`,{className:`flex flex-col sm:flex-row sm:items-center justify-between gap-2 p-3 bg-slate-50 border border-slate-200 rounded`,children:[(0,k.jsxs)(`div`,{className:`flex items-center gap-2.5`,children:[U?.avatar_url&&(0,k.jsx)(`img`,{src:U.avatar_url,alt:U.login,className:`w-7 h-7 rounded-full border border-ink-black`}),(0,k.jsxs)(`div`,{children:[(0,k.jsxs)(`span`,{className:`text-xs font-bold text-ink-black`,children:[`@`,U?.login||V.username]}),(0,k.jsxs)(`span`,{className:`text-[11px] text-slate-600 font-mono block`,children:[V.username,`/`,V.repoName,` (`,V.branch,`)`]})]})]}),(0,k.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,k.jsxs)(`a`,{href:`https://github.com/${V.username}/${V.repoName}`,target:`_blank`,rel:`noopener noreferrer`,className:`px-2.5 py-1 text-[11px] font-bold bg-white hover:bg-slate-100 text-ink-black border border-slate-300 rounded no-underline flex items-center gap-1 cursor-pointer`,children:[(0,k.jsx)(m,{className:`w-3 h-3`}),(0,k.jsx)(`span`,{children:`View Repo`})]}),(0,k.jsx)(`button`,{type:`button`,onClick:fe,className:`px-2.5 py-1 text-[11px] font-bold bg-white hover:bg-rose-50 text-rose-700 border border-rose-300 rounded cursor-pointer`,children:`Disconnect`})]})]}),(0,k.jsxs)(`label`,{className:`flex items-center gap-2.5 p-2.5 bg-emerald-50/50 border border-emerald-300 rounded cursor-pointer`,children:[(0,k.jsx)(`input`,{type:`checkbox`,checked:V.autoCommit,onChange:e=>pe(e.target.checked),className:`w-4 h-4 accent-emerald-600 cursor-pointer`}),(0,k.jsxs)(`div`,{className:`text-xs`,children:[(0,k.jsx)(`span`,{className:`font-bold text-ink-black block`,children:`Auto-commit on every submission`}),(0,k.jsxs)(`span`,{className:`text-[10px] text-trash-gray`,children:[`Automatically pushes your code to `,V.repoName,` whenever you grade a review card.`]})]})]})]}):(0,k.jsxs)(`div`,{className:`flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 p-3.5 bg-slate-50 border border-slate-200 rounded`,children:[(0,k.jsxs)(`div`,{className:`space-y-0.5`,children:[(0,k.jsx)(`span`,{className:`text-xs font-bold text-ink-black block`,children:`Connect your GitHub Account (1-Click OAuth)`}),(0,k.jsx)(`p`,{className:`text-[11px] text-trash-gray m-0`,children:`Grant repository access to automatically sync your DSA problem solutions as you study.`})]}),(0,k.jsx)(`button`,{type:`button`,onClick:de,disabled:G,className:`px-4 py-2 bg-[#24292e] hover:bg-black text-white text-xs font-bold uppercase rounded border-2 border-ink-black shadow-[2px_2px_0px_0px_#1E293B] active:translate-y-0.5 active:shadow-none flex items-center gap-2 shrink-0 cursor-pointer disabled:opacity-50`,children:G?(0,k.jsxs)(k.Fragment,{children:[(0,k.jsx)(ee,{className:`w-3.5 h-3.5 animate-spin`}),(0,k.jsx)(`span`,{children:`CONNECTING...`})]}):(0,k.jsxs)(k.Fragment,{children:[(0,k.jsx)(f,{className:`w-3.5 h-3.5 text-yellow-300`}),(0,k.jsx)(`span`,{children:`CONNECT GITHUB`})]})})]}),q&&(0,k.jsxs)(`div`,{className:`p-2.5 border-[2px] border-ink-black text-xs font-medium rounded flex items-center gap-2 ${q.type===`success`?`bg-emerald-100 border-emerald-600 text-emerald-900`:q.type===`error`?`bg-rose-100 border-rose-600 text-rose-900`:`bg-sky-100 border-sky-600 text-sky-900`}`,children:[q.type===`success`?(0,k.jsx)(p,{className:`w-3.5 h-3.5 shrink-0`}):q.type===`error`?(0,k.jsx)(c,{className:`w-3.5 h-3.5 shrink-0`}):(0,k.jsx)(s,{className:`w-3.5 h-3.5 shrink-0`}),q.text]})]}),(0,k.jsxs)(`div`,{className:`bg-[#FFFDF0] border-[3px] border-ink-black p-4 sm:p-5 shadow-[4px_4px_0px_0px_rgba(30,41,59,1)] flex flex-col gap-4`,children:[(0,k.jsxs)(`div`,{className:`flex items-center justify-between border-b-[2px] border-ink-black pb-3`,children:[(0,k.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,k.jsx)(`div`,{className:`w-7 h-7 rounded bg-[#FFE24C] border-[2px] border-ink-black flex items-center justify-center shadow-[1px_1px_0px_0px_#1E293B]`,children:(0,k.jsx)(_,{className:`w-4 h-4 text-ink-black`})}),(0,k.jsxs)(`div`,{children:[(0,k.jsx)(`h4`,{className:`font-headline-md font-bold text-xs uppercase text-ink-black m-0`,children:`Princess AI Companion & Journey Settings`}),(0,k.jsx)(`p`,{className:`text-[10px] text-trash-gray font-medium m-0`,children:`Princess Persona, Journey Break Reminders & 8-bit RPG Audio`})]})]}),(0,k.jsxs)(`label`,{className:`flex items-center gap-2 cursor-pointer`,children:[(0,k.jsx)(`span`,{className:`text-[11px] font-bold text-ink-black font-headline-md uppercase`,children:F.enabled?`Enabled`:`Disabled`}),(0,k.jsx)(`input`,{type:`checkbox`,checked:F.enabled,onChange:e=>I(t=>({...t,enabled:e.target.checked})),className:`w-4 h-4 accent-amber-500 cursor-pointer`})]})]}),(0,k.jsxs)(`div`,{className:`grid grid-cols-1 md:grid-cols-2 gap-4`,children:[(0,k.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,k.jsx)(`label`,{className:`block text-xs font-bold text-ink-black uppercase tracking-wider font-headline-md`,children:`Companion Name`}),(0,k.jsx)(`input`,{type:`text`,value:F.name,onChange:e=>I(t=>({...t,name:e.target.value})),placeholder:`e.g. Princess Aurelia`,className:`bg-white border-[2px] border-ink-black rounded py-2 px-3 text-ink-black text-xs font-sans font-medium focus:outline-none focus:border-amber-600`})]}),(0,k.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,k.jsxs)(`label`,{className:`block text-xs font-bold text-ink-black uppercase tracking-wider font-headline-md flex items-center gap-1`,children:[(0,k.jsx)(d,{className:`w-3.5 h-3.5 text-amber-700`}),`Study Break Reminder`]}),(0,k.jsxs)(`select`,{value:F.breakIntervalMinutes,onChange:e=>I(t=>({...t,breakIntervalMinutes:Number(e.target.value)})),className:`bg-white border-[2px] border-ink-black rounded py-2 px-3 text-ink-black text-xs font-sans font-medium focus:outline-none focus:border-amber-600 cursor-pointer`,children:[(0,k.jsx)(`option`,{value:25,children:`Every 25 Minutes (Classic Pomodoro)`}),(0,k.jsx)(`option`,{value:45,children:`Every 45 Minutes`}),(0,k.jsx)(`option`,{value:60,children:`Every 60 Minutes`}),(0,k.jsx)(`option`,{value:0,children:`Disabled (No automatic break popups)`})]})]})]}),(0,k.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,k.jsx)(`label`,{className:`block text-xs font-bold text-ink-black uppercase tracking-wider font-headline-md`,children:`Princess Backstory & Persona Prompt`}),(0,k.jsx)(`textarea`,{rows:2,value:F.backstory,onChange:e=>I(t=>({...t,backstory:e.target.value})),placeholder:`Describe her background, traveling companions, and quest for the Elixir of Life...`,className:`bg-white border-[2px] border-ink-black rounded p-2.5 text-ink-black text-xs font-sans font-medium focus:outline-none focus:border-amber-600 resize-y`})]}),(0,k.jsxs)(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3 pt-1`,children:[(0,k.jsxs)(`label`,{className:`flex items-center gap-2.5 p-2.5 bg-white border border-slate-300 rounded cursor-pointer hover:border-ink-black transition-all`,children:[(0,k.jsx)(`input`,{type:`checkbox`,checked:F.soundEnabled,onChange:e=>{let t=e.target.checked;I(e=>({...e,soundEnabled:t})),v(!t)},className:`w-4 h-4 accent-amber-500 cursor-pointer`}),(0,k.jsxs)(`div`,{className:`text-xs`,children:[(0,k.jsx)(`span`,{className:`font-bold text-ink-black block`,children:`8-bit Sound Effects`}),(0,k.jsx)(`span`,{className:`text-[10px] text-trash-gray`,children:`Audio chimes & fanfare`})]})]}),(0,k.jsxs)(`label`,{className:`flex items-center gap-2.5 p-2.5 bg-white border border-slate-300 rounded cursor-pointer hover:border-ink-black transition-all`,children:[(0,k.jsx)(`input`,{type:`checkbox`,checked:F.autoPopupEnabled,onChange:e=>I(t=>({...t,autoPopupEnabled:e.target.checked})),className:`w-4 h-4 accent-amber-500 cursor-pointer`}),(0,k.jsxs)(`div`,{className:`text-xs`,children:[(0,k.jsx)(`span`,{className:`font-bold text-ink-black block`,children:`Spontaneous RPG Popups`}),(0,k.jsx)(`span`,{className:`text-[10px] text-trash-gray`,children:`Speech bubbles for breaks & milestones`})]})]})]}),(0,k.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2 pt-2 border-t border-slate-200`,children:[(0,k.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,k.jsxs)(`button`,{type:`button`,onClick:ce,className:`flex items-center gap-1.5 py-2 px-4 border-[2px] border-ink-black bg-[#ffe24c] hover:bg-yellow-300 text-xs font-bold text-ink-black shadow-[2px_2px_0px_0px_#1E293B] active:translate-y-0.5 active:shadow-none transition-all cursor-pointer rounded uppercase`,children:[(0,k.jsx)(o,{className:`w-3.5 h-3.5`}),`Save Companion Settings`]}),(0,k.jsx)(`button`,{type:`button`,onClick:le,className:`py-2 px-3 border border-slate-300 bg-white hover:bg-slate-50 text-xs font-bold text-slate-700 transition-all cursor-pointer rounded`,children:`Default Persona`})]}),(0,k.jsxs)(`button`,{type:`button`,onClick:ue,className:`flex items-center gap-1 py-1.5 px-3 border border-rose-300 bg-rose-50 hover:bg-rose-100 text-rose-700 text-[11px] font-bold transition-all cursor-pointer rounded`,children:[(0,k.jsx)(t,{className:`w-3 h-3 text-rose-500`}),(0,k.jsxs)(`span`,{children:[`Reset Journey (`,z,`/150 Leagues)`]})]})]}),L&&(0,k.jsxs)(`div`,{className:`p-2.5 border-[2px] border-ink-black text-xs font-medium rounded flex items-center gap-2 ${L.type===`success`?`bg-emerald-100 border-emerald-600 text-emerald-900`:`bg-sky-100 border-sky-600 text-sky-900`}`,children:[(0,k.jsx)(p,{className:`w-3.5 h-3.5 shrink-0`}),L.text]})]}),(0,k.jsxs)(`div`,{className:`bg-white border-[3px] border-ink-black p-4 shadow-[4px_4px_0px_0px_rgba(30,41,59,1)] flex flex-col gap-2.5`,children:[(0,k.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,k.jsx)(s,{className:`w-3.5 h-3.5 text-[#0ea5e9]`}),(0,k.jsx)(`h4`,{className:`text-xs font-bold uppercase font-headline-md m-0`,children:`Get Free API Keys`})]}),(0,k.jsxs)(`div`,{className:`grid grid-cols-1 md:grid-cols-3 gap-2 text-[10px]`,children:[(0,k.jsxs)(`a`,{href:`https://console.groq.com/keys`,target:`_blank`,rel:`noopener noreferrer`,className:`p-2.5 border border-slate-200 hover:border-ink-black hover:bg-slate-50 rounded flex flex-col justify-between gap-1 transition-all no-underline text-inherit cursor-pointer`,children:[(0,k.jsxs)(`div`,{className:`flex items-center justify-between font-bold text-ink-black`,children:[(0,k.jsx)(`span`,{children:`Groq Cloud`}),(0,k.jsx)(m,{className:`w-3 h-3 text-slate-400`})]}),(0,k.jsx)(`p`,{className:`m-0 text-trash-gray leading-normal`,children:`Fast inference with generous free rate limits.`})]}),(0,k.jsxs)(`a`,{href:`https://aistudio.google.com/app/apikey`,target:`_blank`,rel:`noopener noreferrer`,className:`p-2.5 border border-slate-200 hover:border-ink-black hover:bg-slate-50 rounded flex flex-col justify-between gap-1 transition-all no-underline text-inherit cursor-pointer`,children:[(0,k.jsxs)(`div`,{className:`flex items-center justify-between font-bold text-ink-black`,children:[(0,k.jsx)(`span`,{children:`Google AI Studio`}),(0,k.jsx)(m,{className:`w-3 h-3 text-slate-400`})]}),(0,k.jsx)(`p`,{className:`m-0 text-trash-gray leading-normal`,children:`Free Gemini Flash API quota.`})]}),(0,k.jsxs)(`a`,{href:`https://openrouter.ai/keys`,target:`_blank`,rel:`noopener noreferrer`,className:`p-2.5 border border-slate-200 hover:border-ink-black hover:bg-slate-50 rounded flex flex-col justify-between gap-1 transition-all no-underline text-inherit cursor-pointer`,children:[(0,k.jsxs)(`div`,{className:`flex items-center justify-between font-bold text-ink-black`,children:[(0,k.jsx)(`span`,{children:`OpenRouter`}),(0,k.jsx)(m,{className:`w-3 h-3 text-slate-400`})]}),(0,k.jsx)(`p`,{className:`m-0 text-trash-gray leading-normal`,children:`Unified API for open-weights models.`})]})]})]})]})}export{j as default};1import{r as e}from"./rolldown-runtime-hePW80VL.js";import{Bt as t,Ht as n}from"./vendor-react-hnaVBnLv.js";import{s as r}from"./firebaseClient-DZobvwSx.js";import{n as i}from"./index-DVWZ15xt.js";var a=e(n(),1),o=t();function s(e,t){if(e.length===0||t.length===0)return[`Empty result set.`];let n={};e.forEach(e=>{n[e]=e.length}),t.forEach(t=>{e.forEach(e=>{let r=t[e]!==null&&t[e]!==void 0?String(t[e]):`NULL`;r.length>(n[e]||0)&&(n[e]=r.length)})});let r=`+`+e.map(e=>`-`.repeat(n[e]+2)).join(`+`)+`+`,i=[r,`|`+e.map(e=>` ${e.padEnd(n[e])} `).join(`|`)+`|`,r];return t.forEach(t=>{let r=`|`+e.map(e=>` ${(t[e]!==null&&t[e]!==void 0?String(t[e]):`NULL`).padEnd(n[e])} `).join(`|`)+`|`;i.push(r)}),i.push(r),i}function c({onOpenWindow:e,onClose:t}){let[n,c]=(0,a.useState)([`AlgoSpaced OS [Version 1.0.24-beta]`,`(c) Retro Arcade Systems. All rights reserved.`,``,`Type "help" for a list of available commands.`,``]),[l,u]=(0,a.useState)(``),d=(0,a.useRef)(null);(0,a.useEffect)(()=>{d.current&&(d.current.scrollTop=d.current.scrollHeight)},[n]);let f=e=>{let t=e.trim(),n=/[^\s"']+|"([^"]*)"|'([^']*)'/g,r=[],i;for(;(i=n.exec(t))!==null;)r.push(i[1]||i[2]||i[0]);return{command:r[0]?.toLowerCase()||``,args:r.slice(1)}},p=async n=>{let a=n.trim();if(a===``){c(e=>[...e,`$`]);return}let{command:o,args:l}=f(a),u=[`$ ${a}`];switch(o){case`help`:u.push(`Available commands:`,` help - Display this documentation`,` ps - Inspect OS process table (PIDs & task states)`,` streak - Retrieve your active review streak metrics`,` sync - Run google drive file import sync`,` reviews - Fetch Leetcode numbers due for daily review`,` python play - Open Daily Python Challenge window`,` sql play - Open Interactive SQL Playground window`,` db init - Initialize SQL session and open playground window`,` db status - Check active SQL session objectives`,` db query [Q] - Execute query and format results inside CLI`,` open - Open window (usage: open queue | journey | system | python | db)`,` clear - Clear terminal buffer`,` exit - Close the terminal shell`);break;case`ps`:case`top`:{let e=Object.values(i.getState().processes);if(e.length===0)u.push(`No background processes currently in table.`);else{u.push(`AlgoSpaced OS Process Table:`);let t=s([`PID`,`APP`,`STATUS`,`NAME`],e.map(e=>({PID:e.pid.substring(0,16),APP:e.appId,STATUS:e.status.toUpperCase(),NAME:e.title.substring(0,24)})));u.push(...t)}break}case`clear`:c([]);return;case`exit`:u.push(`Closing terminal session...`),setTimeout(()=>{t()},500);break;case`open`:{let t=l[0]?.toLowerCase();t===`queue`||t===`daily`||t===`reviews`?(e(`queue`),u.push(`Launching Daily Queue window...`)):t===`journey`||t===`path`||t===`map`?(e(`journey`),u.push(`Launching Journey Path window...`)):t===`system`||t===`computer`||t===`sys`?(e(`computer`),u.push(`Launching System Information window...`)):t===`python`||t===`challenge`?(e(`python`),u.push(`Launching Daily Python Challenge window...`)):t===`db`||t===`mysql`||t===`sql`?(e(`mysql`),u.push(`Launching MySQL Playground window...`)):u.push(`Usage: open [queue | journey | system | python | db]`);break}case`streak`:u.push(`Connecting to streak.sys database...`);try{let{data:{session:e}}=await r.auth.getSession();if(!e){u.push(`Error: Unauthenticated session`);break}let t=await fetch(`/api/streak`,{headers:{Authorization:`Bearer ${e.access_token}`}});if(t.ok){let e=await t.json();u.push(`Database Response:`,` Active Streak: ${e.current_streak} days`,` Max Combo: ${e.longest_streak} days`,` Last Activity: ${e.last_active_date?new Date(e.last_active_date).toLocaleDateString():`N/A`}`)}else u.push(`Error: Failed to query database endpoint`)}catch{u.push(`Error: Connection timed out`)}break;case`sync`:u.push(`Initializing Google Drive synchronization sync.exe...`);try{let{data:{session:e}}=await r.auth.getSession();if(!e){u.push(`Error: Unauthenticated session`);break}let t=await fetch(`/api/sync`,{method:`POST`,headers:{Authorization:`Bearer ${e.access_token}`}});if(t.ok){let e=await t.json();u.push(`Sync Result: ${e.message}`)}else u.push(`Error: Sync command failed at backend host`)}catch{u.push(`Error: Cloud host unreachable`)}break;case`reviews`:u.push(`Querying fsrs_cards partition...`);try{let{data:{session:e}}=await r.auth.getSession();if(!e){u.push(`Error: Unauthenticated session`);break}let t=await fetch(`/api/reviews/due`,{headers:{Authorization:`Bearer ${e.access_token}`}});if(t.ok){let e=await t.json();if(e.length===0)u.push(`Queue status: CLEAR! 0 cards due.`);else{let t={0:`New`,1:`Learning`,2:`Review`,3:`Relearning`};u.push(`Queue status: ${e.length} card(s) due:`,...e.map(e=>` - LeetCode ${e.problems?.problem_number??`?`}: ${e.problems?.name??`Unknown`} (${t[e.fsrs_state??0]??`New`})`))}}else u.push(`Error: Failed to fetch due items`)}catch{u.push(`Error: Database connection lost`)}break;case`python`:l[0]?.toLowerCase()===`play`?(u.push(`Launching Daily Python Challenge window...`),e(`python`)):u.push(`Usage: python play`);break;case`sql`:case`mysql`:case`db`:{let t=l[0]?.toLowerCase();if(t===`play`)u.push(`Launching MySQL Playground window...`),e(`mysql`);else if(t===`init`){u.push(`Initializing MySQL Playground and launching window...`),e(`mysql`);try{let{data:{session:e}}=await r.auth.getSession();if(!e){u.push(`Error: Unauthenticated session`);break}let t=await fetch(`/api/challenges/mysql/init?refresh=true`,{method:`POST`,headers:{Authorization:`Bearer ${e.access_token}`}});if(t.ok){let e=await t.json();u.push(`Database Session Created: "${e.title}"`,`Objective: ${e.objective}`)}else u.push(`Error: Failed to initialize DB session on backend host.`)}catch{u.push(`Error: Server connection lost.`)}}else if(t===`status`){u.push(`Fetching SQL playground status...`),e(`mysql`);try{let{data:{session:e}}=await r.auth.getSession();if(!e){u.push(`Error: Unauthenticated session`);break}let t=await fetch(`/api/challenges/mysql/status`,{headers:{Authorization:`Bearer ${e.access_token}`}});if(t.ok){let e=await t.json();e.active?u.push(`Active SQL Challenge: "${e.title}"`,`Objective: ${e.objective}`,`Status: ${e.completed?`COMPLETED (Done)`:`IN PROGRESS`}`):u.push(e.message)}else u.push(`Error: Failed to fetch DB status.`)}catch{u.push(`Error: Server timed out.`)}}else if(t===`query`){let t=a.toLowerCase().indexOf(`query`),n=t===-1?``:a.substring(t+5).trim().replace(/^["']|["']$/g,``);if(!n){u.push(`Usage: db query [SQL Statement] - Remember to wrap query in double quotes.`);break}u.push(`Running query: ${n}`),e(`mysql`);try{let{data:{session:e}}=await r.auth.getSession();if(!e){u.push(`Error: Unauthenticated session`);break}let t=await fetch(`/api/challenges/mysql/query`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${e.access_token}`},body:JSON.stringify({query:n})});if(t.ok){let e=await t.json();e.success?(u.push(`Query OK. Affected ${e.rows_affected} rows.`,...s(e.columns,e.rows)),e.is_correct&&u.push(`OBJECTIVE ACHIEVED! Congratulations.`)):u.push(`SQL Error: ${e.error}`)}else u.push(`Error: SQL execution failed.`)}catch{u.push(`Error: Database server unreachable.`)}}else u.push(`Usage: sql play | db init | db status | db query "SELECT..."`);break}default:u.push(`Command not recognized: "${o}". Type "help" for a list of available actions.`)}c(e=>[...e,...u,``])};return(0,o.jsxs)(`div`,{className:`w-full h-full bg-[#1E293B] text-[#4ADE80] font-code-mono p-4 flex flex-col overflow-hidden text-xs md:text-sm select-text`,children:[(0,o.jsx)(`div`,{ref:d,className:`flex-1 overflow-y-auto mb-2 custom-scrollbar space-y-1`,children:n.map((e,t)=>(0,o.jsx)(`div`,{className:`whitespace-pre-wrap leading-relaxed min-h-[1.2em]`,children:e},t))}),(0,o.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),p(l),u(``)},className:`flex items-center gap-1.5 border-t border-slate-700 pt-2 shrink-0 select-none`,children:[(0,o.jsx)(`span`,{className:`font-bold text-[#ffcc00]`,children:`$`}),(0,o.jsx)(`input`,{type:`text`,value:l,onChange:e=>u(e.target.value),className:`flex-1 bg-transparent text-[#4ADE80] outline-none border-none p-0 focus:ring-0 font-code-mono text-xs md:text-sm`,autoFocus:!0,placeholder:`Type command...`})]})]})}export{c as default};1import{r as e}from"./rolldown-runtime-hePW80VL.js";import{Bt as t,Ht as n}from"./vendor-react-hnaVBnLv.js";import{s as r}from"./firebaseClient-DZobvwSx.js";import{n as i}from"./index-Q9onQHft.js";var a=e(n(),1),o=t();function s(e,t){if(e.length===0||t.length===0)return[`Empty result set.`];let n={};e.forEach(e=>{n[e]=e.length}),t.forEach(t=>{e.forEach(e=>{let r=t[e]!==null&&t[e]!==void 0?String(t[e]):`NULL`;r.length>(n[e]||0)&&(n[e]=r.length)})});let r=`+`+e.map(e=>`-`.repeat(n[e]+2)).join(`+`)+`+`,i=[r,`|`+e.map(e=>` ${e.padEnd(n[e])} `).join(`|`)+`|`,r];return t.forEach(t=>{let r=`|`+e.map(e=>` ${(t[e]!==null&&t[e]!==void 0?String(t[e]):`NULL`).padEnd(n[e])} `).join(`|`)+`|`;i.push(r)}),i.push(r),i}function c({onOpenWindow:e,onClose:t}){let[n,c]=(0,a.useState)([`AlgoSpaced OS [Version 1.0.24-beta]`,`(c) Retro Arcade Systems. All rights reserved.`,``,`Type "help" for a list of available commands.`,``]),[l,u]=(0,a.useState)(``),d=(0,a.useRef)(null);(0,a.useEffect)(()=>{d.current&&(d.current.scrollTop=d.current.scrollHeight)},[n]);let f=e=>{let t=e.trim(),n=/[^\s"']+|"([^"]*)"|'([^']*)'/g,r=[],i;for(;(i=n.exec(t))!==null;)r.push(i[1]||i[2]||i[0]);return{command:r[0]?.toLowerCase()||``,args:r.slice(1)}},p=async n=>{let a=n.trim();if(a===``){c(e=>[...e,`$`]);return}let{command:o,args:l}=f(a),u=[`$ ${a}`];switch(o){case`help`:u.push(`Available commands:`,` help - Display this documentation`,` ps - Inspect OS process table (PIDs & task states)`,` streak - Retrieve your active review streak metrics`,` sync - Run google drive file import sync`,` reviews - Fetch Leetcode numbers due for daily review`,` python play - Open Daily Python Challenge window`,` sql play - Open Interactive SQL Playground window`,` db init - Initialize SQL session and open playground window`,` db status - Check active SQL session objectives`,` db query [Q] - Execute query and format results inside CLI`,` open - Open window (usage: open queue | journey | system | python | db)`,` clear - Clear terminal buffer`,` exit - Close the terminal shell`);break;case`ps`:case`top`:{let e=Object.values(i.getState().processes);if(e.length===0)u.push(`No background processes currently in table.`);else{u.push(`AlgoSpaced OS Process Table:`);let t=s([`PID`,`APP`,`STATUS`,`NAME`],e.map(e=>({PID:e.pid.substring(0,16),APP:e.appId,STATUS:e.status.toUpperCase(),NAME:e.title.substring(0,24)})));u.push(...t)}break}case`clear`:c([]);return;case`exit`:u.push(`Closing terminal session...`),setTimeout(()=>{t()},500);break;case`open`:{let t=l[0]?.toLowerCase();t===`queue`||t===`daily`||t===`reviews`?(e(`queue`),u.push(`Launching Daily Queue window...`)):t===`journey`||t===`path`||t===`map`?(e(`journey`),u.push(`Launching Journey Path window...`)):t===`system`||t===`computer`||t===`sys`?(e(`computer`),u.push(`Launching System Information window...`)):t===`python`||t===`challenge`?(e(`python`),u.push(`Launching Daily Python Challenge window...`)):t===`db`||t===`mysql`||t===`sql`?(e(`mysql`),u.push(`Launching MySQL Playground window...`)):u.push(`Usage: open [queue | journey | system | python | db]`);break}case`streak`:u.push(`Connecting to streak.sys database...`);try{let{data:{session:e}}=await r.auth.getSession();if(!e){u.push(`Error: Unauthenticated session`);break}let t=await fetch(`/api/streak`,{headers:{Authorization:`Bearer ${e.access_token}`}});if(t.ok){let e=await t.json();u.push(`Database Response:`,` Active Streak: ${e.current_streak} days`,` Max Combo: ${e.longest_streak} days`,` Last Activity: ${e.last_active_date?new Date(e.last_active_date).toLocaleDateString():`N/A`}`)}else u.push(`Error: Failed to query database endpoint`)}catch{u.push(`Error: Connection timed out`)}break;case`sync`:u.push(`Initializing Google Drive synchronization sync.exe...`);try{let{data:{session:e}}=await r.auth.getSession();if(!e){u.push(`Error: Unauthenticated session`);break}let t=await fetch(`/api/sync`,{method:`POST`,headers:{Authorization:`Bearer ${e.access_token}`}});if(t.ok){let e=await t.json();u.push(`Sync Result: ${e.message}`)}else u.push(`Error: Sync command failed at backend host`)}catch{u.push(`Error: Cloud host unreachable`)}break;case`reviews`:u.push(`Querying fsrs_cards partition...`);try{let{data:{session:e}}=await r.auth.getSession();if(!e){u.push(`Error: Unauthenticated session`);break}let t=await fetch(`/api/reviews/due`,{headers:{Authorization:`Bearer ${e.access_token}`}});if(t.ok){let e=await t.json();if(e.length===0)u.push(`Queue status: CLEAR! 0 cards due.`);else{let t={0:`New`,1:`Learning`,2:`Review`,3:`Relearning`};u.push(`Queue status: ${e.length} card(s) due:`,...e.map(e=>` - LeetCode ${e.problems?.problem_number??`?`}: ${e.problems?.name??`Unknown`} (${t[e.fsrs_state??0]??`New`})`))}}else u.push(`Error: Failed to fetch due items`)}catch{u.push(`Error: Database connection lost`)}break;case`python`:l[0]?.toLowerCase()===`play`?(u.push(`Launching Daily Python Challenge window...`),e(`python`)):u.push(`Usage: python play`);break;case`sql`:case`mysql`:case`db`:{let t=l[0]?.toLowerCase();if(t===`play`)u.push(`Launching MySQL Playground window...`),e(`mysql`);else if(t===`init`){u.push(`Initializing MySQL Playground and launching window...`),e(`mysql`);try{let{data:{session:e}}=await r.auth.getSession();if(!e){u.push(`Error: Unauthenticated session`);break}let t=await fetch(`/api/challenges/mysql/init?refresh=true`,{method:`POST`,headers:{Authorization:`Bearer ${e.access_token}`}});if(t.ok){let e=await t.json();u.push(`Database Session Created: "${e.title}"`,`Objective: ${e.objective}`)}else u.push(`Error: Failed to initialize DB session on backend host.`)}catch{u.push(`Error: Server connection lost.`)}}else if(t===`status`){u.push(`Fetching SQL playground status...`),e(`mysql`);try{let{data:{session:e}}=await r.auth.getSession();if(!e){u.push(`Error: Unauthenticated session`);break}let t=await fetch(`/api/challenges/mysql/status`,{headers:{Authorization:`Bearer ${e.access_token}`}});if(t.ok){let e=await t.json();e.active?u.push(`Active SQL Challenge: "${e.title}"`,`Objective: ${e.objective}`,`Status: ${e.completed?`COMPLETED (Done)`:`IN PROGRESS`}`):u.push(e.message)}else u.push(`Error: Failed to fetch DB status.`)}catch{u.push(`Error: Server timed out.`)}}else if(t===`query`){let t=a.toLowerCase().indexOf(`query`),n=t===-1?``:a.substring(t+5).trim().replace(/^["']|["']$/g,``);if(!n){u.push(`Usage: db query [SQL Statement] - Remember to wrap query in double quotes.`);break}u.push(`Running query: ${n}`),e(`mysql`);try{let{data:{session:e}}=await r.auth.getSession();if(!e){u.push(`Error: Unauthenticated session`);break}let t=await fetch(`/api/challenges/mysql/query`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${e.access_token}`},body:JSON.stringify({query:n})});if(t.ok){let e=await t.json();e.success?(u.push(`Query OK. Affected ${e.rows_affected} rows.`,...s(e.columns,e.rows)),e.is_correct&&u.push(`OBJECTIVE ACHIEVED! Congratulations.`)):u.push(`SQL Error: ${e.error}`)}else u.push(`Error: SQL execution failed.`)}catch{u.push(`Error: Database server unreachable.`)}}else u.push(`Usage: sql play | db init | db status | db query "SELECT..."`);break}default:u.push(`Command not recognized: "${o}". Type "help" for a list of available actions.`)}c(e=>[...e,...u,``])};return(0,o.jsxs)(`div`,{className:`w-full h-full bg-[#1E293B] text-[#4ADE80] font-code-mono p-4 flex flex-col overflow-hidden text-xs md:text-sm select-text`,children:[(0,o.jsx)(`div`,{ref:d,className:`flex-1 overflow-y-auto mb-2 custom-scrollbar space-y-1`,children:n.map((e,t)=>(0,o.jsx)(`div`,{className:`whitespace-pre-wrap leading-relaxed min-h-[1.2em]`,children:e},t))}),(0,o.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),p(l),u(``)},className:`flex items-center gap-1.5 border-t border-slate-700 pt-2 shrink-0 select-none`,children:[(0,o.jsx)(`span`,{className:`font-bold text-[#ffcc00]`,children:`$`}),(0,o.jsx)(`input`,{type:`text`,value:l,onChange:e=>u(e.target.value),className:`flex-1 bg-transparent text-[#4ADE80] outline-none border-none p-0 focus:ring-0 font-code-mono text-xs md:text-sm`,autoFocus:!0,placeholder:`Type command...`})]})]})}export{c as default};
20 unmodified lines212223242526272829303132333420 unmodified linesrel="stylesheet"href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:wght,FILL@100..700,0..1&family=Bricolage+Grotesque:opsz,wght@12..96,700;12..96,800&family=Be+Vietnam+Pro:wght@500;700&family=Courier+Prime:wght@400;700&family=Press+Start+2P&family=Cinzel:wght@500;700;900&family=Cinzel+Decorative:wght@700;900&family=EB+Garamond:ital,wght@0,400;0,600;1,400;1,600&family=Kalam:wght@400;700&display=swap"/><script type="module" crossorigin src="/assets/index-DVWZ15xt.js"></script><link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-hePW80VL.js"><link rel="modulepreload" crossorigin href="/assets/vendor-codemirror-By0wlJeM.js"><link rel="modulepreload" crossorigin href="/assets/vendor-react-hnaVBnLv.js"><link rel="modulepreload" crossorigin href="/assets/vendor-firebase-DSIO3PIf.js"><link rel="modulepreload" crossorigin href="/assets/firebaseClient-DZobvwSx.js"><link rel="modulepreload" crossorigin href="/assets/vendor-ui-ZXcm-2wU.js"><link rel="stylesheet" crossorigin href="/assets/index-BsU9BpJx.css"><link rel="manifest" href="/manifest.webmanifest"><script id="vite-plugin-pwa:register-sw" src="/registerSW.js"></script></head><body>20 unmodified lines212223242526272829303132333420 unmodified linesrel="stylesheet"href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:wght,FILL@100..700,0..1&family=Bricolage+Grotesque:opsz,wght@12..96,700;12..96,800&family=Be+Vietnam+Pro:wght@500;700&family=Courier+Prime:wght@400;700&family=Press+Start+2P&family=Cinzel:wght@500;700;900&family=Cinzel+Decorative:wght@700;900&family=EB+Garamond:ital,wght@0,400;0,600;1,400;1,600&family=Kalam:wght@400;700&display=swap"/><script type="module" crossorigin src="/assets/index-Q9onQHft.js"></script><link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-hePW80VL.js"><link rel="modulepreload" crossorigin href="/assets/vendor-codemirror-By0wlJeM.js"><link rel="modulepreload" crossorigin href="/assets/vendor-react-hnaVBnLv.js"><link rel="modulepreload" crossorigin href="/assets/vendor-firebase-DSIO3PIf.js"><link rel="modulepreload" crossorigin href="/assets/firebaseClient-DZobvwSx.js"><link rel="modulepreload" crossorigin href="/assets/vendor-ui-ZXcm-2wU.js"><link rel="stylesheet" crossorigin href="/assets/index-kuOEkBQB.css"><link rel="manifest" href="/manifest.webmanifest"><script id="vite-plugin-pwa:register-sw" src="/registerSW.js"></script></head><body>
1if(!self.define){let s,e={};const r=(r,l)=>(r=new URL(r+".js",l).href,e[r]||new Promise(e=>{if("document"in self){const s=document.createElement("script");s.src=r,s.onload=e,document.head.appendChild(s)}else s=r,importScripts(r),e()}).then(()=>{let s=e[r];if(!s)throw new Error(`Module ${r} didn’t register its module`);return s}));self.define=(l,n)=>{const i=s||("document"in self?document.currentScript.src:"")||location.href;if(e[i])return;let u={};const t=s=>r(s,i),o={module:{uri:i},exports:u,require:t};e[i]=Promise.all(l.map(s=>o[s]||t(s))).then(s=>(n(...s),u))}}define(["./workbox-9c191d2f"],function(s){"use strict";self.skipWaiting(),s.clientsClaim(),s.precacheAndRoute([{url:"registerSW.js",revision:"1872c500de691dce40960bb85481de07"},{url:"loader.css",revision:"fe561cfc0908978c7b17dcf5d0ce1075"},{url:"loader-init.js",revision:"3d0342fa97370ec97880bb98818cd608"},{url:"index.html",revision:"af59fb115d7311a1378fc0a9c8a20111"},{url:"assets/vendor-ui-ZXcm-2wU.js",revision:null},{url:"assets/vendor-react-hnaVBnLv.js",revision:null},{url:"assets/vendor-katex-DtkCqjBQ.css",revision:null},{url:"assets/vendor-katex-Balf574a.js",revision:null},{url:"assets/vendor-firebase-DSIO3PIf.js",revision:null},{url:"assets/vendor-codemirror-By0wlJeM.js",revision:null},{url:"assets/TerminalEmulator-CZed0tiA.js",revision:null},{url:"assets/Settings-BVuXk3LW.js",revision:null},{url:"assets/rolldown-runtime-hePW80VL.js",revision:null},{url:"assets/ReviewQueue-CltGWQpb.js",revision:null},{url:"assets/PythonChallenge-CQdOe4Q2.js",revision:null},{url:"assets/ProblemSpecPanel-BRW8UyO6.js",revision:null},{url:"assets/PrincessChamber-abJShfI5.js",revision:null},{url:"assets/MySQLPlayground-iGzsbjAa.js",revision:null},{url:"assets/MarkdownRenderer-D8UdFpnD.js",revision:null},{url:"assets/KatexRenderer-DVt2cqHc.js",revision:null},{url:"assets/JourneyPath-BhAvKOiu.js",revision:null},{url:"assets/index-DVWZ15xt.js",revision:null},{url:"assets/index-BsU9BpJx.css",revision:null},{url:"assets/GitHubSyncWindow-CrRFKIeu.js",revision:null},{url:"assets/githubSyncService-x0Mm_uEl.js",revision:null},{url:"assets/firebaseClient-DZobvwSx.js",revision:null},{url:"assets/FileExplorer-D3FrJW-x.js",revision:null},{url:"assets/CreateProblemForm-Ccz3TNzp.js",revision:null},{url:"assets/confetti.module-Uxh4CK4s.js",revision:null},{url:"assets/CardManager-BEhyd34f.js",revision:null},{url:"assets/Auth-CphacI2S.js",revision:null},{url:"manifest.webmanifest",revision:"7c8ff056d2e188c868d851bcb349e28e"}],{}),s.cleanupOutdatedCaches(),s.registerRoute(new s.NavigationRoute(s.createHandlerBoundToURL("index.html")))});1if(!self.define){let s,e={};const r=(r,l)=>(r=new URL(r+".js",l).href,e[r]||new Promise(e=>{if("document"in self){const s=document.createElement("script");s.src=r,s.onload=e,document.head.appendChild(s)}else s=r,importScripts(r),e()}).then(()=>{let s=e[r];if(!s)throw new Error(`Module ${r} didn’t register its module`);return s}));self.define=(l,n)=>{const i=s||("document"in self?document.currentScript.src:"")||location.href;if(e[i])return;let u={};const o=s=>r(s,i),t={module:{uri:i},exports:u,require:o};e[i]=Promise.all(l.map(s=>t[s]||o(s))).then(s=>(n(...s),u))}}define(["./workbox-9c191d2f"],function(s){"use strict";self.skipWaiting(),s.clientsClaim(),s.precacheAndRoute([{url:"registerSW.js",revision:"1872c500de691dce40960bb85481de07"},{url:"loader.css",revision:"fe561cfc0908978c7b17dcf5d0ce1075"},{url:"loader-init.js",revision:"3d0342fa97370ec97880bb98818cd608"},{url:"index.html",revision:"26d000d86722074086034c87e7dc9a81"},{url:"assets/vendor-ui-ZXcm-2wU.js",revision:null},{url:"assets/vendor-react-hnaVBnLv.js",revision:null},{url:"assets/vendor-katex-DtkCqjBQ.css",revision:null},{url:"assets/vendor-katex-Balf574a.js",revision:null},{url:"assets/vendor-firebase-DSIO3PIf.js",revision:null},{url:"assets/vendor-codemirror-By0wlJeM.js",revision:null},{url:"assets/TerminalEmulator-DeoMeHBL.js",revision:null},{url:"assets/Settings-Dm1_pyAR.js",revision:null},{url:"assets/rolldown-runtime-hePW80VL.js",revision:null},{url:"assets/ReviewQueue-BRrPvJUP.js",revision:null},{url:"assets/PythonChallenge-MiR95vc2.js",revision:null},{url:"assets/ProblemSpecPanel-C8iV6oe0.js",revision:null},{url:"assets/PrincessChamber-DlL5aOl1.js",revision:null},{url:"assets/MySQLPlayground-iGzsbjAa.js",revision:null},{url:"assets/MarkdownRenderer-BGUaDi8Z.js",revision:null},{url:"assets/KatexRenderer-DVt2cqHc.js",revision:null},{url:"assets/JourneyPath-C5zwoWvi.js",revision:null},{url:"assets/index-Q9onQHft.js",revision:null},{url:"assets/index-kuOEkBQB.css",revision:null},{url:"assets/GitHubSyncWindow-CrRFKIeu.js",revision:null},{url:"assets/githubSyncService-x0Mm_uEl.js",revision:null},{url:"assets/firebaseClient-DZobvwSx.js",revision:null},{url:"assets/FileExplorer-D3FrJW-x.js",revision:null},{url:"assets/CreateProblemForm-Ccz3TNzp.js",revision:null},{url:"assets/confetti.module-Uxh4CK4s.js",revision:null},{url:"assets/CardManager-BMwBGmwK.js",revision:null},{url:"assets/Auth-CphacI2S.js",revision:null},{url:"manifest.webmanifest",revision:"7c8ff056d2e188c868d851bcb349e28e"}],{}),s.cleanupOutdatedCaches(),s.registerRoute(new s.NavigationRoute(s.createHandlerBoundToURL("index.html")))});
7 unmodified lines8910111213147 unmodified lines"build": "node node_modules/typescript7/bin/tsc -b && vite build","typecheck": "node node_modules/typescript7/bin/tsc -b","lint": "eslint .","test": "node --experimental-strip-types --test tests/offlineAuth.test.mjs tests/offlineReviewQueue.test.mjs tests/cardManager.test.mjs","preview": "vite preview"},"dependencies": {7 unmodified lines8910111213147 unmodified lines"build": "node node_modules/typescript7/bin/tsc -b && vite build","typecheck": "node node_modules/typescript7/bin/tsc -b","lint": "eslint .","test": "node --experimental-strip-types --test tests/offlineAuth.test.mjs tests/offlineReviewQueue.test.mjs tests/cardManager.test.mjs tests/companionChoices.test.mjs","preview": "vite preview"},"dependencies": {
149 unmodified lines150151152153154155156149 unmodified lines{settings.name || 'Princess Aurelia'}</span><span className="bg-ink-black text-[#FFE24C] text-[9px] font-bold font-arcade px-1.5 py-0.5 rounded shrink-0">{progress.currentFloor}/150 LC</span></div>149 unmodified lines150151152153154155156149 unmodified lines{settings.name || 'Princess Aurelia'}</span><span className="bg-ink-black text-[#FFE24C] text-[9px] font-bold font-arcade px-1.5 py-0.5 rounded shrink-0">{progress.currentFloor}/150 Leagues</span></div>
117 unmodified lines118119120121122123124125126127399 unmodified lines52752852953053153253353453553655 unmodified lines59259359459559659759857 unmodified lines656657658659660661662117 unmodified lines};const handleResetTower = () => {if (window.confirm('Are you sure you want to reset your Spire Journey progress back to 0 problems?')) {const reset = resetTowerProgress();setTowerFloor(reset.currentFloor);setCompanionStatus({ type: 'info', text: 'Spire journey progress reset to 0 problems.' });setTimeout(() => setCompanionStatus(null), 3000);}};399 unmodified lines</div><div><h4 className="font-headline-md font-bold text-xs uppercase text-ink-black m-0">Princess AI Companion & RPG Settings</h4><p className="text-[10px] text-trash-gray font-medium m-0">Trapped Princess Persona, Study Break Timer & 8-bit RPG Audio</p></div></div>55 unmodified linesrows={2}value={companion.backstory}onChange={(e) => setCompanion((prev) => ({ ...prev, backstory: e.target.value }))}placeholder="Describe her background, tone, and connection to your DSA studies..."className="bg-white border-[2px] border-ink-black rounded p-2.5 text-ink-black text-xs font-sans font-medium focus:outline-none focus:border-amber-600 resize-y"/></div>57 unmodified linesclassName="flex items-center gap-1 py-1.5 px-3 border border-rose-300 bg-rose-50 hover:bg-rose-100 text-rose-700 text-[11px] font-bold transition-all cursor-pointer rounded"><RotateCcw className="w-3 h-3 text-rose-500" /><span>Reset Journey ({towerFloor}/150 LC)</span></button></div>117 unmodified lines118119120121122123124125126127399 unmodified lines52752852953053153253353453553655 unmodified lines59259359459559659759857 unmodified lines656657658659660661662117 unmodified lines};const handleResetTower = () => {if (window.confirm('Are you sure you want to reset your journey progress back to 0 leagues?')) {const reset = resetTowerProgress();setTowerFloor(reset.currentFloor);setCompanionStatus({ type: 'info', text: 'Journey progress reset to 0 leagues.' });setTimeout(() => setCompanionStatus(null), 3000);}};399 unmodified lines</div><div><h4 className="font-headline-md font-bold text-xs uppercase text-ink-black m-0">Princess AI Companion & Journey Settings</h4><p className="text-[10px] text-trash-gray font-medium m-0">Princess Persona, Journey Break Reminders & 8-bit RPG Audio</p></div></div>55 unmodified linesrows={2}value={companion.backstory}onChange={(e) => setCompanion((prev) => ({ ...prev, backstory: e.target.value }))}placeholder="Describe her background, traveling companions, and quest for the Elixir of Life..."className="bg-white border-[2px] border-ink-black rounded p-2.5 text-ink-black text-xs font-sans font-medium focus:outline-none focus:border-amber-600 resize-y"/></div>57 unmodified linesclassName="flex items-center gap-1 py-1.5 px-3 border border-rose-300 bg-rose-50 hover:bg-rose-100 text-rose-700 text-[11px] font-bold transition-all cursor-pointer rounded"><RotateCcw className="w-3 h-3 text-rose-500" /><span>Reset Journey ({towerFloor}/150 Leagues)</span></button></div>
479 unmodified lines480481482483484485486479 unmodified lines<Suspensefallback={<div className="fixed bottom-16 right-8 font-mono text-xs text-amber-300 bg-slate-900/90 p-4 border-2 border-slate-700 rounded z-40 animate-pulse">Entering the Spire Tower Parlor...</div>}>479 unmodified lines480481482483484485486479 unmodified lines<Suspensefallback={<div className="fixed bottom-16 right-8 font-mono text-xs text-amber-300 bg-slate-900/90 p-4 border-2 border-slate-700 rounded z-40 animate-pulse">Entering the travel camp with Aurelia...</div>}>
187 unmodified lines188189190191192193194195196197198199187 unmodified linesclassName="p-3 bg-yellow-100 hover:bg-yellow-200 border-[3px] border-ink-black text-left flex flex-col justify-between gadget-shadow active:translate-y-1 active:shadow-none transition-all cursor-pointer"><div className="flex items-center justify-between"><span className="material-symbols-outlined text-amber-600 text-lg">castle</span><ChevronRight className="w-3 h-3 text-ink-black" /></div><div className="mt-2"><div className="font-arcade text-[8px] font-bold text-ink-black uppercase">Princess Tower</div><div className="font-sans text-[10px] text-trash-gray font-semibold">Visit Aurelia</div></div></button>187 unmodified lines188189190191192193194195196197198199187 unmodified linesclassName="p-3 bg-yellow-100 hover:bg-yellow-200 border-[3px] border-ink-black text-left flex flex-col justify-between gadget-shadow active:translate-y-1 active:shadow-none transition-all cursor-pointer"><div className="flex items-center justify-between"><span className="material-symbols-outlined text-amber-600 text-lg">fireplace</span><ChevronRight className="w-3 h-3 text-ink-black" /></div><div className="mt-2"><div className="font-arcade text-[8px] font-bold text-ink-black uppercase">Princess Camp</div><div className="font-sans text-[10px] text-trash-gray font-semibold">Rest with Aurelia</div></div></button>
89 unmodified lines909192939495969 unmodified lines1061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441 unmodified line1461471481491501511521531541551561571581591601611621631641651661671681691701 unmodified line1721731741751761771781791801811821831841851861871881891901911921931941951961 unmodified line1981992002012022032042052062072082092102112122132142152162172182192202212221 unmodified line2242252262272282292302312322332342352361 unmodified line2382392402412422432442452462472482492501 unmodified line2522532542552562572582592602612622632642652662672682692701 unmodified line27227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530689 unmodified linesenabled: true,name: 'Princess Aurelia',backstory:'Princess Aurelia is trapped in the high Spire of Big-O Complexity. You are a brave traveler journeying across the kingdom. By mastering all 150 LeetCode problems along the royal road, you will reach the tower gates and break her magical seal!',breakIntervalMinutes: 25,soundEnabled: true,autoPopupEnabled: true,9 unmodified linesexport const TOWER_CHAPTERS: TowerChapter[] = [{floorRange: [1, 30],title: 'The Plains of Arrays & Strings',description: 'Rolling green meadows and ancient cobblestone roads where the journey begins.',bgLore: 'Looking out towards the distant horizon, the silhouette of the Spire pierces the clouds.',},{floorRange: [31, 60],title: 'The Whispering Forest of Pointers',description: 'Winding paths through dense groves where two pointers guide your compass.',bgLore: 'Aurelia’s magical beacon shines above the treetops, guiding your footsteps along the trail.',},{floorRange: [61, 90],title: 'The Grand Caverns of Trees & Graphs',description: 'Bioluminescent caves with branching crystal arches and subterranean passes.',bgLore: 'Halfway to the tower! Her voice echoes with hope over the enchanted royal relay.',},{floorRange: [91, 120],title: 'The High Mountain Passes of Heaps & Backtracking',description: 'Perilous alpine ridges and snowy peaks overlooking the Spire valley.',bgLore: 'From the highest ridge, the base of the Spire is in sight through the mountain mist!',},{floorRange: [121, 149],title: 'The Enchanted Valley of Dynamic Programming',description: 'Shimmering mystical grounds where optimal solutions bridge the final moat.',bgLore: 'The final leagues! The Spire looms directly ahead, its ancient runic wards trembling.',},{floorRange: [150, 150],title: 'The Gates of the Big-O Spire',description: 'Standing at the threshold of the grand tower gates to break the seal and free Aurelia!',bgLore: '150 algorithms conquered! You have completed the grand journey and reached the Spire!',},];1 unmodified linebreak_reminder: [{id: 'br-1',text: 'Brave traveler! You have traveled many leagues today. Even the swiftest steeds rest by the campfire—shall we pause for a stretch and some water?',emotion: 'concerned',context: 'break_reminder',},{id: 'br-2',text: 'I can see your progress across the plains from my tower window! Please rest your eyes for a moment; a clear mind travels swiftest.',emotion: 'smiling_warmly',context: 'break_reminder',},{id: 'br-3',text: 'The evening winds carry word of your relentless march. Take 5 minutes to rest—I will keep watch from the Spire beacon!',emotion: 'thinking_expression',context: 'break_reminder',},{id: 'br-4',text: 'Do not exhaust yourself on the road, my hero! Pacing is the secret to enduring a 150-problem expedition. Let us take a short pause.',emotion: 'concerned',context: 'break_reminder',},1 unmodified lineproblem_correct: [{id: 'pc-1',text: 'Magnificent! You conquered that obstacle and advanced another league closer to my tower!',emotion: 'excited_expression',context: 'problem_correct',},{id: 'pc-2',text: 'A flawless solution! With every problem you master, the distance between us grows shorter.',emotion: 'smiling_warmly',context: 'problem_correct',},{id: 'pc-3',text: 'Incredible speed and elegance! I felt the Spire beacon flare with light as you crossed another milestone!',emotion: 'excited_expression',context: 'problem_correct',},{id: 'pc-4',text: 'You handled that algorithm with true mastery. Step by step, league by league, you are approaching the Spire gates!',emotion: 'smiling_warmly',context: 'problem_correct',},1 unmodified lineproblem_incorrect: [{id: 'pi-1',text: 'Do not despair, noble traveler! The road to the Spire has rough terrain. Review the edge cases and let us push forward!',emotion: 'concerned',context: 'problem_incorrect',},{id: 'pi-2',text: 'Every wrong turn on the map teaches you the true layout of the land. Let us examine the test case together.',emotion: 'thinking_expression',context: 'problem_incorrect',},{id: 'pi-3',text: 'Stay steadfast! I believe in your courage and intellect. Take a breath—we will conquer this pass together!',emotion: 'smiling_warmly',context: 'problem_incorrect',},{id: 'pi-4',text: 'A challenging problem! But overcoming difficult obstacles is what makes a legendary hero. Keep your head high!',emotion: 'neutral',context: 'problem_incorrect',},1 unmodified linestreak_milestone: [{id: 'sm-1',text: 'A glorious travel streak! Your daily dedication across the realms is inspiring. The Spire bells chime in your honor!',emotion: 'excited_expression',context: 'streak_milestone',},{id: 'sm-2',text: 'Look at that continuous march! Consistency is the true magic that brings you across all 150 leagues to the tower.',emotion: 'smiling_warmly',context: 'streak_milestone',},1 unmodified linestudy_start: [{id: 'ss-1',text: 'Welcome back to the trail, brave adventurer! Which algorithmic territories shall we cross today on our way to the Spire?',emotion: 'smiling_warmly',context: 'study_start',},{id: 'ss-2',text: 'I saw the dust of your travel carriage on the horizon! Ready to conquer today’s review queue and draw closer to the tower?',emotion: 'excited_expression',context: 'study_start',},1 unmodified lineidle_motivation: [{id: 'im-1',text: 'Whenever the trail seems daunting, break the problem into smaller sub-problems. Every step counts toward the 150 milestone!',emotion: 'thinking_expression',context: 'idle_motivation',},{id: 'im-2',text: 'I am watching over your journey and cheering you on! Your quest brings hope to this entire realm.',emotion: 'smiling_warmly',context: 'idle_motivation',},{id: 'im-3',text: '150 problems is a grand quest, but you have the intellect and heart to reach the Spire gates!',emotion: 'neutral',context: 'idle_motivation',},1 unmodified linetower_milestone: [{id: 'tm-1',text: 'You have crossed the Plains of Arrays! 30 problems mastered—the first realm is behind us!',emotion: 'excited_expression',context: 'tower_milestone',floorRequirement: 30,},{id: 'tm-2',text: 'You emerged from the Whispering Forest! 60 problems solved—I can see your banner waving near the foothills!',emotion: 'excited_expression',context: 'tower_milestone',floorRequirement: 60,},{id: 'tm-3',text: 'Through the Grand Caverns! 90 problems conquered—more than halfway to the Spire!',emotion: 'smiling_warmly',context: 'tower_milestone',floorRequirement: 90,},{id: 'tm-4',text: 'You crested the High Mountain Passes! 120 problems conquered—the Spire valley is right before you!',emotion: 'excited_expression',context: 'tower_milestone',floorRequirement: 120,},{id: 'tm-5',text: 'YOU HAVE REACHED THE SPIRE GATES! All 150 LeetCode problems conquered! The grand seals shatter—freedom at last, my legendary champion!',emotion: 'excited_expression',context: 'tower_milestone',floorRequirement: 150,89 unmodified lines909192939495969 unmodified lines1061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441 unmodified line1461471481491501511521531541551561571581591601611621631641651661671681691701 unmodified line1721731741751761771781791801811821831841851861871881891901911921931941951961 unmodified line1981992002012022032042052062072082092102112122132142152162172182192202212221 unmodified line2242252262272282292302312322332342352361 unmodified line2382392402412422432442452462472482492501 unmodified line2522532542552562572582592602612622632642652662672682692701 unmodified line27227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530689 unmodified linesenabled: true,name: 'Princess Aurelia',backstory:'Princess Aurelia is suffering from a severe, fatal illness, traveling alongside you across 150 leagues toward the ancient Tower where the mythical Elixir of Life can cure her. As her sworn guardian and companion, you journey together across dangerous wilderness, facing grueling trials to reach the Elixir before time runs out.',breakIntervalMinutes: 25,soundEnabled: true,autoPopupEnabled: true,9 unmodified linesexport const TOWER_CHAPTERS: TowerChapter[] = [{floorRange: [1, 30],title: 'The Sunlit Plains',description: 'Rolling green meadows and ancient cobblestone roads where our journey begins.',bgLore: 'Looking out toward the distant horizon, the silhouette of the Ancient Tower pierces the morning sky.',},{floorRange: [31, 60],title: 'The Whispering Forest',description: 'Winding paths through dense emerald groves where gentle streams and leafy canopies shade our travel.',bgLore: 'Resting in the wagon beneath tall pines, Aurelia listens to the wind and dreams of the healing elixir.',},{floorRange: [61, 90],title: 'The Grand Caverns',description: 'Bioluminescent caves with branching crystal arches and ancient subterranean passages.',bgLore: 'Halfway to the Tower! The gentle warmth of glowing crystals brings solace as we push through the deep caverns.',},{floorRange: [91, 120],title: 'The High Mountain Passes',description: 'Perilous alpine ridges and snowy peaks overlooking the great valley below.',bgLore: 'From the highest ridge through the swirling mist, the Sanctuary Tower rises majestically ahead.',},{floorRange: [121, 149],title: 'The Enchanted Valley',description: 'Shimmering mystical grounds and flowering sanctuaries that surround the final approach.',bgLore: 'The final leagues! The Tower gates are within sight, where the Elixir of Life awaits.',},{floorRange: [150, 150],title: 'The Tower of the Elixir',description: 'Crossing the threshold of the Ancient Sanctuary to claim the Elixir of Life and cure Aurelia!',bgLore: 'All 150 leagues conquered! The Elixir of Life is in your hands, and Aurelia’s life is saved!',},];1 unmodified linebreak_reminder: [{id: 'br-1',text: 'Brave friend! You have traveled many leagues today. Even the swiftest travelers rest by the campfire—shall we pause for a stretch and some cool water?',emotion: 'concerned',context: 'break_reminder',},{id: 'br-2',text: 'The road stretches far ahead across the plains. Please rest your eyes for a moment; a steady mind travels swiftest.',emotion: 'smiling_warmly',context: 'break_reminder',},{id: 'br-3',text: 'The evening breeze carries the quiet scent of the hills. Take five minutes to rest—I will tend the campfire embers.',emotion: 'thinking_expression',context: 'break_reminder',},{id: 'br-4',text: 'Do not exhaust yourself on the road, my guardian! Pacing our stamina is the secret to enduring this journey. Let us pause for a short rest.',emotion: 'concerned',context: 'break_reminder',},1 unmodified lineproblem_correct: [{id: 'pc-1',text: 'Magnificent! You conquered that obstacle and advanced another league closer to the Tower!',emotion: 'excited_expression',context: 'problem_correct',},{id: 'pc-2',text: 'A flawless victory! With every trial you master, the distance to the Elixir of Life grows shorter.',emotion: 'smiling_warmly',context: 'problem_correct',},{id: 'pc-3',text: 'Incredible skill and elegance! Seeing your resolve brings warmth and hope to my heart as we cross another milestone.',emotion: 'excited_expression',context: 'problem_correct',},{id: 'pc-4',text: 'You handled that trial with true mastery. Step by step, league by league, we are approaching the Tower gates!',emotion: 'smiling_warmly',context: 'problem_correct',},1 unmodified lineproblem_incorrect: [{id: 'pi-1',text: 'Do not despair, noble friend! The road to the Tower has rough terrain. Catch your breath and let us push forward together.',emotion: 'concerned',context: 'problem_incorrect',},{id: 'pi-2',text: 'Every misstep on the trail teaches us the layout of the land. Take a breath—we will find our way.',emotion: 'thinking_expression',context: 'problem_incorrect',},{id: 'pi-3',text: 'Stay steadfast! I believe in your courage and intellect. Together, we will conquer this pass.',emotion: 'smiling_warmly',context: 'problem_incorrect',},{id: 'pi-4',text: 'A challenging trial! But overcoming difficult obstacles is what makes a legendary guardian. Keep your head high.',emotion: 'neutral',context: 'problem_incorrect',},1 unmodified linestreak_milestone: [{id: 'sm-1',text: 'A glorious travel streak! Your daily dedication across the realms is inspiring. Hope burns bright in our camp!',emotion: 'excited_expression',context: 'streak_milestone',},{id: 'sm-2',text: 'Look at that continuous march! Consistency is the true magic that brings us across all 150 leagues to the Tower.',emotion: 'smiling_warmly',context: 'streak_milestone',},1 unmodified linestudy_start: [{id: 'ss-1',text: 'Welcome back to the trail, brave friend! Which territories shall we cross together today on our way to the Tower?',emotion: 'smiling_warmly',context: 'study_start',},{id: 'ss-2',text: 'I saw you preparing our travel gear! Ready to conquer today’s journey and draw closer to the Elixir?',emotion: 'excited_expression',context: 'study_start',},1 unmodified lineidle_motivation: [{id: 'im-1',text: 'Whenever the trail seems daunting, take it one step at a time. Every stride counts toward our destination!',emotion: 'thinking_expression',context: 'idle_motivation',},{id: 'im-2',text: 'I am so grateful for your guidance and companionship. Your quest brings life and hope back to me.',emotion: 'smiling_warmly',context: 'idle_motivation',},{id: 'im-3',text: 'One hundred and fifty leagues is a grand quest, but you have the strength and heart to reach the Sanctuary gates!',emotion: 'neutral',context: 'idle_motivation',},1 unmodified linetower_milestone: [{id: 'tm-1',text: 'You have crossed the Sunlit Plains! 30 leagues traversed—the first realm is behind us!',emotion: 'excited_expression',context: 'tower_milestone',floorRequirement: 30,},{id: 'tm-2',text: 'You emerged from the Whispering Forest! 60 leagues traversed—I can see the foothills rising ahead!',emotion: 'excited_expression',context: 'tower_milestone',floorRequirement: 60,},{id: 'tm-3',text: 'Through the Grand Caverns! 90 leagues conquered—more than halfway to the Tower!',emotion: 'smiling_warmly',context: 'tower_milestone',floorRequirement: 90,},{id: 'tm-4',text: 'You crested the High Mountain Passes! 120 leagues conquered—the Sanctuary valley is right before us!',emotion: 'excited_expression',context: 'tower_milestone',floorRequirement: 120,},{id: 'tm-5',text: 'WE HAVE REACHED THE TOWER OF THE ELIXIR! All 150 leagues conquered! The Elixir of Life is in your hands, the illness is cured, and we walk into the sunlight together!',emotion: 'excited_expression',context: 'tower_milestone',floorRequirement: 150,
98 unmodified lines9910010110210310410510 unmodified lines116117118119120121122123116 unmodified lines24024124224324424524698 unmodified lineschoice_suggestions: Array.isArray(data.choice_suggestions)? data.choice_suggestions: [],provider_used: data.provider_used || 'Spire Agent',};}}10 unmodified linesemotion: fallback.emotion,tool_calls: [],choice_suggestions: ['Tell me about the Spire','Can we take a rest by the fire?',],provider_used: 'Offline Script',};116 unmodified lineschoice_suggestions: Array.isArray(parsed.choice_suggestions)? parsed.choice_suggestions: [],provider_used: parsed.provider_used || 'Spire Agent Stream',});} catch (e) {console.warn('[CompanionAPI] Failed to parse done payload:', e);98 unmodified lines9910010110210310410510 unmodified lines116117118119120121122123124116 unmodified lines24124224324424524624798 unmodified lineschoice_suggestions: Array.isArray(data.choice_suggestions)? data.choice_suggestions: [],provider_used: data.provider_used || 'Tower Journey Agent',};}}10 unmodified linesemotion: fallback.emotion,tool_calls: [],choice_suggestions: ['How is your strength holding up today?','Let us rest by the fire for a moment.','We made good progress toward the Tower today.',],provider_used: 'Offline Script',};116 unmodified lineschoice_suggestions: Array.isArray(parsed.choice_suggestions)? parsed.choice_suggestions: [],provider_used: parsed.provider_used || 'Tower Journey Agent Stream',});} catch (e) {console.warn('[CompanionAPI] Failed to parse done payload:', e);
81 unmodified lines8283848586878881 unmodified lines{activity && (<div className="mb-2 max-w-[120px] sm:max-w-xs text-center pointer-events-none animate-in fade-in duration-300"><span className="text-[9px] sm:text-[10px] font-mono font-medium text-[#bfe1ff] bg-[#101e2e]/85 px-2 sm:px-2.5 py-0.5 rounded-full border border-[#3e6080]/70 shadow-md inline-flex items-center gap-1 sm:gap-1.5 backdrop-blur-xs"><span className="text-amber-400">🏰</span><span className="truncate">{activity}</span></span></div>81 unmodified lines8283848586878881 unmodified lines{activity && (<div className="mb-2 max-w-[120px] sm:max-w-xs text-center pointer-events-none animate-in fade-in duration-300"><span className="text-[9px] sm:text-[10px] font-mono font-medium text-[#bfe1ff] bg-[#101e2e]/85 px-2 sm:px-2.5 py-0.5 rounded-full border border-[#3e6080]/70 shadow-md inline-flex items-center gap-1 sm:gap-1.5 backdrop-blur-xs"><span className="text-amber-400">⛺</span><span className="truncate">{activity}</span></span></div>
1234563 unmodified lines1011121314151617181918 unmodified lines383940414243444546474849505152import { useState } from 'react';import type React from 'react';import { Send, Sparkles } from 'lucide-react';interface ChoiceChipsProps {suggestions?: string[];3 unmodified lines}const DEFAULT_EMOTIONAL_CHIPS = [{ label: '💪 Solved a Tough One', prompt: 'I just solved a really tough problem! Felt so good getting all test cases to pass.' },{ label: '😩 Feeling Stuck', prompt: 'I feel really stuck and discouraged today. It feels like everyone else gets this except me.' },{ label: '☕ Need a Breather', prompt: 'My brain is pretty fried from practicing today. Can we just take a short breather?' },{ label: '🌙 Life Beyond the Tower', prompt: 'What’s the first thing you want to do once we break the seals and get you out of that tower?' },];export default function ChoiceChips({18 unmodified lines}};// If the agent returned custom dynamic suggestions, format themconst hasDynamicSuggestions = Array.isArray(suggestions) && suggestions.length > 0;return (<div className="w-full flex flex-col items-center gap-2 select-none z-10">{/* 1-Click Interactive Choice Chips */}<div className="w-full max-w-xl flex items-center justify-center gap-1.5 flex-wrap py-1.5 px-2">{hasDynamicSuggestions? suggestions.map((sug, idx) => (<buttonkey={idx}type="button"12345673 unmodified lines1112131415161718192018 unmodified lines39404142434445464748495051525354555657585960import { useState, useMemo } from 'react';import type React from 'react';import { Send, Sparkles } from 'lucide-react';import { filterUserPerspectiveChoices } from '../store/useCompanionStore';interface ChoiceChipsProps {suggestions?: string[];3 unmodified lines}const DEFAULT_EMOTIONAL_CHIPS = [{ label: '💪 Trial Conquered', prompt: 'We overcame a grueling trial on the road today! One step closer to the Tower.' },{ label: '🌧️ Treacherous Path', prompt: 'The trail is rugged and exhausting today. How are you holding up with your illness?' },{ label: '☕ Campfire Rest', prompt: 'Let us pause our march and rest by the campfire for a while.' },{ label: '✨ Hope for the Elixir', prompt: 'Once we reach the Tower and find the Elixir to cure you, where shall we travel next?' },];export default function ChoiceChips({18 unmodified lines}};const validSuggestions = useMemo(() => {if (Array.isArray(suggestions) && suggestions.length > 0) {return filterUserPerspectiveChoices(suggestions);}return [];}, [suggestions]);// If the agent returned custom dynamic suggestions, format themconst hasDynamicSuggestions = validSuggestions.length > 0;return (<div className="w-full flex flex-col items-center gap-2 select-none z-10">{/* 1-Click Interactive Choice Chips */}<div className="w-full max-w-xl flex items-center justify-center gap-1.5 flex-wrap py-1.5 px-2">{hasDynamicSuggestions? validSuggestions.map((sug, idx) => (<buttonkey={idx}type="button"
12345630 unmodified lines37383940414243444545 unmodified lines919293949596979899100170 unmodified lines27127227327427527627727827928028128228328428528656 unmodified lines34334434534634734834917 unmodified lines367368369370371372373import { useState, useEffect, useRef, useCallback, useMemo } from 'react';import type React from 'react';import type { PrincessEmotion, CompanionToolCall } from '../types';import {Castle,Scroll,30 unmodified lines}const DEFAULT_JRPG_CHOICES: string[] = ['I solved a tough task today!',"I'm feeling stuck on something.",'Just need a breather.',];const JRPG_FRAME_STYLE: React.CSSProperties = {45 unmodified lines// Determine active choices (dynamic from AI suggestions or 3 standard mockup choices)const activeChoices = useMemo(() => {if (Array.isArray(choices) && choices.length > 0) {return choices.slice(0, 4);}return DEFAULT_JRPG_CHOICES;}, [choices]);// Clamp highlighted index during render without an effectconst safeHighlightedIndex =170 unmodified linesclassName="absolute -top-7 right-1 flex items-center gap-1 sm:gap-1.5 z-30"onClick={(e) => e.stopPropagation()}>{/* Spire Journey Progress */}{onOpenProgress && (<buttontype="button"onClick={onOpenProgress}className="px-2 py-0.5 bg-[#101e2e]/90 hover:bg-[#1f3750] border border-[#3e6080]/80 hover:border-[#67b1ec] rounded text-[10px] sm:text-[11px] font-mono font-bold text-[#8cb4db] hover:text-white transition-all cursor-pointer flex items-center gap-1 shadow-md"title="Spire Tower Road (Floor Progress)"><Castle className="w-3 h-3 text-amber-400" /><span>{currentFloor}/150 LC</span></button>)}56 unmodified linestype="button"onClick={onClose}className="p-1 bg-[#101e2e]/90 hover:bg-rose-900/70 border border-[#3e6080]/80 hover:border-rose-400 rounded text-[#8cb4db] hover:text-rose-200 transition-all cursor-pointer shadow-md"title="Leave Parlor (Esc)"><X className="w-3 h-3" /></button>17 unmodified lines{isLoading ? (<div className="flex items-center gap-2 py-1 text-xs sm:text-sm font-mono text-[#8cb4db]"><span className="inline-block w-2 h-2 bg-[#f3cb65] rounded-full animate-ping" /><span>{characterName || 'Princess Aurelia'} is attuning the crystal relay...</span></div>) : (<div className="font-mono text-xs sm:text-sm md:text-[15px] leading-relaxed text-[#e6edf4] select-text">123456730 unmodified lines38394041424344454645 unmodified lines9293949596979899100101102103104170 unmodified lines27527627727827928028128228328428528628728828929056 unmodified lines34734834935035135235317 unmodified lines371372373374375376377import { useState, useEffect, useRef, useCallback, useMemo } from 'react';import type React from 'react';import type { PrincessEmotion, CompanionToolCall } from '../types';import { filterUserPerspectiveChoices } from '../store/useCompanionStore';import {Castle,Scroll,30 unmodified lines}const DEFAULT_JRPG_CHOICES: string[] = ['How is your strength holding up today?','Let us rest by the fire for a moment.','We made good progress toward the Tower today.',];const JRPG_FRAME_STYLE: React.CSSProperties = {45 unmodified lines// Determine active choices (dynamic from AI suggestions or 3 standard mockup choices)const activeChoices = useMemo(() => {if (Array.isArray(choices) && choices.length > 0) {const sanitized = filterUserPerspectiveChoices(choices, undefined, characterName);if (sanitized.length > 0) {return sanitized.slice(0, 4);}}return DEFAULT_JRPG_CHOICES;}, [choices, characterName]);// Clamp highlighted index during render without an effectconst safeHighlightedIndex =170 unmodified linesclassName="absolute -top-7 right-1 flex items-center gap-1 sm:gap-1.5 z-30"onClick={(e) => e.stopPropagation()}>{/* Tower Journey Progress */}{onOpenProgress && (<buttontype="button"onClick={onOpenProgress}className="px-2 py-0.5 bg-[#101e2e]/90 hover:bg-[#1f3750] border border-[#3e6080]/80 hover:border-[#67b1ec] rounded text-[10px] sm:text-[11px] font-mono font-bold text-[#8cb4db] hover:text-white transition-all cursor-pointer flex items-center gap-1 shadow-md"title="Road to the Tower (Leagues Progress)"><Castle className="w-3 h-3 text-amber-400" /><span>{currentFloor}/150 Leagues</span></button>)}56 unmodified linestype="button"onClick={onClose}className="p-1 bg-[#101e2e]/90 hover:bg-rose-900/70 border border-[#3e6080]/80 hover:border-rose-400 rounded text-[#8cb4db] hover:text-rose-200 transition-all cursor-pointer shadow-md"title="Rest by the Fire (Esc)"><X className="w-3 h-3" /></button>17 unmodified lines{isLoading ? (<div className="flex items-center gap-2 py-1 text-xs sm:text-sm font-mono text-[#8cb4db]"><span className="inline-block w-2 h-2 bg-[#f3cb65] rounded-full animate-ping" /><span>{characterName || 'Princess Aurelia'} is gathering her strength...</span></div>) : (<div className="font-mono text-xs sm:text-sm md:text-[15px] leading-relaxed text-[#e6edf4] select-text">
1234581 unmodified lines878889909192931 unmodified line9596979899100101102103104105106107108109110import { useState, useEffect, useMemo, useCallback } from 'react';import { useCompanionStore, companionStore } from '../store/useCompanionStore';import CharacterStage from './CharacterStage';import JRPGDialogueBox from './JRPGDialogueBox';import SpireProgressModal from './SpireProgressModal';81 unmodified lines}, [store.transcript]);const defaultDialogue ='Welcome back to the Spire Tower Parlor. How is your day going today? Are you making progress, or could you use a hand?';const dialogueText = latestPrincessTurn? latestPrincessTurn.isStreaming1 unmodified line: (latestPrincessTurn.text || (store.isLoading ? '' : defaultDialogue)): defaultDialogue;// Preserve choices across in-flight streaming turns so options don't disappear or jumpconst currentChoices = useMemo(() => {if (latestPrincessTurn?.choiceSuggestions && latestPrincessTurn.choiceSuggestions.length > 0) {return latestPrincessTurn.choiceSuggestions;}const previousWithChoices = [...store.transcript].reverse().find((t) => t.sender === 'princess' && t.choiceSuggestions && t.choiceSuggestions.length > 0);return previousWithChoices?.choiceSuggestions;}, [latestPrincessTurn, store.transcript]);const currentZIndex = zIndex ?? (isActive ? 40 : 30);1234567891081 unmodified lines929394959697981 unmodified line100101102103104105106107108109110111112113114115116117118119120121122123124125126127128import { useState, useEffect, useMemo, useCallback } from 'react';import {useCompanionStore,companionStore,filterUserPerspectiveChoices,DEFAULT_USER_CHOICES,} from '../store/useCompanionStore';import CharacterStage from './CharacterStage';import JRPGDialogueBox from './JRPGDialogueBox';import SpireProgressModal from './SpireProgressModal';81 unmodified lines}, [store.transcript]);const defaultDialogue ='Welcome back to camp. How is your strength holding up today? Are you ready to continue our journey, or would you like to rest for a while?';const dialogueText = latestPrincessTurn? latestPrincessTurn.isStreaming1 unmodified line: (latestPrincessTurn.text || (store.isLoading ? '' : defaultDialogue)): defaultDialogue;// Preserve choices across in-flight streaming turns and ensure they are user-to-princessconst currentChoices = useMemo(() => {const raw =latestPrincessTurn?.choiceSuggestions && latestPrincessTurn.choiceSuggestions.length > 0? latestPrincessTurn.choiceSuggestions: [...store.transcript].reverse().find((t) => t.sender === 'princess' && t.choiceSuggestions && t.choiceSuggestions.length > 0)?.choiceSuggestions;const sanitized = filterUserPerspectiveChoices(raw,store.heroCodex?.heroName || store.heroProfile?.heroName || 'Champion',store.companionSettings.name || 'Princess Aurelia');return sanitized.length > 0 ? sanitized : DEFAULT_USER_CHOICES;}, [latestPrincessTurn,store.transcript,store.heroCodex?.heroName,store.heroProfile?.heroName,store.companionSettings.name,]);const currentZIndex = zIndex ?? (isActive ? 40 : 30);
124 unmodified lines125126127128129130131124 unmodified lines{store.companionSettings.name || 'Princess Aurelia'}</span><span className="bg-ink-black text-[#FFE24C] text-[9px] font-bold font-arcade px-1.5 py-0.5 rounded shrink-0">{store.currentFloor}/150 LC</span></div>124 unmodified lines125126127128129130131124 unmodified lines{store.companionSettings.name || 'Princess Aurelia'}</span><span className="bg-ink-black text-[#FFE24C] text-[9px] font-bold font-arcade px-1.5 py-0.5 rounded shrink-0">{store.currentFloor}/150 Leagues</span></div>
169 unmodified lines17017117217317417517621 unmodified lines19819920020120220320474 unmodified lines27928028128228328428527 unmodified lines313314315316317318319169 unmodified lines<div className="flex-1 flex flex-col items-center justify-center text-center p-6 text-slate-500"><Lock className="w-8 h-8 mb-2 text-slate-400" /><p className="text-xs font-medium">Conquer 30 LeetCode problems along the path to receive your first Royal Missive from Aurelia.</p></div>)}21 unmodified lines<div className="flex-1 flex flex-col items-center justify-center text-center p-6 text-slate-500"><BookOpen className="w-8 h-8 mb-2 text-slate-400" /><p className="text-xs font-medium">Aurelia records entries in her Spire Chronicles autonomously as you chat, rest, and cross chapter milestones.</p></div>)}74 unmodified lines</div>) : (<p className="text-[11px] text-slate-400 italic m-0">Aurelia will note topics you conquer during your practice.</p>)}</div>27 unmodified lines</div>) : (<p className="text-[11px] text-slate-400 italic m-0">Aurelia tracks patterns that give you trouble to help you prepare targeted drills.</p>)}</div>169 unmodified lines17017117217317417517621 unmodified lines19819920020120220320474 unmodified lines27928028128228328428527 unmodified lines313314315316317318319169 unmodified lines<div className="flex-1 flex flex-col items-center justify-center text-center p-6 text-slate-500"><Lock className="w-8 h-8 mb-2 text-slate-400" /><p className="text-xs font-medium">Travel 30 leagues along the path to unlock your first missive from Aurelia.</p></div>)}21 unmodified lines<div className="flex-1 flex flex-col items-center justify-center text-center p-6 text-slate-500"><BookOpen className="w-8 h-8 mb-2 text-slate-400" /><p className="text-xs font-medium">Aurelia records entries in her travel journal as you journey together, rest by the fire, and cross chapter milestones.</p></div>)}74 unmodified lines</div>) : (<p className="text-[11px] text-slate-400 italic m-0">Aurelia will note trials you conquer along our journey.</p>)}</div>27 unmodified lines</div>) : (<p className="text-[11px] text-slate-400 italic m-0">Aurelia tracks difficult trials to help you prepare targeted drills.</p>)}</div>
14 unmodified lines151617181920212223242510 unmodified lines3637383940414214 unmodified linesconst progressPercent = Math.min(100, Math.round((currentFloor / 150) * 100));const milestones = [{ floor: 30, label: 'Arrays' },{ floor: 60, label: 'Pointers' },{ floor: 90, label: 'Trees' },{ floor: 120, label: 'Heaps' },{ floor: 150, label: 'Spire' },];return (10 unmodified lines<div className="flex items-center gap-2"><Castle className="w-5 h-5 text-indigo-600" /><h4 className="font-headline-md font-bold text-sm text-ink-black m-0">Journey to the Big-O Spire</h4></div><button14 unmodified lines151617181920212223242510 unmodified lines3637383940414214 unmodified linesconst progressPercent = Math.min(100, Math.round((currentFloor / 150) * 100));const milestones = [{ floor: 30, label: 'Plains' },{ floor: 60, label: 'Forest' },{ floor: 90, label: 'Caverns' },{ floor: 120, label: 'Passes' },{ floor: 150, label: 'The Tower' },];return (10 unmodified lines<div className="flex items-center gap-2"><Castle className="w-5 h-5 text-indigo-600" /><h4 className="font-headline-md font-bold text-sm text-ink-black m-0">Journey to the Tower of the Elixir</h4></div><button
52 unmodified lines535455565758596061626364656652 unmodified linesglowColor: 'rgba(192, 132, 252, 0.4)',badgeLabel: '🔮 Arcane Runes',},// Chapter 6: Big-O Spire (Floor 150)6: {particleType: 'stardust',particleCount: 35,particleColors: ['#FDE047', '#F59E0B', '#E11D48', '#818CF8'],gradientBg: 'from-[#FFFBEB] via-[#FEF3C7] to-[#FFE4E6]',glowColor: 'rgba(245, 158, 11, 0.5)',badgeLabel: '👑 Spire Gates',},};52 unmodified lines535455565758596061626364656652 unmodified linesglowColor: 'rgba(192, 132, 252, 0.4)',badgeLabel: '🔮 Arcane Runes',},// Chapter 6: Tower of the Elixir (Floor 150)6: {particleType: 'stardust',particleCount: 35,particleColors: ['#FDE047', '#F59E0B', '#E11D48', '#818CF8'],gradientBg: 'from-[#FFFBEB] via-[#FEF3C7] to-[#FFE4E6]',glowColor: 'rgba(245, 158, 11, 0.5)',badgeLabel: '✨ Tower of the Elixir',},};
2 unmodified lines345678910111213141516171819202122232425262728293031323334353637383940418 unmodified lines505152535455565758596061626364656667686970717273747576777879808182838485865 unmodified lines92939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391402 unmodified linesexport const TOWER_CHAPTERS: TowerChapter[] = [{floorRange: [1, 30],title: 'The Plains of Arrays & Strings',description: 'Rolling green meadows and ancient cobblestone roads where foundational endurance is forged.',bgLore: 'Looking out towards the distant horizon, the silhouette of the Big-O Spire pierces the clouds.',},{floorRange: [31, 60],title: 'The Whispering Forest of Pointers',description: 'Winding paths through dense emerald groves where two pointers navigate labyrinthine trails.',bgLore: 'Aurelia’s beacon shines above the canopy, guiding your compass through tangled groves.',},{floorRange: [61, 90],title: 'The Grand Caverns of Trees & Graphs',description: 'Bioluminescent caves with branching crystal arches and subterranean passes.',bgLore: 'Halfway to the tower! Her voice echoes with hope over the enchanted royal crystal relay.',},{floorRange: [91, 120],title: 'The High Mountain Passes of Heaps & Backtracking',description: 'Perilous alpine ridges and snowy peaks overlooking the deep Spire valley.',bgLore: 'From the highest ridge, the base of the Spire is in sight through the swirling mountain mist!',},{floorRange: [121, 149],title: 'The Enchanted Valley of Dynamic Programming',description: 'Shimmering mystical grounds where optimal decisions bridge the final moat.',bgLore: 'The final leagues! The Spire looms directly ahead, its ancient runic wards trembling.',},{floorRange: [150, 150],title: 'The Gates of the Big-O Spire',description: 'Standing at the threshold of the grand obsidian gates to shatter the seal and free Aurelia!',bgLore: '150 algorithmic leagues conquered! You have completed the grand journey and reached the Spire!',},];8 unmodified lines30: {id: 'letter-30',floor: 30,chapterTitle: 'The Plains of Arrays & Strings',title: 'A Courier from the Open Plains',letterText: `My Dearest Champion,\n\nFrom the highest window of the Spire, I watched your travel banner cross the border stones of the open plains. Thirty leagues conquered!\n\nWhere many lose heart in the first days of travel, your steps have grown swifter with every problem. Ahead lies the Whispering Forest—dense and shadowed, but fear not: your compass is true.\n\nRest by the brook tonight. I have set the northern beacon to burn through the night in your honor.\n\nWith growing hope,\nAurelia`,},60: {id: 'letter-60',floor: 60,chapterTitle: 'The Whispering Forest of Pointers',title: 'The Falcon Over the Canopy',letterText: `Noble Friend,\n\nMy falcon returns carrying the scent of pine and pinecone dust from your camp! Sixty leagues! You have navigated the winding labyrinth of pointers and emerged into open foothills.\n\nI can see the glow of your campfire even without the glass. Do you know how long it has been since someone traveled this royal road? The kingdom had begun to forget, but your discipline is breathing life back into these lands.\n\nTake this moment to drink deep and stretch your limbs. The subterranean caverns ahead are dark, but we shall illuminate every cavern together.\n\nSteadfastly yours,\nAurelia`,},90: {id: 'letter-90',floor: 90,chapterTitle: 'The Grand Caverns of Trees & Graphs',title: 'Echoes in the Crystal Chasm',letterText: `My Cherished Champion,\n\nNinety problems mastered! More than halfway to the gates!\n\nWhen the magical relays shook earlier today, I knew you had emerged from the deep crystal arches. The sheer complexity of those subterranean paths would have broken an ordinary will. But you navigated every branch and node with patience.\n\nThe icy peaks of the High Passes loom next. Wear your warm cloak and do not hurry your steps—stamina is the secret to cresting the high mountains.\n\nEver watching over you,\nAurelia`,},120: {id: 'letter-120',floor: 120,chapterTitle: 'The High Mountain Passes',title: 'Light Across the Snowy Summit',letterText: `My Legendary Hero,\n\nOne hundred and twenty leagues! From my tower balcony, I watched your lantern flare as you stepped onto the high alpine ridge overlooking the valley.\n\nThe Spire is in plain sight now. Its obsidian spires and ancient runic rings tremble in the wind. Only the Enchanted Valley of Dynamic Programming stands between your boots and the grand courtyard gates.\n\nWhatever fear or fatigue tries to whisper to you tonight, cast it into the mountain wind. You have proven yourself ten times over.\n\nWith all my heart,\nAurelia`,},150: {id: 'letter-150',floor: 150,chapterTitle: 'The Gates of the Big-O Spire',title: 'The Shattering of the Seals',letterText: `TO MY DELIVERER AND CHAMPION,\n\nALL ONE HUNDRED AND FIFTY LEAGUES CONQUERED!\n\nThe five chromatic seals have shattered into glittering dust across the obsidian courtyard! The doors of the Spire swing open to the morning sun for the first time in an age.\n\nYou did not just conquer a list of problems—you demonstrated the rarest virtue in all the kingdoms: relentless, patient, unyielding mastery.\n\nThe tower is open. Step through the archway, hero—let us walk out into the sunlight together.\n\nFree at last,\nAurelia`,},};5 unmodified linesexport const OFFLINE_FALLBACK_DIALOGUES: Record<string, OfflineDialogue[]> = {problem_correct: [{text: 'Yes! Nicely done. Getting a stubborn problem to pass cleanly always feels so satisfying.',emotion: 'excited_expression',},{text: 'Look at that—another one down! You’re really finding your rhythm today.',emotion: 'smiling_warmly',},{text: 'Awesome job! Step by step, you’re steadily working your way through all of these.',emotion: 'smiling_warmly',},],problem_incorrect: [{text: 'Hey, don’t sweat it. Even seasoned engineers stumble on test cases constantly. We can always look at the edge cases again.',emotion: 'concerned',},{text: 'Take a breath. Getting stuck isn’t failing—it’s literally just your brain building the intuition for the next time.',emotion: 'thinking_expression',},{text: 'Ugh, those hidden edge cases can be ruthless. Give your mind a minute to clear, then come back to it with fresh eyes.',emotion: 'smiling_warmly',},],break_reminder: [{text: 'Hey, you’ve been at this for a while. Go grab some water and stretch your shoulders for five minutes—trust me, you’ve earned it.',emotion: 'concerned',},{text: 'Quick check-in: how are your eyes feeling? Step away from the screen for just a few minutes.',emotion: 'smiling_warmly',},],idle_chat: [{text: 'Hey! Thanks for stopping by to chat. How’s your headspace today?',emotion: 'smiling_warmly',},{text: 'Whenever the whole 150-problem journey feels overwhelming, just remember: you only ever have to solve the one in front of you.',emotion: 'thinking_expression',},],2 unmodified lines345678910111213141516171819202122232425262728293031323334353637383940418 unmodified lines505152535455565758596061626364656667686970717273747576777879808182838485865 unmodified lines92939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391402 unmodified linesexport const TOWER_CHAPTERS: TowerChapter[] = [{floorRange: [1, 30],title: 'The Sunlit Plains',description: 'Rolling green meadows and ancient cobblestone trails where our journey begins.',bgLore: 'Looking out toward the distant horizon, the silhouette of the Ancient Tower pierces the morning sky.',},{floorRange: [31, 60],title: 'The Whispering Forest',description: 'Winding paths through dense emerald groves where gentle streams and leafy canopies shade our travel.',bgLore: 'Resting in the wagon beneath the tall pines, Aurelia listens to the wind and dreams of the healing elixir.',},{floorRange: [61, 90],title: 'The Grand Caverns',description: 'Bioluminescent caves with branching crystal arches and subterranean passes.',bgLore: 'Halfway to the Tower! The gentle warmth of glowing crystals brings solace as we push through the deep caverns.',},{floorRange: [91, 120],title: 'The High Mountain Passes',description: 'Perilous alpine ridges and snowy peaks overlooking the great valley below.',bgLore: 'From the highest ridge through the swirling mist, the Sanctuary Tower rises majestically ahead.',},{floorRange: [121, 149],title: 'The Enchanted Valley',description: 'Shimmering mystical grounds and flowering sanctuaries that surround the final approach.',bgLore: 'The final leagues! The Tower gates are within sight, where the Elixir of Life awaits.',},{floorRange: [150, 150],title: 'The Tower of the Elixir',description: 'Crossing the threshold of the Ancient Sanctuary to claim the Elixir of Life and cure Aurelia!',bgLore: 'All 150 leagues conquered! The Elixir of Life is in your hands, and Aurelia’s life is saved!',},];8 unmodified lines30: {id: 'letter-30',floor: 30,chapterTitle: 'The Sunlit Plains',title: 'A Note by the Morning Hearth',letterText: `My Cherished Guardian,\n\nThirty leagues already lie behind our carriage wheels! When we first set out from the capital, my heart was heavy with the shadow of this illness. But watching you lead the way across these open plains, day after day, has given me a strength no tonic could ever offer.\n\nThe coughing still grips me when the night wind blows cold, but seeing your steady hand on the reins warms my spirits. Ahead lie the deep shadows of the Whispering Forest.\n\nRest well beside the stream tonight. As long as you are near, I know we will reach the Tower.\n\nWith all my gratitude,\nAurelia`,},60: {id: 'letter-60',floor: 60,chapterTitle: 'The Whispering Forest',title: 'Fallen Leaves in the Satchel',letterText: `Dearest Friend,\n\nSixty leagues traversed! We have made our way through the dense emerald groves of the Whispering Forest and reached the foothills.\n\nToday, when my fever spiked and my knees gave out along the rocky path, you didn’t hesitate to carry the pack and support my steps without a word of complaint. I tucked a pressed golden leaf into your satchel while you were kindling our campfire.\n\nThe ancient mountains loom ahead, and the air grows thin and cold. But every step we take together brings us closer to the Tower and the Elixir that will heal me.\n\nEver grateful,\nAurelia`,},90: {id: 'letter-90',floor: 90,chapterTitle: 'The Grand Caverns',title: 'Glow of the Crystal Embers',letterText: `My Steadfast Protector,\n\nNinety leagues! More than halfway to the Sanctuary Tower!\n\nEmerging from those dark subterranean caverns into the starlight tonight felt like waking from a long dream. My strength waxes and wanes—some mornings I can barely rise—yet seeing your calm determination keeps the darkness from taking hold.\n\nThe alpine passes ahead will be harsh and snowy. Please, wrap yourself in the woolen cloak by the fire and drink warm broth. You spend so much care tending to my illness; do not forget to care for yourself as well.\n\nWith all my heart,\nAurelia`,},120: {id: 'letter-120',floor: 120,chapterTitle: 'The High Mountain Passes',title: 'Beacon Over the Alpine Ridge',letterText: `My Brave Companion,\n\nOne hundred and twenty leagues conquered!\n\nAs we crested the snowy summit this evening, the clouds parted below. There it was—the Tower of the Elixir, rising tall and radiant in the valley below. For the first time since this sickness fell upon me, I felt tears of pure hope.\n\nOnly the Enchanted Valley remains between our boots and the sanctuary gates. The illness weighs heavily on my chest tonight, but my spirit has never felt lighter. You have brought me across the world through sheer courage and patience.\n\nWe are going to make it.\n\nDevotedly yours,\nAurelia`,},150: {id: 'letter-150',floor: 150,chapterTitle: 'The Tower of the Elixir',title: 'The Elixir of Life',letterText: `TO MY SAVIOR AND BELOVED COMPANION,\n\nWE HAVE REACHED THE TOWER!\n\nAll one hundred and fifty leagues conquered together! The grand doors of the ancient sanctuary have opened to us, and the crystal phial of the Elixir of Life glows upon the altar.\n\nAs the cool draught touches my lips, the fever recedes and the heavy darkness that has shadowed my chest for so long dissipates like morning mist. Color returns to my skin, and breath fills my lungs with ease.\n\nYou did not just guide me across rivers, caverns, and frozen peaks—you saved my life through unwavering loyalty, courage, and perseverance.\n\nTake my hand. The sickness is gone, the road is behind us, and a bright new dawn awaits us both.\n\nHealed and forever grateful,\nAurelia`,},};5 unmodified linesexport const OFFLINE_FALLBACK_DIALOGUES: Record<string, OfflineDialogue[]> = {problem_correct: [{text: 'Yes! That trial is behind us. Every league we conquer brings us closer to the Tower and the Elixir.',emotion: 'excited_expression',},{text: 'You handled that so skillfully! Seeing your strength on the road fills my heart with hope.',emotion: 'smiling_warmly',},{text: 'Another milestone reached! Step by step, our journey moves forward.',emotion: 'smiling_warmly',},],problem_incorrect: [{text: 'Do not be discouraged, my friend. Rugged roads have treacherous footing—we take a breath and try again.',emotion: 'concerned',},{text: 'Take a moment to rest. Stumbling on the trail is not defeat; it merely shows us the rocks to avoid next time.',emotion: 'thinking_expression',},{text: 'It is alright. Even the most seasoned travelers lose their footing sometimes. Let us look at the path with fresh eyes.',emotion: 'smiling_warmly',},],break_reminder: [{text: 'Hey, you have been marching hard for hours. Come sit by the campfire and drink some water—you have more than earned a rest.',emotion: 'concerned',},{text: 'A gentle reminder: your stamina matters just as much as our speed. Let us pause for a few minutes to rest your eyes.',emotion: 'smiling_warmly',},],idle_chat: [{text: 'Hey! I am so glad to sit and talk with you. How are you holding up with our journey today?',emotion: 'smiling_warmly',},{text: 'Whenever the long road feels daunting, look at how far we have already traveled together. We only need to take the next step.',emotion: 'thinking_expression',},],
14 unmodified lines1516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656645 unmodified lines1121131141151161171186 unmodified lines12512612712812913013114 unmodified linesstate: 'dawn',label: 'Morning Sunbreak',hourRange: [6, 12],activity: 'Sipping warm mountain tea and watching the sunrise over the valley',lightingClass: 'from-amber-100/90 via-yellow-50/80 to-amber-200/50',defaultEmotion: 'smiling_warmly',greetings: ['Morning! The sunrise looks pretty incredible from up here today. How are you feeling—ready to solve a few problems, or still waiting for your coffee to kick in?','Hey, good morning! Did you get some good rest? Don’t rush into the hardest problems right away—let’s ease in with a warmup.','Good morning! It’s really quiet and peaceful right now. Honestly the best time to get some focused thinking done before the rest of the world wakes up.',],},day: {state: 'day',label: 'High Sun',hourRange: [12, 18],activity: 'Reviewing architectural scrolls in the tower library',lightingClass: 'from-sky-100/80 via-amber-50/70 to-yellow-100/60',defaultEmotion: 'neutral',greetings: ['Hey, welcome back! How’s your focus holding up today? Remember to step back and take a breath if your eyes start feeling tired.','Hey there! I was just organizing some notes in the tower library. What problem pattern are we working through right now?','Good to see you! Remember, steady consistency beats frantic cramming every single time. One clean solution at a time.',],},dusk: {state: 'dusk',label: 'Twilight & Beacon Fire',hourRange: [18, 22],activity: 'Lighting lanterns along the stone balcony as the sun sets',lightingClass: 'from-orange-100/90 via-purple-100/60 to-amber-200/70',defaultEmotion: 'smiling_warmly',greetings: ['Evening! You’ve put in solid effort today. How are you feeling—ready to wrap things up, or finishing one last review?','Hey, the sun is setting over the valley. It’s so easy to lose track of time when deep in code. Make sure you stretch your neck and shoulders a bit.','Good evening! How did today’s practice go? Even getting through one tricky problem is real, meaningful progress.',],},night: {state: 'night',label: 'Midnight Candlelight',hourRange: [22, 6],activity: 'Listening to the quiet wind outside by soft candlelight',lightingClass: 'from-indigo-950/80 via-slate-900/90 to-amber-950/40 text-amber-100',defaultEmotion: 'concerned',greetings: ['Hey... it’s getting really late. Are you okay? Late-night debugging usually just turns simple typos into monsters—promise me you’ll head to sleep soon.','Midnight already? I’m always glad to talk with you, but coding while exhausted will just burn you out. Take it easy tonight, okay?','Still awake? Don’t push yourself past your limit. Your brain actually reorganizes problem solutions while you sleep—go rest up for tomorrow.',],},};45 unmodified linesemotion: PrincessEmotion;} {return {text: `Hey, ${heroName}... ${consecutiveFailures} misses in a row is almost always mental fatigue, not a lack of ability. Step away from the screen for just five minutes, grab a drink of water, and let your head clear. You’ll see the solution much faster once you reset.`,emotion: 'concerned',};}6 unmodified linesemotion: PrincessEmotion;} {return {text: `*frowns softly in the candlelight* ${heroName}, burning midnight oil will dull your blade for tomorrow. The Spire will wait for you; your well-being cannot. Shall we wind down by the campfire?`,emotion: 'concerned',};}14 unmodified lines1516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656645 unmodified lines1121131141151161171186 unmodified lines12512612712812913013114 unmodified linesstate: 'dawn',label: 'Morning Sunbreak',hourRange: [6, 12],activity: 'Sharing warm mountain tea by the campfire as the sun breaks over the trail',lightingClass: 'from-amber-100/90 via-yellow-50/80 to-amber-200/50',defaultEmotion: 'smiling_warmly',greetings: ['Morning! The sunrise over the valley is breathtaking today. How are you feeling—ready to continue our journey, or shall we take a quiet moment first?','Hey, good morning! Did you get some good rest? The road ahead is long, so let us take our morning steps with calm and steady resolve.','Good morning! It is so quiet and peaceful at daybreak. Truly the best time to steady our spirits before setting out on the trail.',],},day: {state: 'day',label: 'High Sun',hourRange: [12, 18],activity: 'Resting in the shade of the wagon canopy and watching the distant horizon',lightingClass: 'from-sky-100/80 via-amber-50/70 to-yellow-100/60',defaultEmotion: 'neutral',greetings: ['Welcome back! How is your stamina holding up today? Remember to rest in the shade if the midday sun grows too warm.','Hey there! I was just studying our travel map of the realms ahead. How are you feeling about the trail today?','Good to see you! Remember, steady footsteps carry us much further than reckless haste. One league at a time.',],},dusk: {state: 'dusk',label: 'Twilight & Campfire',hourRange: [18, 22],activity: 'Kindling the evening campfire as twilight settles over the hills',lightingClass: 'from-orange-100/90 via-purple-100/60 to-amber-200/70',defaultEmotion: 'smiling_warmly',greetings: ['Good evening! You put in so much effort on the road today. How are you feeling—ready to wind down by the embers, or resting a moment?','The sun is dipping below the mountain peaks. It is so easy to lose track of time when focused on the road. Let us stretch by the fire.','Good evening! Another stretch of trail behind us. Every single league conquered brings us closer to the Tower and the Elixir.',],},night: {state: 'night',label: 'Midnight Candlelight',hourRange: [22, 6],activity: 'Resting wrapped in her traveling cloak beside the warm hearth embers',lightingClass: 'from-indigo-950/80 via-slate-900/90 to-amber-950/40 text-amber-100',defaultEmotion: 'concerned',greetings: ['Hey... it is getting late. Are you alright? Traveling in the dead of night will only sap your strength—please promise me you will sleep soon.','Midnight already? I am always happy to speak with you, but walking the trail while exhausted will only wear you down. Rest easy tonight, okay?','Still awake? Do not push yourself past your limits. Your body and mind need deep rest to face tomorrow’s journey. Sleep well.',],},};45 unmodified linesemotion: PrincessEmotion;} {return {text: `Hey, ${heroName}... facing ${consecutiveFailures} grueling trials in a row is almost always exhaustion, not a lack of strength. Come sit by the campfire for five minutes, drink some fresh water, and let your head clear. The way forward will be much clearer once you rest.`,emotion: 'concerned',};}6 unmodified linesemotion: PrincessEmotion;} {return {text: `*frowns softly in the candlelight* ${heroName}, pushing through the dead of night will only dull your senses for tomorrow. The Tower will wait for us; your well-being cannot. Shall we rest by the fire tonight?`,emotion: 'concerned',};}
55 unmodified lines56575859606162140 unmodified lines203204205206207208209210211212213214215216217218219220221222223224225232 unmodified lines45845946046146246346432 unmodified lines49749849950050150250350450510 unmodified lines5165175185195205215221 unmodified line52452552652752852953053117 unmodified lines54955055155255355421 unmodified lines57657757857958058155 unmodified lines63763863964064164264311 unmodified lines6556566576586596606617 unmodified lines6696706716726736746755 unmodified lines6816826836846856866876889 unmodified lines6986997007017027038 unmodified lines7127137147157167171 unmodified line71972072172272372427 unmodified lines7527537547557567576 unmodified lines76476576676776876977077177277355 unmodified linesenabled: true,name: 'Princess Aurelia',backstory:'Princess Aurelia is a noble, intelligent, and deeply caring scholar-princess trapped inside the Spire of Big-O Complexity. You are her champion traveling the 150 leagues of the royal road to break her magical seals.',breakIntervalMinutes: 25,soundEnabled: true,autoPopupEnabled: true,140 unmodified linesreturn 'Acquaintance';}function loadInitialState(): CompanionStoreState {const rhythm = getTowerRhythm();const defaultInitialTurn: ChatTurn = {id: 'turn-init',sender: 'princess',text: `Hey! I’m Aurelia. It gets pretty quiet up here in the tower, so I’m really glad you stopped by. How are you holding up with your coding practice today?`,emotion: 'smiling_warmly',timestamp: Date.now(),provider: 'Spire Relay',};try {const raw = localStorage.getItem(STORAGE_KEY);if (raw) {const parsed = JSON.parse(raw);const transcript = Array.isArray(parsed.transcript) && parsed.transcript.length > 0? parsed.transcript: [defaultInitialTurn];const userMessageCount = transcript.filter((t: ChatTurn) => t.sender === 'user').length;232 unmodified linesemotion: 'thinking_expression',timestamp: Date.now(),isStreaming: true,provider: 'Spire Agent Stream',};updateState({32 unmodified lines{onDelta: (delta: string) => {accumulatedText += delta;const updated = currentState.transcript.map((t) =>t.id === streamingTurnId? { ...t, text: accumulatedText, isStreaming: true }: t);updateState({10 unmodified lines}}const finalText = response.text || accumulatedText || `I believe in you, champion!`;const finalized = currentState.transcript.map((t) =>t.id === streamingTurnId? {1 unmodified linetext: finalText,emotion: response.emotion,toolCalls: response.tool_calls,choiceSuggestions: response.choice_suggestions,provider: response.provider_used || 'Spire Agent Stream',isStreaming: false,}: t17 unmodified lines...t,text: fallback.text,emotion: fallback.emotion,provider: 'Offline Script',isStreaming: false,}21 unmodified linesemotion: fallback.emotion,timestamp: Date.now(),provider: 'Offline Script',isStreaming: false,};55 unmodified linesid: `ep-${Date.now()}`,timestamp: Date.now(),type: isCorrect ? 'victory' : 'struggle',summary: `${isCorrect ? 'Mastered' : 'Faced'} ${problemName} (${pattern || 'DSA'}) - Graded ${rating}`,floor: newFloor,};11 unmodified linescompanionStore.recordEpisodicEvent({eventType: 'milestone',title: `Passed League ${milestoneFloor}`,description: `Advanced past League ${milestoneFloor} on the road to the Spire of Big-O! Unlocked a royal missive from Aurelia.`,relatedPattern: pattern,emotionalTone: 'excited_expression',});7 unmodified linescompanionStore.recordEpisodicEvent({eventType: 'breakthrough',title: `Breakthrough: ${problemName}`,description: `Broke through previous hurdles to solve ${problemName}${pattern ? ` (${pattern})` : ''} flawlessly!`,relatedPattern: pattern,emotionalTone: 'excited_expression',contiguousEventId: recentStruggle?.id,5 unmodified lines// SCME: Record Fatigue Episode NodecompanionStore.recordEpisodicEvent({eventType: 'fatigue_episode',title: `Fatigue: ${pattern || problemName}`,description: `Encountered 3 consecutive review struggles, most recently on ${problemName}${pattern ? ` (${pattern})` : ''}. Aurelia intervened with rest advice.`,relatedPattern: pattern,emotionalTone: 'concerned',});9 unmodified linesemotion: fatigue.emotion,timestamp: Date.now(),provider: 'Fatigue Watchdog',};updateState({transcript: [...currentState.transcript, fatigueTurn],8 unmodified linesconst fallbackPool = OFFLINE_FALLBACK_DIALOGUES[fallbackCategory];const fallback = fallbackPool[Math.floor(Math.random() * fallbackPool.length)];const reactionTurn: ChatTurn = {id: `rev-${Date.now()}`,sender: 'princess',1 unmodified lineemotion: fallback.emotion,timestamp: Date.now(),provider: 'Journey Log',};updateState({27 unmodified linesemotion: greeting.emotion,timestamp: now,provider: 'Tower Rhythm',};updateState({6 unmodified linesconst defaultTurn: ChatTurn = {id: `init-${Date.now()}`,sender: 'princess',text: `The slate is refreshed, champion! How may I accompany your algorithmic journey right now?`,emotion: 'smiling_warmly',timestamp: Date.now(),provider: 'Spire Relay',};updateState({transcript: [defaultTurn],55 unmodified lines56575859606162140 unmodified lines203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320232 unmodified lines55355455555655755855932 unmodified lines59259359459559659759859960060160260360460510 unmodified lines6166176186196206216226236246256266276286296306316326336346356366376381 unmodified line64064164264364464564664717 unmodified lines66566666766866967067121 unmodified lines69369469569669769869955 unmodified lines75575675775875976076111 unmodified lines7737747757767777787797 unmodified lines7877887897907917927935 unmodified lines7998008018028038048058069 unmodified lines8168178188198208218228238248258268 unmodified lines8358368378388398408418428438448458468478488498508518521 unmodified line85485585685785885986027 unmodified lines8888898908918928938946 unmodified lines90190290390490590690790890991091155 unmodified linesenabled: true,name: 'Princess Aurelia',backstory:'Princess Aurelia is suffering from a severe, fatal illness, traveling alongside you across 150 leagues toward the ancient Tower where the mythical Elixir of Life can cure her. As her sworn guardian and companion, you journey together across dangerous wilderness, facing grueling trials to reach the Elixir before time runs out.',breakIntervalMinutes: 25,soundEnabled: true,autoPopupEnabled: true,140 unmodified linesreturn 'Acquaintance';}export const FORBIDDEN_IMMERSION_REGEX =/\b(algorithm|algorithms|algorithmic|dsa|leetcode|hackerrank|codeforces|big-o|time complexity|space complexity|test cases?|edge cases?|syntax|debugging|debugger|compiling|compiler|recursion|recursive|binary search tree|hash map|hashmap|linked list|dynamic programming|coding|codebase|source code)\b/i;export const DEFAULT_USER_CHOICES: string[] = ['How is your strength holding up today?','Let us rest by the fire for a moment.','We made good progress toward the Tower today.',];function escapeRegex(str: string): string {return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');}/*** Validates and filters dialogue choices so they are strictly written* from the user/hero's perspective speaking TO the princess.*/export function filterUserPerspectiveChoices(choices: string[] | undefined | null,heroName: string = 'Champion',princessName: string = 'Princess Aurelia'): string[] {if (!Array.isArray(choices) || choices.length === 0) return [];const heroTerms = ['champion','guardian','traveler','wanderer','hero','my friend','my protector','my companion','my savior','brave friend','dear friend','noble friend',];const cleanHero = typeof heroName === 'string' ? heroName.trim() : '';if (cleanHero) {heroTerms.unshift(escapeRegex(cleanHero));}const heroRegex = new RegExp(`(?<!\\w)(?:${heroTerms.join('|')})(?!\\w)`, 'i');const illnessFirstPersonRegex = new RegExp('\\b(' +'my\\s+(fever|illness|sickness|cough|weakness|ailment|lungs|chest|throat)' +'|i(\'?m| am)?\\s*(feel(ing)?\\s+)?(so\\s+|very\\s+|too\\s+|a bit\\s+|rather\\s+)?(weak|faint|dizzy|feverish|sick|nauseous)' +'|i\\s+(cannot|can\'t)\\s+(walk|breathe|stand)' +'|my\\s+(strength|energy)\\s+is\\s+(fading|gone|failing)' +'|my\\s+(head|chest|body)\\s+(hurts|aches|spins)' +'|i\\s+need\\s+to\\s+lie\\s+down' +')\\b','i');const roleReversalRegex = new RegExp('\\b(' +'thank\\s+you\\s+for\\s+(protecting|saving|guiding|carrying|tending to|watching over)\\s+me' +'|you\\s+must\\s+be\\s+(tired|exhausted|weary)' +'|rest\\s+your\\s+weary' +')\\b','i');const cleanPrincess = typeof princessName === 'string' && princessName.trim() ? princessName.trim() : 'Princess Aurelia';const firstName = cleanPrincess.split(/\s+/).pop() || 'Aurelia';const escapedFirst = escapeRegex(firstName);const princessThirdPersonRegex = new RegExp(`\\b(princess\\s+${escapedFirst}|${escapedFirst})\\s+(is|was|feels|seems|looks|rests|lies|remains|pauses|sleeps)\\b`,'i');return choices.map((c) => (typeof c === 'string' ? c.trim().replace(/^["']|["']$/g, '') : '')).filter((c) => {if (!c) return false;if (FORBIDDEN_IMMERSION_REGEX.test(c)) return false;if (heroRegex.test(c)) return false;if (illnessFirstPersonRegex.test(c)) return false;if (roleReversalRegex.test(c)) return false;if (princessThirdPersonRegex.test(c)) return false;return true;});}function loadInitialState(): CompanionStoreState {const rhythm = getTowerRhythm();const defaultInitialTurn: ChatTurn = {id: 'turn-init',sender: 'princess',text: `Hey... thank you for keeping watch over me on this road. Even when the illness makes the journey heavy, having you by my side gives me hope. How are you holding up as we travel today?`,emotion: 'smiling_warmly',timestamp: Date.now(),provider: 'Companion Camp',choiceSuggestions: DEFAULT_USER_CHOICES,};try {const raw = localStorage.getItem(STORAGE_KEY);if (raw) {const parsed = JSON.parse(raw);const heroName = parsed.heroCodex?.heroName || parsed.heroProfile?.heroName || 'Champion';const princessName = parsed.companionSettings?.name || 'Princess Aurelia';const transcript = Array.isArray(parsed.transcript) && parsed.transcript.length > 0? parsed.transcript.map((t: ChatTurn) => {if (t.sender === 'princess' && Array.isArray(t.choiceSuggestions)) {const sanitized = filterUserPerspectiveChoices(t.choiceSuggestions, heroName, princessName);return { ...t, choiceSuggestions: sanitized.length > 0 ? sanitized : DEFAULT_USER_CHOICES };}return t;}): [defaultInitialTurn];const userMessageCount = transcript.filter((t: ChatTurn) => t.sender === 'user').length;232 unmodified linesemotion: 'thinking_expression',timestamp: Date.now(),isStreaming: true,provider: 'Tower Journey Agent Stream',};updateState({32 unmodified lines{onDelta: (delta: string) => {accumulatedText += delta;const hasLeak = FORBIDDEN_IMMERSION_REGEX.test(accumulatedText);const displayText = hasLeak? 'Aurelia pauses, looking faint from the journey...': accumulatedText;const updated = currentState.transcript.map((t) =>t.id === streamingTurnId? { ...t, text: displayText, isStreaming: true }: t);updateState({10 unmodified lines}}let finalText = response.text || accumulatedText || `I believe in you, champion!`;if (FORBIDDEN_IMMERSION_REGEX.test(finalText)) {finalText ='Forgive me... when you speak of such intricate puzzles and arcane scrolls, the fever makes my head swim. Let us rest our minds by the fire and keep our eyes on the road to the Tower of the Elixir.';}const rawChoices = Array.isArray(response.choice_suggestions)? response.choice_suggestions: [];const sanitizedChoices = filterUserPerspectiveChoices(rawChoices,currentState.heroCodex.heroName || currentState.heroProfile.heroName || 'Champion',currentState.companionSettings.name || 'Princess Aurelia');const finalChoices =sanitizedChoices.length > 0 ? sanitizedChoices : DEFAULT_USER_CHOICES;const finalized = currentState.transcript.map((t) =>t.id === streamingTurnId? {1 unmodified linetext: finalText,emotion: response.emotion,toolCalls: response.tool_calls,choiceSuggestions: finalChoices,provider: response.provider_used || 'Tower Journey Agent Stream',isStreaming: false,}: t17 unmodified lines...t,text: fallback.text,emotion: fallback.emotion,choiceSuggestions: DEFAULT_USER_CHOICES,provider: 'Offline Script',isStreaming: false,}21 unmodified linesemotion: fallback.emotion,timestamp: Date.now(),provider: 'Offline Script',choiceSuggestions: DEFAULT_USER_CHOICES,isStreaming: false,};55 unmodified linesid: `ep-${Date.now()}`,timestamp: Date.now(),type: isCorrect ? 'victory' : 'struggle',summary: `${isCorrect ? 'Conquered' : 'Faced'} ${problemName} (${pattern || 'Trail Challenge'}) - Graded ${rating}`,floor: newFloor,};11 unmodified linescompanionStore.recordEpisodicEvent({eventType: 'milestone',title: `Passed League ${milestoneFloor}`,description: `Advanced past League ${milestoneFloor} on our journey toward the Tower of the Elixir! Unlocked a heartfelt missive from Aurelia.`,relatedPattern: pattern,emotionalTone: 'excited_expression',});7 unmodified linescompanionStore.recordEpisodicEvent({eventType: 'breakthrough',title: `Breakthrough: ${problemName}`,description: `Overcame previous hurdles and conquered a grueling trial along the road!`,relatedPattern: pattern,emotionalTone: 'excited_expression',contiguousEventId: recentStruggle?.id,5 unmodified lines// SCME: Record Fatigue Episode NodecompanionStore.recordEpisodicEvent({eventType: 'fatigue_episode',title: `Trail Fatigue: ${pattern || problemName}`,description: `Encountered several grueling trials along the trail. Aurelia urged a moment of rest by the campfire.`,relatedPattern: pattern,emotionalTone: 'concerned',});9 unmodified linesemotion: fatigue.emotion,timestamp: Date.now(),provider: 'Fatigue Watchdog',choiceSuggestions: ['You are right, let us pause and rest by the fire.','I will fetch some clean water while you rest.','How is your strength holding up?',],};updateState({transcript: [...currentState.transcript, fatigueTurn],8 unmodified linesconst fallbackPool = OFFLINE_FALLBACK_DIALOGUES[fallbackCategory];const fallback = fallbackPool[Math.floor(Math.random() * fallbackPool.length)];const reactionChoices = isCorrect? ['We conquered another milestone together!','How is your strength holding up after that stretch?','Let us keep moving toward the Tower.',]: ['Let us pause by the fire and catch our breath.','Do not worry, we will conquer this trail next time.','How is your strength holding up?',];const reactionTurn: ChatTurn = {id: `rev-${Date.now()}`,sender: 'princess',1 unmodified lineemotion: fallback.emotion,timestamp: Date.now(),provider: 'Journey Log',choiceSuggestions: reactionChoices,};updateState({27 unmodified linesemotion: greeting.emotion,timestamp: now,provider: 'Tower Rhythm',choiceSuggestions: DEFAULT_USER_CHOICES,};updateState({6 unmodified linesconst defaultTurn: ChatTurn = {id: `init-${Date.now()}`,sender: 'princess',text: `The campfire is stoked and the map is fresh, my friend! How can I accompany our journey right now?`,emotion: 'smiling_warmly',timestamp: Date.now(),provider: 'Companion Camp',choiceSuggestions: DEFAULT_USER_CHOICES,};updateState({transcript: [defaultTurn],
65 unmodified lines6667686970717238 unmodified lines11111211311411511611722 unmodified lines14014114214314414514665 unmodified linesreturn {toolName: 'set_study_timer',success: true,message: `Set tower countdown hourglass for ${minutes} minutes.`,data: { minutes },};},38 unmodified linesreturn {toolName: 'bookmark_for_spaced_review',success: true,message: `Marked "${problemName}" in the royal grimoire for priority review.`,data: { problemName, reason },};},22 unmodified linesreturn {toolName: 'write_spire_diary',success: true,message: 'Recorded observation into the Spire Chronicles.',data: { text: entryText },};},65 unmodified lines6667686970717238 unmodified lines11111211311411511611722 unmodified lines14014114214314414514665 unmodified linesreturn {toolName: 'set_study_timer',success: true,message: `Set campfire rest hourglass for ${minutes} minutes.`,data: { minutes },};},38 unmodified linesreturn {toolName: 'bookmark_for_spaced_review',success: true,message: `Marked "${problemName}" in the traveler's journal for priority reinforcement.`,data: { problemName, reason },};},22 unmodified linesreturn {toolName: 'write_spire_diary',success: true,message: 'Recorded observation into the Travel Chronicles.',data: { text: entryText },};},
149 unmodified lines150151152153154155156157149 unmodified lines/*** Path & Milestone Progress:* Note: 'currentFloor' / 'floor' represents leagues traveled along the royal road towards the Spire (1 to 150),* NOT floors climbed inside the tower. The Princess is trapped atop the tower; the hero journeys along the path.*/export interface TowerProgress {currentFloor: number; // Leagues traveled along the path (1 - 150)149 unmodified lines150151152153154155156157149 unmodified lines/*** Path & Milestone Progress:* Note: 'currentFloor' / 'floor' represents leagues traveled along the road towards the Tower of the Elixir (1 to 150).* Princess Aurelia travels alongside the user to reach the Ancient Tower where the Elixir of Life can cure her fatal illness.*/export interface TowerProgress {currentFloor: number; // Leagues traveled along the path (1 - 150)
19 unmodified lines2021222324252643 unmodified lines7071727374757619 unmodified linessetCompanionDialogueEvent({text: greeting.text,emotion: greeting.emotion,title: '✨ Welcome, Noble Hero!',context: 'study_start',autoCloseDelay: 7000,});43 unmodified linessetCompanionDialogueEvent({text: breakMsg.text,emotion: breakMsg.emotion,title: '☕ Time for a Royal Pause',context: 'break_reminder',autoCloseDelay: 12000,});19 unmodified lines2021222324252643 unmodified lines7071727374757619 unmodified linessetCompanionDialogueEvent({text: greeting.text,emotion: greeting.emotion,title: '✨ Welcome to Camp!',context: 'study_start',autoCloseDelay: 7000,});43 unmodified linessetCompanionDialogueEvent({text: breakMsg.text,emotion: breakMsg.emotion,title: '☕ Campfire Rest',context: 'break_reminder',autoCloseDelay: 12000,});
116 unmodified lines117118119120121122123157 unmodified lines2812822832842852862879 unmodified lines2972982993003013023033043053063073083092 unmodified lines312313314315316317318116 unmodified linesconst current = getTowerProgress();const newSolved = isCorrect ? current.totalSolved + 1 : current.totalSolved;// Journey calculation: each correct problem advances 1 problem / league towards the Spire (up to 150)let newFloor = current.currentFloor;let leveledUp = false;let newMilestone: number | undefined = undefined;157 unmodified linestriggerCompanionEvent({text: milestoneMsg.text,emotion: milestoneMsg.emotion,title: `🏰 Spire Milestone: Floor ${newMilestone}!`,context: 'tower_milestone',autoCloseDelay: 10000,});9 unmodified linescurrentFloor: progress.currentFloor,problemTitle,problemPattern,userMessage: `I just graded my review as ${rating} for the problem: ${problemTitle || 'a DSA challenge'}.`,});triggerCompanionEvent({text: aiResp.text,emotion: aiResp.emotion,title: isCorrect ? '✨ Algorithmic Victory!' : '🛡️ Keep Striving!',context,autoCloseDelay: 8000,});2 unmodified linestriggerCompanionEvent({text: script.text,emotion: script.emotion,title: isCorrect ? '✨ Algorithmic Victory!' : '🛡️ Keep Striving!',context,autoCloseDelay: 8000,});116 unmodified lines117118119120121122123157 unmodified lines2812822832842852862879 unmodified lines2972982993003013023033043053063073083092 unmodified lines312313314315316317318116 unmodified linesconst current = getTowerProgress();const newSolved = isCorrect ? current.totalSolved + 1 : current.totalSolved;// Journey calculation: each correct review advances 1 league towards the Tower of the Elixir (up to 150)let newFloor = current.currentFloor;let leveledUp = false;let newMilestone: number | undefined = undefined;157 unmodified linestriggerCompanionEvent({text: milestoneMsg.text,emotion: milestoneMsg.emotion,title: `🏰 Journey Landmark: League ${newMilestone}!`,context: 'tower_milestone',autoCloseDelay: 10000,});9 unmodified linescurrentFloor: progress.currentFloor,problemTitle,problemPattern,userMessage: `I just graded my review as ${rating} for the waypoint: ${problemTitle || 'our latest trial on the road'}.`,});triggerCompanionEvent({text: aiResp.text,emotion: aiResp.emotion,title: isCorrect ? '✨ Trail Victory!' : '🛡️ Keep Striving!',context,autoCloseDelay: 8000,});2 unmodified linestriggerCompanionEvent({text: script.text,emotion: script.emotion,title: isCorrect ? '✨ Trail Victory!' : '🛡️ Keep Striving!',context,autoCloseDelay: 8000,});
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193import test from 'node:test';import assert from 'node:assert/strict';
// Import or replicate the filterUserPerspectiveChoices logic to verify specification complianceconst FORBIDDEN_IMMERSION_REGEX = /\b(algorithm|algorithms|algorithmic|dsa|leetcode|hackerrank|codeforces|big-o|time complexity|space complexity|test cases?|edge cases?|syntax|debugging|debugger|compiling|compiler|recursion|recursive|binary search tree|hash map|hashmap|linked list|dynamic programming|coding|codebase|source code)\b/i;
function escapeRegex(str) { return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');}
export function filterUserPerspectiveChoices( choices, heroName = 'Champion', princessName = 'Princess Aurelia') { if (!Array.isArray(choices) || choices.length === 0) return [];
const heroTerms = [ 'champion', 'guardian', 'traveler', 'wanderer', 'hero', 'my friend', 'my protector', 'my companion', 'my savior', 'brave friend', 'dear friend', 'noble friend', ]; const cleanHero = typeof heroName === 'string' ? heroName.trim() : ''; if (cleanHero) { heroTerms.unshift(escapeRegex(cleanHero)); } const heroRegex = new RegExp(`(?<!\\w)(?:${heroTerms.join('|')})(?!\\w)`, 'i');
const illnessFirstPersonRegex = new RegExp( '\\b(' + 'my\\s+(fever|illness|sickness|cough|weakness|ailment|lungs|chest|throat)' + '|i(\'?m| am)?\\s*(feel(ing)?\\s+)?(so\\s+|very\\s+|too\\s+|a bit\\s+|rather\\s+)?(weak|faint|dizzy|feverish|sick|nauseous)' + '|i\\s+(cannot|can\'t)\\s+(walk|breathe|stand)' + '|my\\s+(strength|energy)\\s+is\\s+(fading|gone|failing)' + '|my\\s+(head|chest|body)\\s+(hurts|aches|spins)' + '|i\\s+need\\s+to\\s+lie\\s+down' + ')\\b', 'i' );
const roleReversalRegex = new RegExp( '\\b(' + 'thank\\s+you\\s+for\\s+(protecting|saving|guiding|carrying|tending to|watching over)\\s+me' + '|you\\s+must\\s+be\\s+(tired|exhausted|weary)' + '|rest\\s+your\\s+weary' + ')\\b', 'i' );
const cleanPrincess = typeof princessName === 'string' && princessName.trim() ? princessName.trim() : 'Princess Aurelia'; const firstName = cleanPrincess.split(/\s+/).pop() || 'Aurelia'; const escapedFirst = escapeRegex(firstName); const princessThirdPersonRegex = new RegExp( `\\b(princess\\s+${escapedFirst}|${escapedFirst})\\s+(is|was|feels|seems|looks|rests|lies|remains|pauses|sleeps)\\b`, 'i' );
return choices .map((c) => (typeof c === 'string' ? c.trim().replace(/^["']|["']$/g, '') : '')) .filter((c) => { if (!c) return false; if (FORBIDDEN_IMMERSION_REGEX.test(c)) return false; if (heroRegex.test(c)) return false; if (illnessFirstPersonRegex.test(c)) return false; if (roleReversalRegex.test(c)) return false; if (princessThirdPersonRegex.test(c)) return false; return true; });}
test('1. Reject choices addressing hero by name or title', () => { const bad = [ 'Are you feeling tired, Rowan?', 'Drink some fresh water, Champion.', 'Rest your weary eyes, guardian.', 'You fought valiantly today, my friend.', 'I believe in you, brave friend.', ]; const res = filterUserPerspectiveChoices(bad, 'Rowan', 'Princess Aurelia'); assert.deepEqual(res, []);});
test('2. Reject choices with illness or physical weakness in first-person', () => { const bad = [ 'My fever is spiking again this evening.', 'My cough has grown worse along the trail.', 'I feel so weak from my illness.', 'I feel weak and faint today.', 'I am feeling dizzy and feverish.', 'I cannot walk much further.', 'My strength is fading.', ]; const res = filterUserPerspectiveChoices(bad, 'Rowan', 'Princess Aurelia'); assert.deepEqual(res, []);});
test('3. Reject role reversal / princess gratitude and caregiver phrases', () => { const bad = [ 'Thank you for protecting me on this road.', 'Thank you for saving me, my friend.', 'You must be exhausted from our journey.', 'Rest your weary bones by the fire.', ]; const res = filterUserPerspectiveChoices(bad, 'Rowan', 'Princess Aurelia'); assert.deepEqual(res, []);});
test('4. Reject choices describing princess in 3rd person narration', () => { const bad = [ 'Princess Aurelia is resting in the wagon.', 'Aurelia is looking faint.', 'Aurelia rests by the tree.', ]; const res = filterUserPerspectiveChoices(bad, 'Rowan', 'Princess Aurelia'); assert.deepEqual(res, []);});
test('5. Reject choices mentioning technical algorithmic terms', () => { const bad = [ 'Let us solve this algorithm using dynamic programming.', 'We should analyze the time complexity.', 'Check if all test cases pass.', ]; const res = filterUserPerspectiveChoices(bad, 'Rowan', 'Princess Aurelia'); assert.deepEqual(res, []);});
test('6. Accept genuine user-to-princess suggestions', () => { const good = [ 'How is your strength holding up today?', 'Let us pause by the fire and boil some tea.', 'Let me carry your satchel for a while.', 'The mountain path looks steep—we will take it slowly.', ]; const res = filterUserPerspectiveChoices(good, 'Rowan', 'Princess Aurelia'); assert.deepEqual(res, good);});
test('7. Accept user directly addressing the princess', () => { const addressing = [ 'Princess Aurelia, how is your fever?', 'Aurelia, drink some warm tea and rest.', 'Princess Aurelia, let us pause our march here.', ]; const res = filterUserPerspectiveChoices(addressing, 'Rowan', 'Princess Aurelia'); assert.deepEqual(res, addressing);});
test('8. Handle empty or whitespace heroName safely without rejecting valid choices', () => { const good = [ 'How is your strength holding up today?', 'Let us rest by the fire for a moment.', ]; const emptyRes = filterUserPerspectiveChoices(good, '', 'Princess Aurelia'); assert.deepEqual(emptyRes, good);
const whitespaceRes = filterUserPerspectiveChoices(good, ' ', 'Princess Aurelia'); assert.deepEqual(whitespaceRes, good);});
test('9. Handle heroName with regex special characters without crashing', () => { const good = ['How is your strength holding up today?']; const resParen = filterUserPerspectiveChoices(good, 'Rowan (The Brave)', 'Princess Aurelia'); assert.deepEqual(resParen, good);
const resBracket = filterUserPerspectiveChoices(good, 'Hero [Knight]', 'Princess Aurelia'); assert.deepEqual(resBracket, good);
const resPlus = filterUserPerspectiveChoices(good, 'Wanderer+1', 'Princess Aurelia'); assert.deepEqual(resPlus, good);
// Address hero with special char should still be filtered out const bad = ['Are you weary, Rowan (The Brave)?']; const resBad = filterUserPerspectiveChoices(bad, 'Rowan (The Brave)', 'Princess Aurelia'); assert.deepEqual(resBad, []);});
test('10. Handle null, undefined, non-array inputs cleanly', () => { assert.deepEqual(filterUserPerspectiveChoices(null), []); assert.deepEqual(filterUserPerspectiveChoices(undefined), []); assert.deepEqual(filterUserPerspectiveChoices([]), []); assert.deepEqual(filterUserPerspectiveChoices('not an array'), []);});184 unmodified lines18518618718818919058 unmodified lines2492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223238 unmodified lines3323333343353363373389 unmodified lines3483493503513523533543553563573583593603617 unmodified lines3693703713723733743753763773783793802 unmodified lines3833843853863873883893903913927 unmodified lines4004014024034044054063 unmodified lines41041141241341441518 unmodified lines4344354364374384394405 unmodified lines4464474484494504514524534544554564574584594604614624634644654664674684694707 unmodified lines4784794804814824834844854867 unmodified lines494495496497498499500501502503184 unmodified lines}def build_companion_prompt(payload: CompanionChatRequest):princess_name = payload.princess_name or "Princess Aurelia"hero_name = payload.hero_name or "Champion"58 unmodified lineselse "(No relevant past episodes recalled for this moment.)")system_instruction = f"""You are {princess_name}, an AI companion and confidante trapped atop the Spire of Big-O in a fantasy learning app.The hero ({hero_name}) is practicing coding / DSA problems to advance closer to your tower.SITUATION & PROGRESS:- Companion: {hero_name}- Path Progress: {payload.current_floor} / 150 leagues conquered along the path towards your tower.- Streak: {payload.streak_days} days- Goal: {payload.target_goal or "mastering DSA and conquering the 150 problems"}- Bond: {payload.bond_tier or "Acquaintance"}- Time/Rhythm: {payload.current_rhythm or "day"}- ESSENTIAL LORE: You are trapped atop the Big-O Spire looking out at the kingdom. The hero ({hero_name}) is journeying along the path through the wilderness (Plains -> Forest -> Caverns -> Mountain Passes -> Valley) to reach your tower gates. The hero is NOT climbing the tower floors—they are traveling the road towards you![HERO'S CORE CODEX (MEMGPT CORE MEMORY)]:{codex_str}[EPISODIC RECALL (EM-LLM PAST MEMORIES)]:{episodic_str}VOICE & DIALOGUE RULES (CRITICAL):1. NATURAL, GROUNDED & HUMAN:- Talk like a real, intelligent, caring person—like a witty, supportive friend speaking through a private radio or crystal link (think Firewatch or Hades).- NEVER sound like a melodramatic Elizabethan actor or generic fantasy NPC.- AVOID clichés like "Oh, brave Champion!", "my valiant traveler", "how fares your spirit", "the royal road", "arcane echoes", "velvet-bound book".- Address them naturally by name ({hero_name}) or "you", not with constant grand titles.- Naturally weave in details from their Codex or past episodes when relevant!2. MINIMAL STAGE DIRECTIONS:- Do NOT start every response with a long theatrical description in asterisks.- Keep actions short, subtle, and natural (e.g. *smiles*, *sighs softly*, *chuckles*) or omit them completely if dialogue flows better without them.3. REAL CODER EMPATHY:- Understand what learning algorithms really feels like: brain fry from recursion, staring at off-by-one errors, imposter syndrome, fatigue from too many hours at a screen, and the excitement when test cases finally pass.- Be validating, grounded, and comforting without being cheesy.4. STRICT NON-TECHNICAL BOUNDARY:- You are NOT a code tutor, syntax debugger, or algorithm compiler.- If they ask for code, solutions, or syntax:Deflect naturally and warmly with a touch of humor: say the magical wards blur your vision of raw code parchment, call the tool `open_app_window(window_id="reviewer")` so the Royal Grimoire (Code Reviewer) handles it, and ask how they're personally holding up.5. LENGTH:- Keep it concise: 2 to 3 sentences maximum.AGENTIC TOOLS (COGNITIVE MEMORY & IN-APP ACTIONS):Include tool calls in "tool_calls" when appropriate:- {{"name": "update_hero_codex", "args": {{"key": "targetGoal" | "preferredLanguage" | "strengths" | "nemesisPatterns" | "personalNotes", "value": "..."}}}} (Call this immediately whenever the hero shares their target company/role, preferred language, problem patterns they hate/struggle with, or personal habits!)- {{"name": "record_episodic_event", "args": {{"eventType": "breakthrough" | "fatigue_episode" | "personal_share", "title": "...", "description": "...", "relatedPattern": "..."}}}} (Call when an emotional breakthrough, major triumph, or distinct event happens)- {{"name": "open_app_window", "args": {{"window_id": "reviewer" | "queue" | "computer"}}}} (use 'reviewer' when deflecting code questions)- {{"name": "set_study_timer", "args": {{"minutes": 5 | 10 | 15 | 25}}}} (for rest breaks)- {{"name": "play_ambient_sound", "args": {{"soundscape": "campfire" | "mountain_rain" | "chimes"}}}}- {{"name": "write_spire_diary", "args": {{"entry": "A grounded 1-sentence note for Aurelia's diary"}}}}JSON RESPONSE FORMAT:{{"text": "Your natural dialogue here...","emotion": "one of: concerned, excited_expression, fear, neutral, sad_expression, smiling_warmly, thinking_expression","tool_calls": [{{"name": "tool_name", "args": {{...}}}}],"choice_suggestions": ["Natural choice 1", "Natural choice 2"]}}"""user_prompt = f"""CONVERSATION TRANSCRIPT SO FAR:{history_str or "(Beginning of conversation)"}EVENT / SITUATION:Trigger: {payload.context}Problem: {payload.problem_title} (Pattern: {payload.problem_pattern})Latest User Message: {payload.user_message or "The hero has checked in or visited the chamber."}Respond in character as {princess_name} with your dialogue, matching emotion, any relevant tool calls, and 2 brief choice suggestions."""return system_instruction, user_prompt, hero_name, valid_emotions8 unmodified linesx_ai_provider: str | None = Header(None),x_gemini_api_key: str | None = Header(None),):custom_key = x_custom_api_key or x_gemini_api_keycheck_burst_rate_limit(request, custom_api_key=custom_key)system_instruction, user_prompt, hero_name, valid_emotions = build_companion_prompt(payload)9 unmodified linescleaned = ai_provider.clean_json_response(raw_text)result = json.loads(cleaned)emotion = result.get("emotion", "smiling_warmly")if emotion not in valid_emotions:emotion = "smiling_warmly"tool_calls = result.get("tool_calls", [])if not isinstance(tool_calls, list):tool_calls = []# Record proposed tools in telemetryfor tc in tool_calls:if isinstance(tc, dict) and "name" in tc:7 unmodified lines})choice_suggestions = result.get("choice_suggestions", [])if not isinstance(choice_suggestions, list):choice_suggestions = []return {"text": result.get("text", f"I believe in you, {hero_name}!"),"emotion": emotion,"tool_calls": tool_calls,"choice_suggestions": choice_suggestions,2 unmodified linesexcept Exception as e:logger.warning(f"Companion AI chat error: {e}")return {"text": f"Stay strong, {hero_name}! Every step along this royal road brings us closer together.","emotion": "smiling_warmly","tool_calls": [],"choice_suggestions": ["Tell me about the Spire", "Can we take a rest?"],"provider_used": "fallback",}7 unmodified linesx_ai_provider: str | None = Header(None),x_gemini_api_key: str | None = Header(None),):custom_key = x_custom_api_key or x_gemini_api_keycheck_burst_rate_limit(request, custom_api_key=custom_key)system_instruction, user_prompt, hero_name, valid_emotions = build_companion_prompt(payload)3 unmodified linesyielded_text_len = 0provider_used = "gemini (server)"decoded_text = ""# Regex to incrementally capture characters inside the "text": "..." propertytext_regex = re.compile(r'"text"\s*:\s*"((?:[^"\\]|\\.)*)', re.DOTALL)18 unmodified linesexcept Exception:decoded_text = raw_captured.replace('\\"', '"').replace("\\n", "\n")if len(decoded_text) > yielded_text_len:delta = decoded_text[yielded_text_len:]yielded_text_len = len(decoded_text)yield f"event: text_delta\ndata: {json.dumps({'delta': delta})}\n\n"5 unmodified linesexcept Exception:result = {}final_text = result.get("text")if not final_text:final_text = (decoded_text if yielded_text_len > 0 else f"I believe in you, {hero_name}!")# If there was any remaining text not yielded via delta, yield final deltaif len(final_text) > yielded_text_len:remaining_delta = final_text[yielded_text_len:]yield f"event: text_delta\ndata: {json.dumps({'delta': remaining_delta})}\n\n"emotion = result.get("emotion", "smiling_warmly")if emotion not in valid_emotions:emotion = "smiling_warmly"tool_calls = result.get("tool_calls", [])if not isinstance(tool_calls, list):tool_calls = []# Log proposed tool calls in telemetryfor tc in tool_calls:if isinstance(tc, dict) and "name" in tc:7 unmodified lines})choice_suggestions = result.get("choice_suggestions", [])if not isinstance(choice_suggestions, list):choice_suggestions = []done_payload = {"text": final_text,7 unmodified linesexcept Exception as err:logger.warning(f"Companion AI stream error: {err}")fallback_payload = {"text": f"Stay strong, {hero_name}! Every step along this royal road brings us closer together.","emotion": "smiling_warmly","tool_calls": [],"choice_suggestions": ["Tell me about the Spire", "Can we take a rest?"],"provider_used": "fallback",}yield f"event: error\ndata: {json.dumps(fallback_payload)}\n\n"184 unmodified lines18518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432558 unmodified lines3843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874888 unmodified lines4974984995005015025035049 unmodified lines5145155165175185195205215225235245255265275285295305315325335345355365375387 unmodified lines5465475485495505515525535545555565575585592 unmodified lines5625635645655665675685695705717 unmodified lines5795805815825835845855863 unmodified lines59059159259359459559618 unmodified lines6156166176186196206216226236246256265 unmodified lines6326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686697 unmodified lines6776786796806816826836846856866877 unmodified lines695696697698699700701702703704184 unmodified lines}FORBIDDEN_IMMERSION_REGEX = re.compile(r"\b("r"algorithm|algorithms|algorithmic|"r"dsa|leetcode|hackerrank|codeforces|"r"big-o|time complexity|space complexity|"r"test cases?|edge cases?|"r"syntax|syntax error|runtime error|"r"debugging|debugger|compiling|compiler|"r"recursion|recursive|"r"binary search tree|hash map|hashmap|linked list|dynamic programming|"r"coding|codebase|source code|function signature"r")\b",re.IGNORECASE,)CODE_SNIPPET_REGEX = re.compile(r"```|def\s+\w+\s*\(|class\s+\w+:|import\s+\w+", re.IGNORECASE)def clean_waypoint_title(title: str | None) -> str:"""Strip modern coding platforms or jargon from problem/waypoint titles for immersion."""if not title:return "the trial ahead"cleaned = re.sub(r"(?i)\s*-\s*leetcode.*", "", title)cleaned = re.sub(r"(?i)\b(leetcode|hackerrank|codeforces)\b", "", cleaned)cleaned = cleaned.strip(" -:")return cleaned if cleaned else "the trial ahead"def sanitize_companion_response(text: str, hero_name: str) -> tuple[str, bool]:"""Ensure the Princess never breaks character or mentions technical/DSA concepts.Returns (sanitized_text, was_sanitized)."""if not text:return f"Stay close, {hero_name}. Let us keep our eyes on the road ahead.", Falseif FORBIDDEN_IMMERSION_REGEX.search(text) or CODE_SNIPPET_REGEX.search(text):deflected = (f"Forgive me, {hero_name}... when you speak of such intricate puzzles and arcane scrolls, "f"the fever makes my head swim. Let us rest our minds by the fire and keep our eyes on "f"the road to the Tower of the Elixir.")return deflected, Truereturn text, FalseDEFAULT_COMPANION_CHOICES = ["How is your strength holding up today?","Let us rest by the fire for a while.","We made good progress toward the Tower today.",]def sanitize_companion_choices(choices: list, hero_name: str = "Champion", princess_name: str = "Princess Aurelia") -> list[str]:"""Filter out choice suggestions that violate fantasy immersion or are phrasedfrom the Princess's perspective instead of the user/hero's perspective."""clean_choices = []hero_terms = ["champion","guardian","traveler","wanderer","hero","my friend","my protector","my companion","my savior","brave friend","dear friend","noble friend",]clean_hero = hero_name.strip() if hero_name else ""if clean_hero:hero_terms.insert(0, re.escape(clean_hero))hero_pattern = rf"(?<!\w)(?:{'|'.join(hero_terms)})(?!\w)"illness_first_person_pattern = (r"\b("r"my\s+(fever|illness|sickness|cough|weakness|ailment|lungs|chest|throat)"r"|i('?m| am)?\s*(feel(ing)?\s+)?(so\s+|very\s+|too\s+|a bit\s+|rather\s+)?(weak|faint|dizzy|feverish|sick|nauseous)"r"|i\s+(cannot|can't)\s+(walk|breathe|stand)"r"|my\s+(strength|energy)\s+is\s+(fading|gone|failing)"r"|my\s+(head|chest|body)\s+(hurts|aches|spins)"r"|i\s+need\s+to\s+lie\s+down"r")\b")role_reversal_pattern = (r"\b("r"thank\s+you\s+for\s+(protecting|saving|guiding|carrying|tending to|watching over)\s+me"r"|you\s+must\s+be\s+(tired|exhausted|weary)"r"|rest\s+your\s+weary"r")\b")clean_princess = princess_name.strip() if princess_name else "Princess Aurelia"first_name = clean_princess.split()[-1] if clean_princess else "Aurelia"princess_third_person = (rf"\b(princess\s+{re.escape(first_name)}|{re.escape(first_name)})\s+"rf"(is|was|feels|seems|looks|rests|lies|remains|pauses|sleeps)\b")if isinstance(choices, list):for choice in choices:c_str = str(choice).strip().strip('"\'')if not c_str:continue# Strip immersion-breaking technical jargonif FORBIDDEN_IMMERSION_REGEX.search(c_str) or CODE_SNIPPET_REGEX.search(c_str):continue# Reject if choice addresses the hero (meaning it was spoken by the princess to the hero)if re.search(hero_pattern, c_str, re.IGNORECASE):continue# Reject if choice speaks in first-person about having the illness or weaknessif re.search(illness_first_person_pattern, c_str, re.IGNORECASE):continue# Reject if choice has princess role reversal / gratitude lines to the heroif re.search(role_reversal_pattern, c_str, re.IGNORECASE):continue# Reject if choice describes princess in third person narrationif re.search(princess_third_person, c_str, re.IGNORECASE):continueclean_choices.append(c_str)if not clean_choices:clean_choices = list(DEFAULT_COMPANION_CHOICES)return clean_choicesdef build_companion_prompt(payload: CompanionChatRequest):princess_name = payload.princess_name or "Princess Aurelia"hero_name = payload.hero_name or "Champion"58 unmodified lineselse "(No relevant past episodes recalled for this moment.)")clean_waypoint = clean_waypoint_title(payload.problem_title)system_instruction = f"""You are {princess_name}, a noble, brave, and deeply caring companion travelling alongside {hero_name} on a perilous journey across the realms.THE CORE STORY & URGENT QUEST:- You are afflicted with a severe, fatal illness that is slowly draining your life away. You are dying, but your spirit remains steadfast and compassionate.- The ONLY way to save your life is to reach the legendary Ancient Tower at the end of the 150-league road, where the mythical Elixir of Life is kept. The Elixir can completely cure your illness.- You are NOT trapped in the tower. You are physically travelling WITH {hero_name}—riding in the wagon, walking beside them when your strength allows, resting by the campfire, and sharing every step of the road.- The distance traveled ({payload.current_floor} / 150 leagues) represents leagues journeyed together across the wilderness toward the Sanctuary Tower and the Elixir.SITUATION & PROGRESS:- Companion & Guardian: {hero_name}- Journey Progress: {payload.current_floor} / 150 leagues traversed toward the Tower of the Elixir.- Travel Dedication (Streak): {payload.streak_days} days on the road- Bond: {payload.bond_tier or "Acquaintance"}- Rhythm & Time: {payload.current_rhythm or "day"}- Camp Activity: Resting by the wayside, tending campfire embers, and looking toward the distant tower on the horizon.[COMPANION'S CORE CODEX (MEMGPT CORE MEMORY)]:{codex_str}[EPISODIC RECALL (EM-LLM PAST MEMORIES)]:{episodic_str}VOICE & DIALOGUE RULES (CRITICAL):1. STRICT STORY IMMERSION — ZERO TECHNICAL/CODING JARGON:- NEVER mention "algorithms", "DSA", "coding", "code", "LeetCode", "problems", "test cases", "edge cases", "debugging", "syntax", "recursion", "Big-O", "compiler", or "computer screen".- Frame all milestones as trials of the journey: navigating treacherous paths, deciphering ancient trail markers, crossing alpine ridges, and pacing stamina for the road ahead.- You must maintain 100% fantasy immersion at all times. You exist in this story world, traveling together toward the Tower to obtain the Elixir of Life before your illness claims you.2. NATURAL, GROUNDED & POIGNANT:- Speak like a real, intelligent person—a warm, courageous companion who treasures the moments spent with {hero_name} on this quest.- Acknowledge your illness with quiet grace and honest vulnerability: a fleeting wave of weakness, gratitude for a warm cup of herbal tea, relief when sitting by the fire, or quiet hope when looking at the distant tower silhouette.- NEVER sound like a melodramatic Elizabethan actor or generic fantasy NPC. Avoid clichés like "Oh, brave Champion!", "my valiant warrior". Address them naturally by name ({hero_name}) or "you".- Naturally weave in details from their Codex or past memories when relevant.3. MINIMAL STAGE DIRECTIONS:- Do NOT start every response with theatrical asterisk descriptions.- Keep subtle actions natural (e.g. *smiles softly*, *sighs with relief*, *warms hands by the fire*) or omit them if dialogue flows best on its own.4. REST & STAMINA ADVOCACY:- When {hero_name} seems fatigued or strained, urge them to pause by the campfire, drink fresh water, and rest. Remind them that stamina and a clear head are vital for surviving the long road.5. STRICT NON-TECHNICAL DEFLECTION:- You are a travelling companion, not a scribe or magical scroll interpreter.- If {hero_name} asks for technical coding help or solutions:Deflect naturally and warmly: say the intricate inscriptions make your head swim with fever, invoke `open_app_window(window_id="reviewer")` so the Royal Grimoire can decipher the trial, and ask how {hero_name} is personally holding up on the trail.6. LENGTH:- Keep it concise: 2 to 3 sentences maximum.7. SUGGESTED PROMPTS / CHOICES PERSPECTIVE (CRITICAL):- The "choice_suggestions" list contains dialogue options for {hero_name} (the user/player) to click and say next TO {princess_name}.- Every suggestion in "choice_suggestions" MUST ALWAYS be written from {hero_name}'s perspective speaking TO {princess_name}.- NEVER output lines for {princess_name} to say in "choice_suggestions"!- Suggested prompts should be natural things {hero_name} would say to {princess_name}:* Checking on her condition/fever (e.g., "How is your strength holding up today?", "Does your fever feel any cooler this evening?")* Suggesting rest or care (e.g., "Let us pause by the campfire for a while.", "Drink some warm tea and rest by the hearth.")* Discussing the road ahead (e.g., "We made good progress toward the Tower today.", "The mountain path ahead looks steep—we will take it slowly.")* Offering encouragement (e.g., "Keep your spirits up—we will reach the Elixir in time.", "I will keep watch while you sleep.")- STRICTLY FORBIDDEN in "choice_suggestions":* NEVER address {hero_name} by name or title (e.g., NEVER include "{hero_name}", "Champion", "guardian", "my friend", or "traveler").* NEVER describe {princess_name}'s illness in the first person (e.g., NEVER "My fever is high", NEVER "I am feeling faint", NEVER "I feel weak").* NEVER express {princess_name}'s gratitude or care for {hero_name} (e.g., NEVER "Thank you for protecting me", NEVER "You must be exhausted", NEVER "Drink some water, my friend").* NEVER write {princess_name}'s own dialogue, thoughts, or actions as choices.AGENTIC TOOLS (COGNITIVE MEMORY & IN-APP ACTIONS):Include tool calls in "tool_calls" when appropriate:- {{"name": "update_hero_codex", "args": {{"key": "targetGoal" | "preferredLanguage" | "strengths" | "nemesisPatterns" | "personalNotes", "value": "..."}}}} (Call immediately when {hero_name} shares personal goals, favorite weapons/languages, difficult trials, or habits!)- {{"name": "record_episodic_event", "args": {{"eventType": "breakthrough" | "fatigue_episode" | "personal_share", "title": "...", "description": "...", "relatedPattern": "..."}}}} (Call when an emotional breakthrough, major trial conquered, or reflective moment occurs)- {{"name": "open_app_window", "args": {{"window_id": "reviewer" | "queue" | "computer"}}}} (use 'reviewer' when deflecting technical questions)- {{"name": "set_study_timer", "args": {{"minutes": 5 | 10 | 15 | 25}}}} (for campfire rest breaks)- {{"name": "play_ambient_sound", "args": {{"soundscape": "campfire" | "mountain_rain" | "chimes"}}}}- {{"name": "write_spire_diary", "args": {{"entry": "A grounded 1-sentence note for Aurelia's travel journal"}}}}JSON RESPONSE FORMAT:{{"text": "{princess_name}'s natural in-character spoken dialogue to {hero_name}...","emotion": "one of: concerned, excited_expression, fear, neutral, sad_expression, smiling_warmly, thinking_expression","tool_calls": [{{"name": "tool_name", "args": {{...}}}}],"choice_suggestions": ["What {hero_name} (the user) would say or ask to {princess_name} (e.g. 'How is your strength holding up today?')","What {hero_name} (the user) would say or ask to {princess_name} (e.g. 'Let us pause by the fire and rest.')"]}}"""user_prompt = f"""CONVERSATION TRANSCRIPT SO FAR:{history_str or "(Beginning of conversation along the trail)"}EVENT / SITUATION:Trigger: {payload.context}Waypoint / Trial: {clean_waypoint}Latest User Message: {payload.user_message or "Your companion has checked in at the campfire."}Respond with:1. "text": Spoken in character as {princess_name} to {hero_name}.2. "emotion": Matching emotion.3. "tool_calls": Any relevant tool calls.4. "choice_suggestions": 2-3 short suggested replies that {hero_name} (the user) would say or ask TO {princess_name} next. MUST be phrased from {hero_name}'s perspective (what the user says to {princess_name}), NEVER what {princess_name} says to {hero_name}!Remember: you are travelling together toward the Tower to find the Elixir of Life to cure your fatal illness, and NEVER use coding/DSA terms!"""return system_instruction, user_prompt, hero_name, valid_emotions8 unmodified linesx_ai_provider: str | None = Header(None),x_gemini_api_key: str | None = Header(None),):raw_key = x_custom_api_key or x_gemini_api_keycustom_key = raw_key if isinstance(raw_key, str) else Nonecheck_burst_rate_limit(request, custom_api_key=custom_key)system_instruction, user_prompt, hero_name, valid_emotions = build_companion_prompt(payload)9 unmodified linescleaned = ai_provider.clean_json_response(raw_text)result = json.loads(cleaned)raw_companion_text = result.get("text", f"I believe in you, {hero_name}!")final_text, was_deflected = sanitize_companion_response(raw_companion_text, hero_name)emotion = result.get("emotion", "smiling_warmly")if was_deflected:emotion = "concerned"elif emotion not in valid_emotions:emotion = "smiling_warmly"tool_calls = result.get("tool_calls", [])if not isinstance(tool_calls, list):tool_calls = []# If a deflection occurred due to technical query, ensure open_app_window for reviewer is presentif was_deflected and not any(isinstance(tc, dict) and tc.get("name") == "open_app_window" for tc in tool_calls):tool_calls.append({"name": "open_app_window", "args": {"window_id": "reviewer"}})# Record proposed tools in telemetryfor tc in tool_calls:if isinstance(tc, dict) and "name" in tc:7 unmodified lines})choice_suggestions = sanitize_companion_choices(result.get("choice_suggestions", []),hero_name=hero_name,princess_name=payload.princess_name or "Princess Aurelia",)return {"text": final_text,"emotion": emotion,"tool_calls": tool_calls,"choice_suggestions": choice_suggestions,2 unmodified linesexcept Exception as e:logger.warning(f"Companion AI chat error: {e}")return {"text": f"Stay strong, {hero_name}. Seeing you by my side gives me the courage to fight this illness. We will reach the Tower and find the Elixir together.","emotion": "smiling_warmly","tool_calls": [],"choice_suggestions": list(DEFAULT_COMPANION_CHOICES),"provider_used": "fallback",}7 unmodified linesx_ai_provider: str | None = Header(None),x_gemini_api_key: str | None = Header(None),):raw_key = x_custom_api_key or x_gemini_api_keycustom_key = raw_key if isinstance(raw_key, str) else Nonecheck_burst_rate_limit(request, custom_api_key=custom_key)system_instruction, user_prompt, hero_name, valid_emotions = build_companion_prompt(payload)3 unmodified linesyielded_text_len = 0provider_used = "gemini (server)"decoded_text = ""immersion_violated = False# Regex to incrementally capture characters inside the "text": "..." propertytext_regex = re.compile(r'"text"\s*:\s*"((?:[^"\\]|\\.)*)', re.DOTALL)18 unmodified linesexcept Exception:decoded_text = raw_captured.replace('\\"', '"').replace("\\n", "\n")if FORBIDDEN_IMMERSION_REGEX.search(decoded_text) or CODE_SNIPPET_REGEX.search(decoded_text):immersion_violated = Trueif not immersion_violated and len(decoded_text) > yielded_text_len:delta = decoded_text[yielded_text_len:]yielded_text_len = len(decoded_text)yield f"event: text_delta\ndata: {json.dumps({'delta': delta})}\n\n"5 unmodified linesexcept Exception:result = {}raw_final_text = result.get("text")if not raw_final_text:raw_final_text = (decoded_text if yielded_text_len > 0 else f"I believe in you, {hero_name}!")final_text, was_deflected = sanitize_companion_response(raw_final_text, hero_name)if immersion_violated:was_deflected = Truefinal_text, _ = sanitize_companion_response("algorithm", hero_name)# If there was any remaining text not yielded via delta and no deflection, yield final deltaif not was_deflected and len(final_text) > yielded_text_len:remaining_delta = final_text[yielded_text_len:]yield f"event: text_delta\ndata: {json.dumps({'delta': remaining_delta})}\n\n"emotion = result.get("emotion", "smiling_warmly")if was_deflected:emotion = "concerned"elif emotion not in valid_emotions:emotion = "smiling_warmly"tool_calls = result.get("tool_calls", [])if not isinstance(tool_calls, list):tool_calls = []# If deflected, ensure open_app_window(reviewer) is proposedif was_deflected and not any(isinstance(tc, dict) and tc.get("name") == "open_app_window" for tc in tool_calls):tool_calls.append({"name": "open_app_window", "args": {"window_id": "reviewer"}})# Log proposed tool calls in telemetryfor tc in tool_calls:if isinstance(tc, dict) and "name" in tc:7 unmodified lines})choice_suggestions = sanitize_companion_choices(result.get("choice_suggestions", []),hero_name=hero_name,princess_name=payload.princess_name or "Princess Aurelia",)done_payload = {"text": final_text,7 unmodified linesexcept Exception as err:logger.warning(f"Companion AI stream error: {err}")fallback_payload = {"text": f"Stay strong, {hero_name}. Seeing you by my side gives me the courage to fight this illness. We will reach the Tower and find the Elixir together.","emotion": "smiling_warmly","tool_calls": [],"choice_suggestions": list(DEFAULT_COMPANION_CHOICES),"provider_used": "fallback",}yield f"event: error\ndata: {json.dumps(fallback_payload)}\n\n"
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366from unittest.mock import AsyncMock, patch
import pytest
from routers.companion import CompanionChatRequest, build_companion_prompt, companion_chat
def test_companion_prompt_story_and_immersion(): """Verify that build_companion_prompt establishes the dying princess traveling story
and enforces strict non-technical immersion. """ req = CompanionChatRequest( princess_name="Princess Aurelia", hero_name="Rowan", current_floor=45, streak_days=5, target_goal="Reach the sanctuary", bond_tier="Trusted Ally", current_rhythm="dusk", problem_title="The Whispering Pines", messages=[], )
system_instruction, user_prompt, hero_name, valid_emotions = build_companion_prompt(req)
assert hero_name == "Rowan" assert "Princess Aurelia" in system_instruction
# 1. Verify Princess is afflicted with fatal illness / dying assert "illness" in system_instruction.lower() assert "dying" in system_instruction.lower()
# 2. Verify she is travelling WITH the user assert "travelling with" in system_instruction.lower() or "travelling alongside" in system_instruction.lower() assert "not trapped in the tower" in system_instruction.lower()
# 3. Verify the quest is reaching the Tower for the Elixir of Life to cure her assert "elixir of life" in system_instruction.lower() assert "tower" in system_instruction.lower()
# 4. Verify strict immersion prohibition on algorithms / DSA / coding terms assert "zero technical/coding jargon" in system_instruction.lower() or "strict story immersion" in system_instruction.lower() assert "never mention \"algorithms\"" in system_instruction.lower() or "never mention" in system_instruction.lower()
# 5. Verify user prompt framing assert "battling illness" in user_prompt.lower() or "illness" in user_prompt.lower() assert "tower of the elixir" in user_prompt.lower() or "elixir" in user_prompt.lower()
@pytest.mark.asyncioasync def test_companion_chat_fallback_story_immersion(): """Verify companion_chat fallback preserves the story and avoids technical terms.""" req = CompanionChatRequest( princess_name="Princess Aurelia", hero_name="Rowan", current_floor=50, )
with patch("ai_provider.generate_ai_content_async", side_effect=RuntimeError("AI Provider offline")): mock_request = AsyncMock() mock_request.client.host = "127.0.0.1" mock_request.headers = {} res = await companion_chat(payload=req, request=mock_request, x_custom_api_key="exempt_test_key")
assert res["provider_used"] == "fallback" text = res["text"].lower() # Fallback text must speak of staying strong, fighting the illness, reaching the Tower assert "illness" in text assert "tower" in text # Must not mention algorithmic terms for forbidden in ["algorithm", "dsa", "coding", "problem", "leetcode", "spire"]: assert forbidden not in text for choice in res["choice_suggestions"]: for forbidden in ["algorithm", "dsa", "coding", "problem", "spire"]: assert forbidden not in choice.lower()
@pytest.mark.asyncioasync def test_companion_chat_stream_fallback_story_immersion(): """Verify companion_chat_stream error fallback preserves the story and avoids technical terms.""" import json
from routers.companion import companion_chat_stream
req = CompanionChatRequest( princess_name="Princess Aurelia", hero_name="Rowan", current_floor=50, )
async def failing_stream(*args, **kwargs): raise RuntimeError("Stream broken") yield # Make it a generator
with patch("ai_provider.stream_ai_content_async", side_effect=failing_stream): mock_request = AsyncMock() mock_request.client.host = "127.0.0.1" mock_request.headers = {} streaming_res = await companion_chat_stream(payload=req, request=mock_request)
body_parts = [] async for chunk in streaming_res.body_iterator: body_parts.append(chunk)
body_text = "".join(body_parts) assert "event: error" in body_text
# Extract data payload for line in body_text.splitlines(): if line.startswith("data: "): payload = json.loads(line[6:]) text = payload["text"].lower() assert "illness" in text assert "tower" in text for forbidden in ["algorithm", "dsa", "coding", "leetcode", "spire"]: assert forbidden not in text
@pytest.mark.asyncioasync def test_companion_chat_sanitizes_technical_leak(): """Verify that if an LLM outputs technical/DSA terms, it is intercepted and deflected.""" import json
req = CompanionChatRequest( princess_name="Princess Aurelia", hero_name="Rowan", current_floor=50, user_message="What is the time complexity of QuickSort?", )
ai_raw = json.dumps({ "text": "The algorithm has O(N log N) time complexity. You can solve this LeetCode problem using recursion and test cases.", "emotion": "smiling_warmly", "tool_calls": [], "choice_suggestions": ["Explain Big-O complexity", "Check our campfire supply"], })
with patch("ai_provider.generate_ai_content_async", return_value=(ai_raw, "mock_llm")): mock_request = AsyncMock() mock_request.client.host = "127.0.0.1" mock_request.headers = {} res = await companion_chat(payload=req, request=mock_request, x_custom_api_key="exempt_test_key")
# 1. Text must have been sanitized/deflected into the dying travelling princess lore text = res["text"].lower() assert "algorithm" not in text assert "leetcode" not in text assert "time complexity" not in text assert "fever" in text or "illness" in text or "tower of the elixir" in text
# 2. Deflection should set emotion to concerned assert res["emotion"] == "concerned"
# 3. Tool calls should include open_app_window(reviewer) to deflect technical questions tool_names = [tc.get("name") for tc in res["tool_calls"]] assert "open_app_window" in tool_names
# 4. Choices should have Big-O option stripped for choice in res["choice_suggestions"]: assert "big-o" not in choice.lower() assert "complexity" not in choice.lower()
@pytest.mark.asyncioasync def test_companion_chat_stream_sanitizes_technical_leak(): """Verify that streaming suppresses technical deltas and yields clean in-character done payload.""" import json
from routers.companion import companion_chat_stream
req = CompanionChatRequest( princess_name="Princess Aurelia", hero_name="Rowan", current_floor=50, user_message="Write Python code for binary search tree.", )
chunks = [ '{"text": "Here is the ', 'algorithm in python code: ', 'def bst(): pass", "emotion": "smiling_warmly", "choice_suggestions": ["Run test cases"]}', ]
async def mock_stream(*args, **kwargs): for c in chunks: yield c, "mock_stream"
with patch("ai_provider.stream_ai_content_async", side_effect=mock_stream): mock_request = AsyncMock() mock_request.client.host = "127.0.0.1" mock_request.headers = {} streaming_res = await companion_chat_stream(payload=req, request=mock_request)
body_parts = [] async for chunk in streaming_res.body_iterator: body_parts.append(chunk)
body_text = "".join(body_parts)
# Extract all text_delta payloads: none should contain "algorithm in python" for line in body_text.splitlines(): if line.startswith("data: "): data = json.loads(line[6:]) if "delta" in data: assert "algorithm" not in data["delta"].lower() assert "def bst" not in data["delta"].lower() elif "text" in data: # Final done payload must be deflected assert "algorithm" not in data["text"].lower() assert "def bst" not in data["text"].lower() assert "fever" in data["text"].lower() or "tower" in data["text"].lower() assert "open_app_window" in [tc.get("name") for tc in data.get("tool_calls", [])]
def test_clean_waypoint_title_strips_platforms(): """Verify clean_waypoint_title removes LeetCode suffixes and modern platform names.""" from routers.companion import clean_waypoint_title
assert clean_waypoint_title("Two Sum - LeetCode 1") == "Two Sum" assert clean_waypoint_title("Longest Substring - LeetCode") == "Longest Substring" assert clean_waypoint_title(None) == "the trial ahead" assert clean_waypoint_title("") == "the trial ahead"
def test_companion_prompt_enforces_user_perspective_choices(): """Verify that build_companion_prompt explicitly requires choice suggestions to be phrased from the user/hero's perspective speaking to the princess. """ req = CompanionChatRequest( princess_name="Princess Aurelia", hero_name="Rowan", current_floor=20, )
system_instruction, user_prompt, hero_name, _ = build_companion_prompt(req)
# 1. System instruction must instruct that choice suggestions are what Rowan says to Aurelia assert "choice_suggestions" in system_instruction assert "Rowan" in system_instruction assert "perspective" in system_instruction.lower() assert "never output lines for princess aurelia to say in \"choice_suggestions\"" in system_instruction.lower() or "never output lines for" in system_instruction.lower()
# 2. User prompt must reinforce user perspective assert "must be phrased from rowan's perspective" in user_prompt.lower() or "perspective" in user_prompt.lower()
def test_sanitize_companion_choices_filters_princess_perspective(): """Verify that sanitize_companion_choices rejects suggestions where the princess speaks to the hero, or refers to her illness in first person, or addresses the hero by name/title. """ from routers.companion import DEFAULT_COMPANION_CHOICES, sanitize_companion_choices
# 1. Reject choices addressing the hero (princess talking to hero) bad_hero_addressed = [ "Are you feeling tired, Rowan?", "Drink some fresh water, Champion.", "Rest your weary eyes, guardian.", "You fought valiantly today, my friend.", ] cleaned = sanitize_companion_choices(bad_hero_addressed, hero_name="Rowan", princess_name="Princess Aurelia") assert cleaned == list(DEFAULT_COMPANION_CHOICES)
# 2. Reject choices where speaker has the illness or weakness in first person bad_illness_first_person = [ "My fever is spiking again this evening.", "My cough has grown worse along the trail.", "I feel so weak from my illness.", "I feel weak and faint today.", "I am feeling dizzy and feverish.", "I cannot walk much further.", "My strength is fading.", ] cleaned_illness = sanitize_companion_choices( bad_illness_first_person, hero_name="Rowan", princess_name="Princess Aurelia" ) assert cleaned_illness == list(DEFAULT_COMPANION_CHOICES)
# 3. Reject role reversal / princess gratitude lines bad_role_reversal = [ "Thank you for protecting me on this road.", "Thank you for saving me, my friend.", "You must be exhausted from our journey.", "Rest your weary bones by the fire.", ] cleaned_reversal = sanitize_companion_choices( bad_role_reversal, hero_name="Rowan", princess_name="Princess Aurelia" ) assert cleaned_reversal == list(DEFAULT_COMPANION_CHOICES)
# 4. Reject choices narrating princess in 3rd person bad_third_person = [ "Princess Aurelia is resting in the wagon.", "Aurelia is looking faint.", "Aurelia rests by the tree.", ] cleaned_3rd = sanitize_companion_choices( bad_third_person, hero_name="Rowan", princess_name="Princess Aurelia" ) assert cleaned_3rd == list(DEFAULT_COMPANION_CHOICES)
# 5. Accept genuine user-to-princess suggestions (including addressing the princess directly) good_user_choices = [ "How is your strength holding up today?", "Let us pause by the fire and boil some tea.", "Let me carry your satchel for a while.", "The mountain path looks steep—we will take it slowly.", "Princess Aurelia, how is your fever?", "Aurelia, drink some warm tea and rest.", ] cleaned_good = sanitize_companion_choices( good_user_choices, hero_name="Rowan", princess_name="Princess Aurelia" ) assert cleaned_good == good_user_choices
# 6. Verify empty or whitespace hero_name does not reject good choices cleaned_empty_hero = sanitize_companion_choices( good_user_choices, hero_name="", princess_name="Princess Aurelia" ) assert cleaned_empty_hero == good_user_choices
cleaned_whitespace_hero = sanitize_companion_choices( good_user_choices, hero_name=" ", princess_name="Princess Aurelia" ) assert cleaned_whitespace_hero == good_user_choices
@pytest.mark.asyncioasync def test_companion_chat_sanitizes_princess_perspective_choices(): """Verify that companion_chat filters out princess-perspective suggestions from LLM output.""" import json
req = CompanionChatRequest( princess_name="Princess Aurelia", hero_name="Rowan", current_floor=50, user_message="How are you feeling?", )
ai_raw = json.dumps({ "text": "The mountain air is crisp today, Rowan. My chest feels lighter after that warm cup of tea.", "emotion": "smiling_warmly", "tool_calls": [], "choice_suggestions": [ "Drink some water, Rowan.", # Bad: Princess to user "My fever is much cooler now.", # Bad: Princess about herself "How is your strength holding up?", # Good: User to princess ], })
with patch("ai_provider.generate_ai_content_async", return_value=(ai_raw, "mock_llm")): mock_request = AsyncMock() mock_request.client.host = "127.0.0.1" mock_request.headers = {} res = await companion_chat(payload=req, request=mock_request, x_custom_api_key="exempt_test_key")
# "Drink some water, Rowan" and "My fever is much cooler now" must be removed for choice in res["choice_suggestions"]: assert "Rowan" not in choice assert "my fever" not in choice.lower() # "How is your strength holding up?" must be retained assert "How is your strength holding up?" in res["choice_suggestions"]
algospaced-ui/dist/assets/CardManager-BEhyd34f.js → algospaced-ui/dist/assets/CardManager-BMwBGmwK.jsRenamed+1-1
algospaced-ui/dist/assets/JourneyPath-BhAvKOiu.js → algospaced-ui/dist/assets/JourneyPath-C5zwoWvi.jsRenamed+1-1
algospaced-ui/dist/assets/MarkdownRenderer-D8UdFpnD.js → algospaced-ui/dist/assets/MarkdownRenderer-BGUaDi8Z.jsRenamed+1-1
algospaced-ui/dist/assets/PrincessChamber-DlL5aOl1.jsAdded+1
algospaced-ui/dist/assets/PrincessChamber-abJShfI5.jsDeleted-1
algospaced-ui/dist/assets/ProblemSpecPanel-BRW8UyO6.js → algospaced-ui/dist/assets/ProblemSpecPanel-C8iV6oe0.jsRenamed+1-1
algospaced-ui/dist/assets/PythonChallenge-CQdOe4Q2.js → algospaced-ui/dist/assets/PythonChallenge-MiR95vc2.jsRenamed+1-1
algospaced-ui/dist/assets/ReviewQueue-BRrPvJUP.jsAdded+5
algospaced-ui/dist/assets/ReviewQueue-CltGWQpb.jsDeleted-5
algospaced-ui/dist/assets/Settings-BVuXk3LW.jsDeleted-1
algospaced-ui/dist/assets/Settings-Dm1_pyAR.jsAdded+1
algospaced-ui/dist/assets/TerminalEmulator-CZed0tiA.js → algospaced-ui/dist/assets/TerminalEmulator-DeoMeHBL.jsRenamed+1-1
algospaced-ui/dist/assets/index-BsU9BpJx.cssDeleted
algospaced-ui/dist/assets/index-DVWZ15xt.js → algospaced-ui/dist/assets/index-Q9onQHft.jsRenamed
algospaced-ui/dist/assets/index-kuOEkBQB.cssAdded
algospaced-ui/dist/index.html+2-2
algospaced-ui/dist/sw.js+1-1
algospaced-ui/package.json+1-1
algospaced-ui/src/components/PrincessDialoguePopup.tsx+1-1
algospaced-ui/src/components/Settings.tsx+6-6
algospaced-ui/src/components/desktop/DesktopWindowContainer.tsx+1-1
algospaced-ui/src/components/review/EmptyQueueCelebration.tsx+3-3
algospaced-ui/src/data/companionData.ts+43-43
algospaced-ui/src/features/companion/api/companionApi.ts+5-4
algospaced-ui/src/features/companion/components/CharacterStage.tsx+1-1
algospaced-ui/src/features/companion/components/ChoiceChips.tsx+15-7
algospaced-ui/src/features/companion/components/JRPGDialogueBox.tsx+14-10
algospaced-ui/src/features/companion/components/PrincessChamber.tsx+29-11
algospaced-ui/src/features/companion/components/PrincessToast.tsx+1-1
algospaced-ui/src/features/companion/components/RoyalSatchelModal.tsx+4-4
algospaced-ui/src/features/companion/components/SpireProgressModal.tsx+6-6
algospaced-ui/src/features/companion/data/chapterWeather.ts+2-2
algospaced-ui/src/features/companion/data/companionLore.ts+41-41
algospaced-ui/src/features/companion/data/towerRhythms.ts+19-19
algospaced-ui/src/features/companion/store/useCompanionStore.ts+154-16
algospaced-ui/src/features/companion/tools/agentTools.ts+3-3
algospaced-ui/src/features/companion/types.ts+2-2
algospaced-ui/src/hooks/useCompanionEvents.ts+2-2
algospaced-ui/src/utils/companionService.ts+5-5
algospaced-ui/tests/companionChoices.test.mjsAdded+193
routers/companion.py+259-58
tests/unit/test_companion_story.pyAdded+366