import{s as o}from"./index-C-Kzd2Hj.js";const v={async getUserProgress(){try{const{data:e}=await o.auth.getSession(),r=e.session?.user;if(!r)return null;const{data:a,error:t}=await o.from("user_progress").select("*").eq("user_id",r.id).single();if(t){if(t.code==="PGRST116")return{id:"placeholder-id",userId:r.id,storiesRead:0,readingTimeMinutes:0,currentStreak:0,lastReadDate:null,highestStreak:0};throw console.error("Error fetching user progress:",t),t}return y(a)}catch(e){return console.error("Error in getUserProgress:",e),null}},async updateUserProgress(e){try{const{data:r}=await o.auth.getSession(),a=r.session?.user;if(!a)return!1;const t=S(e);t.user_id=a.id;const{error:n}=await o.from("user_progress").upsert(t,{onConflict:"user_id"});return n?(console.error("Error updating user progress:",n),!1):!0}catch(r){return console.error("Error in updateUserProgress:",r),!1}},async getStoryCompletions(){try{const{data:e}=await o.auth.getSession(),r=e.session?.user;if(!r)return[];const{data:a,error:t}=await o.from("story_completions").select("*").eq("user_id",r.id);return t?(console.error("Error fetching story completions:",t),[]):a.map(w)}catch(e){return console.error("Error in getStoryCompletions:",e),[]}},async recordStoryProgress(e,r,a,t){try{const{data:n}=await o.auth.getSession(),s=n.session?.user;if(!s)return!1;const i={user_id:s.id,story_id:e,completion_percentage:r,reading_time_minutes:a,is_completed:t,completed_at:t?new Date().toISOString():null},{error:c}=await o.from("story_completions").upsert(i,{onConflict:"user_id,story_id"});return c?(console.error("Error recording story progress:",c),!1):!0}catch(n){return console.error("Error in recordStoryProgress:",n),!1}},async updateUserProgressWithTracking(e){try{const{data:r}=await o.auth.getSession(),a=r.session?.user;if(!a)return!1;const{data:t,error:n}=await o.from("user_progress").select("*").eq("user_id",a.id).single();if(n&&n.code!=="PGRST116")return console.error("Error fetching user progress:",n),!1;const s=new Date().toISOString().split("T")[0];let i=1,c=1,g=e;if(t){g+=t.reading_time_minutes;const u=t.last_read_date?new Date(t.last_read_date).toISOString().split("T")[0]:null;if(u)if(u===s)i=t.current_streak;else{const l=new Date;l.setDate(l.getDate()-1);const m=l.toISOString().split("T")[0];u===m?i=t.current_streak+1:i=1}c=Math.max(i,t.highest_streak||0)}const f={user_id:a.id,reading_time_minutes:g,current_streak:i,highest_streak:c,last_read_date:new Date().toISOString(),stories_read:t?.stories_read||0},{error:d}=await o.from("user_progress").upsert(f,{onConflict:"user_id"});return d?(console.error("Error updating user progress:",d),!1):!0}catch(r){return console.error("Error in updateUserProgressWithTracking:",r),!1}},async incrementStoriesRead(){try{const{data:e}=await o.auth.getSession(),r=e.session?.user;if(!r)return!1;const{data:a,error:t}=await o.from("user_progress").select("stories_read").eq("user_id",r.id).single();if(t&&t.code!=="PGRST116")return console.error("Error fetching user progress:",t),!1;const s=(a?.stories_read||0)+1,{error:i}=await o.from("user_progress").update({stories_read:s}).eq("user_id",r.id);return i?(console.error("Error incrementing stories read:",i),!1):!0}catch(e){return console.error("Error in incrementStoriesRead:",e),!1}},async recalculateStoriesRead(){try{const{data:e}=await o.auth.getSession(),r=e.session?.user;if(!r)return!1;const{data:a,error:t}=await o.from("story_completions").select("story_id, completion_percentage, is_completed").eq("user_id",r.id).or("is_completed.eq.true,completion_percentage.gte.80");if(t)return console.error("Error fetching story completions:",t),!1;const s=new Set(a.map(c=>c.story_id)).size;console.log(`Recalculated stories read: ${s} unique stories`);const{error:i}=await o.from("user_progress").update({stories_read:s}).eq("user_id",r.id);return i?(console.error("Error updating stories read count:",i),!1):!0}catch(e){return console.error("Error in recalculateStoriesRead:",e),!1}},async updateUserProgressOnCompletion(e){try{const{data:r}=await o.auth.getSession();return r.session?.user?await this.updateUserProgressWithTracking(e):!1}catch(r){return console.error("Error in updateUserProgressOnCompletion:",r),!1}},async calculateWordsLearned(){try{const{data:e}=await o.auth.getSession(),r=e.session?.user;if(!r)return 0;const{data:a,error:t}=await o.from("vocabulary_words").select("id").eq("user_id",r.id);return t?(console.error("Error counting vocabulary words:",t),0):a?.length||0}catch(e){return console.error("Error in calculateWordsLearned:",e),0}},async fixUserProgress(){try{const{data:e}=await o.auth.getSession(),r=e.session?.user;if(!r)return!1;console.log("Starting user progress data fix..."),await this.recalculateStoriesRead();const{data:a,error:t}=await o.from("story_completions").select("reading_time_minutes").eq("user_id",r.id);if(t)return console.error("Error fetching story completions:",t),!1;const n=a.reduce((_,p)=>_+(p.reading_time_minutes||0),0);console.log(`Recalculated reading time: ${n} minutes`);const{data:s}=await o.from("user_progress").select("*").eq("user_id",r.id).single(),i=await this.getCompletedStoriesCount(),c=await this.calculateWordsLearned(),g=new Date().toISOString().split("T")[0],f=s?.current_streak||0,d=s?.last_read_date?new Date(s.last_read_date).toISOString().split("T")[0]:null;let u=f;if(d){const _=new Date;_.setDate(_.getDate()-1);const p=_.toISOString().split("T")[0];d!==g&&d!==p&&(u=0)}const l={user_id:r.id,reading_time_minutes:n,current_streak:u,highest_streak:Math.max(u,s?.highest_streak||0),last_read_date:s?.last_read_date||null,stories_read:i},{error:m}=await o.from("user_progress").upsert(l,{onConflict:"user_id"});return m?(console.error("Error updating user progress:",m),!1):(console.log("User progress data fixed successfully"),!0)}catch(e){return console.error("Error in fixUserProgress:",e),!1}},async getCompletedStoriesCount(){try{const{data:e}=await o.auth.getSession(),r=e.session?.user;if(!r)return 0;const{data:a,error:t}=await o.from("story_completions").select("story_id").eq("user_id",r.id).or("is_completed.eq.true,completion_percentage.gte.80");return t?(console.error("Error counting completed stories:",t),0):new Set(a.map(s=>s.story_id)).size}catch(e){return console.error("Error in getCompletedStoriesCount:",e),0}}};function y(e){return{id:e.id||"placeholder-id",userId:e.user_id||"placeholder-user-id",storiesRead:e.stories_read||0,readingTimeMinutes:e.reading_time_minutes||0,currentStreak:e.current_streak||0,lastReadDate:e.last_read_date||null,highestStreak:e.highest_streak||0}}function S(e){const r={};return e.storiesRead!==void 0&&(r.stories_read=e.storiesRead),e.readingTimeMinutes!==void 0&&(r.reading_time_minutes=e.readingTimeMinutes),e.currentStreak!==void 0&&(r.current_streak=e.currentStreak),e.lastReadDate!==void 0&&(r.last_read_date=e.lastReadDate),e.highestStreak!==void 0&&(r.highest_streak=e.highestStreak),r}function w(e){return{id:e.id||"placeholder-id",userId:e.user_id||"placeholder-user-id",storyId:e.story_id||"placeholder-story-id",completionPercentage:e.completion_percentage||0,readingTimeMinutes:e.reading_time_minutes||0,isCompleted:e.is_completed||!1,completedAt:e.completed_at||null}}const h=[1,.5,.25,.1];function E(e){return e<3?h[e]:h[3]}function D(e){if(e==null)throw new Error("SESL score is required for XP calculation");return Math.max(10,Math.floor(e/10))}const k={async recordXPEvent(e){const{data:r}=await o.auth.getSession();if(!r?.session?.user)return!1;const a=r.session.user.id,t=new Date().toISOString(),{data:n}=await o.from("user_xp_events").select("id, events").eq("user_id",a).eq("story_id",e).maybeSingle();if(n){const s=n.events?`${n.events},${t}`:t,{error:i}=await o.from("user_xp_events").update({events:s}).eq("id",n.id);return i?(console.error("Failed to update XP event:",i),!1):!0}else{const{error:s}=await o.from("user_xp_events").insert({user_id:a,story_id:e,events:t});return s?(console.error("Failed to insert XP event:",s),!1):!0}},async getUserXPHistory(){const{data:e}=await o.auth.getSession();if(!e?.session?.user)return[];const{data:r,error:a}=await o.from("user_xp_events").select(`
        story_id,
        events,
        stories!inner(title, sesl_score, thumbnail)
      `).eq("user_id",e.session.user.id);if(a||!r)return console.error("Failed to fetch XP history:",a),[];const t=[];for(const s of r){const i=s.stories,c=i.sesl_score;if(c==null){console.error(`Story ${s.story_id} missing SESL score - skipping XP calculation`);continue}const g=D(c);(s.events?s.events.split(","):[]).forEach((d,u)=>{const l=E(u);t.push({timestamp:d.trim(),storyId:s.story_id,storyTitle:i.title,storyThumbnail:i.thumbnail,seslScore:c,xpEarned:Math.round(g*l),cumulativeXP:0,readNumber:u+1})})}t.sort((s,i)=>new Date(s.timestamp).getTime()-new Date(i.timestamp).getTime());let n=0;return t.forEach(s=>{n+=s.xpEarned,s.cumulativeXP=n}),t},async getTotalXP(){const e=await this.getUserXPHistory();return e.length>0?e[e.length-1].cumulativeXP:0}};export{v as u,k as x};