import{j as e}from"./query-vendor-CZu0EHPe.js";import{r as n,j as Le}from"./react-vendor-0bvDbF03.js";import{u as ke,a as ce,s as D,A as Fe,m as de,b as Ie,c as Ee,g as ie,G as Re,S as Pe,B as R,d as Te}from"./index-CwGgW-mc.js";import{S as me}from"./StoryCard-DrMmBVM2.js";import{S as ne,m as Me}from"./slider-7EpA47SO.js";import{I as Be}from"./input-BmGI2AMP.js";import{S as P,a as T,b as M,c as B,d as $}from"./select-CZOpKSzH.js";import{C as $e,a as De,b as Ve}from"./collapsible-D9FFVC2H.js";import{B as Oe}from"./BreadcrumbNavigation-BdjsMZvM.js";import{S as w}from"./skeleton-CuroRPkC.js";import{u as ue}from"./i18n-vendor-Cl4-lKeC.js";import{B as Ge}from"./bookmark-WjXFM5FJ.js";import{S as oe}from"./search-Cu3Q9NK2.js";import{C as Ue}from"./chevron-down-35EsGFOb.js";import{R as We}from"./rotate-ccw-WJG_6zgW.js";import"./supabase-vendor-CNV44oIa.js";import"./helmet-vendor-NlTFkN97.js";import"./card-MP0DL603.js";import"./AccessLevelBadge-BgU9jy8n.js";import"./dialog-oFFe7yWE.js";import"./UpgradeButton-XXtqY7Or.js";import"./AnimatedBadge-Bn2am2np.js";import"./sesl-badge-utils-ehMeVD2e.js";import"./clock-CoodSkBk.js";import"./book-check-B9nHWc0Z.js";import"./index-mXG3wuIW.js";import"./chevron-up-CbGDMrSQ.js";import"./index-188qFkvA.js";const qe=()=>{const[c,v]=n.useState(new Set),[S,u]=n.useState(!0),{user:d}=ke(),{toast:b}=ce(),f=!!d;n.useEffect(()=>{(async()=>{if(!f||!d){v(new Set),u(!1);return}try{const{data:o,error:i}=await D.from("reading_cart").select("story_id").eq("user_id",d.id);if(i)throw i;const h=new Set(o?.map(m=>m.story_id)||[]);v(h)}catch(o){console.error("Error fetching reading cart:",o),b({title:"Error",description:"Failed to load reading cart items.",variant:"destructive"})}finally{u(!1)}})()},[f,d,b]);const y=(r,o)=>{v(i=>{const h=new Set(i);return o?h.add(r):h.delete(r),h})},l=r=>c.has(r),g=c.size;return{isStoryInCart:l,updateCartState:y,isLoading:S,cartCount:g}},ze=()=>e.jsxs("div",{className:"h-full rounded-lg overflow-hidden bg-white shadow-md",children:[e.jsx(w,{className:"h-48 w-full"}),e.jsxs("div",{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(w,{className:"h-6 w-16"}),e.jsx(w,{className:"h-6 w-20"})]}),e.jsx(w,{className:"h-6 w-3/4 mb-2"}),e.jsx(w,{className:"h-4 w-full mb-2"}),e.jsx(w,{className:"h-4 w-2/3"})]}),e.jsxs("div",{className:"p-4 pt-0 flex gap-2",children:[e.jsx(w,{className:"h-5 w-12"}),e.jsx(w,{className:"h-5 w-16"}),e.jsx(w,{className:"h-5 w-14"})]})]}),He=(c,v,S)=>{const u=(l,g)=>{const r=new Date(l.createdAt||0).getTime();return new Date(g.createdAt||0).getTime()-r},d=l=>S.includes(l);if(v==="paid"||v==="admin"){const l=c.filter(r=>!d(r.id)).sort(u),g=c.filter(r=>d(r.id)).sort(u);return[...l,...g]}if(v==="free"){const l=c.filter(i=>i.accessLevel==="free"&&!d(i.id)).sort(u),g=c.filter(i=>i.accessLevel==="guest"&&!d(i.id)).sort(u),r=c.filter(i=>(i.accessLevel==="free"||i.accessLevel==="guest")&&d(i.id)).sort(u),o=c.filter(i=>i.accessLevel==="paid").sort(u);return[...l,...g,...r,...o]}const b=c.filter(l=>l.accessLevel==="guest").sort(u),f=c.filter(l=>l.accessLevel==="free").sort(u),y=c.filter(l=>l.accessLevel==="paid").sort(u);return[...b,...f,...y]},Je=({stories:c,readStoryIds:v,isStoryInCart:S,updateCartState:u,getLocalizedPath:d,canAccessStory:b,isAuthenticated:f,visible:y})=>{const{t:l}=ue("stories"),[g,r]=n.useState(!1),o=n.useMemo(()=>[...c].sort((h,m)=>{const F=h.createdAt?new Date(h.createdAt).getTime():0;return(m.createdAt?new Date(m.createdAt).getTime():0)-F}).slice(0,8),[c]);if(o.length===0)return null;const i=[...o,...o];return e.jsx(Fe,{initial:!1,children:y&&e.jsxs(de.section,{initial:{opacity:0,height:0},animate:{opacity:1,height:"auto"},exit:{opacity:0,height:0},transition:{duration:.28,ease:"easeOut"},className:"mb-8 overflow-hidden","aria-label":l("badge.new",{defaultValue:"New!"}),children:[e.jsx("div",{className:"flex items-center mb-3 px-1",children:e.jsxs("span",{className:"inline-flex items-center gap-1.5 bg-nature-yellow text-primary-foreground font-semibold text-sm px-3 py-1 rounded-full",children:[e.jsx(Ge,{className:"h-4 w-4"}),l("badge.new",{defaultValue:"New!"})]})}),e.jsx("div",{className:"newest-rail-mask relative",onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),onTouchStart:()=>r(!0),onTouchEnd:()=>r(!1),children:e.jsx("div",{className:`newest-rail-track flex gap-4 w-max ${g?"is-paused":""}`,children:i.map((h,m)=>e.jsx("div",{className:"w-[260px] sm:w-[280px] flex-shrink-0","aria-hidden":m>=o.length?"true":void 0,children:e.jsx(me,{story:h,isMarkedAsRead:v.includes(String(h.id)),isInCart:S(h.id),onCartChange:u,index:m%o.length,getLocalizedPath:d,hasAccess:b(h.accessLevel||"paid"),isAuthenticated:f})},`${h.id}-${m}`))})})]},"newest-rail")})},ys=()=>{const[c,v]=n.useState([]),[S,u]=n.useState(!0),[d,b]=Le(),[f,y]=n.useState(d.get("search")||""),[l,g]=n.useState(d.get("age")||"all"),[r,o]=n.useState(d.get("level")||"all"),[i,h]=n.useState(d.get("theme")||"all"),[m,F]=n.useState(d.get("sesl")||"all"),[p,z]=n.useState([0,600]),[A,H]=n.useState([0,1e3]),[J,he]=n.useState(!1),{t}=ue("stories"),{getLocalizedPath:V}=Ie(),fe=()=>{y(""),g("all"),o("all"),h("all"),F("all"),z([0,600]),H([0,1e3])},{toast:O}=ce(),{canAccessStory:K,isAuthenticated:I,userType:ge}=Ee(),{isStoryInCart:Q,updateCartState:X}=qe(),[G,Y]=n.useState([]),[_,Z]=n.useState(1),U=12,ee=n.useRef(null),xe=[{label:t("age.all"),value:"all"},{label:`5-7 ${t("age.years")}`,value:"5-7"},{label:`7-9 ${t("age.years")}`,value:"7-9"},{label:`9-12 ${t("age.years")}`,value:"9-12"},{label:`12-15 ${t("age.years")}`,value:"12-15"},{label:`15-18 ${t("age.years")}`,value:"15-18"},{label:`18+ ${t("age.years")}`,value:"18+"}],ve=[{label:t("level.all"),value:"all"},{label:t("level.A1"),value:"A1"},{label:t("level.A2"),value:"A2"},{label:t("level.B1"),value:"B1"},{label:t("level.B2"),value:"B2"},{label:t("level.C1"),value:"C1"},{label:t("level.C2"),value:"C2"}],pe=[{label:t("theme.all"),value:"all"},{label:t("theme.adventure_curiosity"),value:"Adventure & Curiosity"},{label:t("theme.anger_frustration"),value:"Anger & Frustration"},{label:t("theme.confidence_determination"),value:"Confidence & Determination"},{label:t("theme.fear_courage"),value:"Fear & Courage"},{label:t("theme.friendship_teamwork"),value:"Friendship & Teamwork"},{label:t("theme.fun_wit"),value:"Fun & Wit"},{label:t("theme.jealousy_appreciation"),value:"Jealousy & Appreciation"},{label:t("theme.kindness_empathy"),value:"Kindness & Empathy"},{label:t("theme.magic_wonder"),value:"Magic & Wonder"},{label:t("theme.nature_animals"),value:"Nature & Animals"},{label:t("theme.problem_solution"),value:"Problem & Solution"},{label:t("theme.sadness_loss"),value:"Sadness & Loss"}],be=[{label:t("sesl.filter.all"),value:"all"},{label:`${t("sesl.difficulty.very_easy")} (0-250)`,value:"very_easy"},{label:`${t("sesl.difficulty.easy")} (251-450)`,value:"easy"},{label:`${t("sesl.difficulty.medium")} (451-650)`,value:"medium"},{label:`${t("sesl.difficulty.hard")} (651-800)`,value:"hard"},{label:`${t("sesl.difficulty.very_hard")} (801-1000)`,value:"very_hard"}],k=n.useCallback(async()=>{console.log("fetchReadStories running, isAuthenticated:",I);try{const{data:s}=await D.auth.getSession(),a=s.session?.user;if(console.log("User session in fetchReadStories:",a?a.id:"No user"),!a){console.log("No user found, clearing read story IDs"),Y([]);return}const{data:j,error:N}=await D.from("story_completions").select("story_id").eq("user_id",a.id).eq("mark_as_read",!0);if(N){console.error("Error fetching read stories:",N);return}if(j){console.log("Raw read stories data:",j);const C=j.map(L=>String(L.story_id));console.log("Processed read story IDs:",C),Y(C)}}catch(s){console.error("Error fetching read stories:",s)}},[I]);n.useEffect(()=>{(async()=>{u(!0);try{console.log("Fetching stories using security definer function for listing...");const{data:a,error:j}=await D.rpc("get_stories_for_listing");if(j){console.error("Error fetching stories:",j),O({title:t("toast.loadError"),description:t("toast.loadErrorDescription"),variant:"destructive"});return}if(console.log("Raw Supabase data:",a),a){const N=a.map(C=>{const L=C.access_level;return Me({...C,text:"",audio_url:"",word_timestamps:[],access_level:L||"paid"})});console.log("Mapped stories:",N),v(N)}}catch(a){console.error("Error in fetchStories:",a),O({title:t("toast.loadError"),description:t("toast.loadErrorDescription"),variant:"destructive"})}finally{u(!1)}})()},[O]),n.useEffect(()=>{k()},[k]),n.useEffect(()=>{const s=()=>{document.hidden||(console.log("Page became visible, refreshing read stories..."),k())},a=()=>{console.log("Window focused, refreshing read stories..."),k()};return document.addEventListener("visibilitychange",s),window.addEventListener("focus",a),()=>{document.removeEventListener("visibilitychange",s),window.removeEventListener("focus",a)}},[k]),n.useEffect(()=>{const s=new URLSearchParams;f&&s.set("search",f),l&&l!=="all"&&s.set("age",l),r&&r!=="all"&&s.set("level",r),i&&i!=="all"&&s.set("theme",i),m&&m!=="all"&&s.set("sesl",m),b(s),Z(1)},[f,l,r,i,m,b]);const je=c.filter(s=>{console.log("Filtering story:",s.title,{searchTerm:f,ageFilter:l,levelFilter:r,themeFilter:i,seslFilter:m,story:{ageRange:s.ageRange,cefrLevel:s.cefrLevel,theme:s.theme,duration:s.duration,wordCount:s.wordCount,seslScore:s.seslScore}});const a=!f||s.title.toLowerCase().includes(f.toLowerCase())||s.description.toLowerCase().includes(f.toLowerCase()),j=l==="all"||ie(s.cefrLevel)===l,N=r==="all"||s.cefrLevel===r,C=i==="all"||Array.isArray(s.theme)&&s.theme.some(x=>x.toLowerCase()===i.toLowerCase()),L=m==="all"||(()=>{if(s.seslScore===void 0||s.seslScore===null)return!1;const x=s.seslScore;switch(m){case"very_easy":return x>=0&&x<=250;case"easy":return x>=251&&x<=450;case"medium":return x>=451&&x<=650;case"hard":return x>=651&&x<=800;case"very_hard":return x>=801&&x<=1e3;default:return!0}})(),ae=s.duration>=p[0]&&s.duration<=p[1],le=s.wordCount>=A[0]&&s.wordCount<=A[1],re=a&&j&&N&&C&&L&&ae&≤return console.log("Story matches filters:",re,{searchMatch:a,ageMatch:j,levelMatch:N,themeMatch:C,seslMatch:L,durationMatch:ae,wordCountMatch:le}),re}),E=He(je,ge,G);console.log("Sorted stories count:",E.length);const se=(_-1)*U,we=se+U,te=E.slice(se,we),W=Math.ceil(E.length/U),Se=f.trim()!==""||l!=="all"||r!=="all"||i!=="all"||m!=="all"||p[0]!==0||p[1]!==600||A[0]!==0||A[1]!==1e3,ye=s=>{y(s.target.value)},Ne=s=>{if(g(s),s==="all")o("all");else{const a=Te(s);a&&o(a)}},Ce=s=>{if(o(s),s==="all")g("all");else{const a=ie(s);a&&a!=="Unknown"&&g(a)}},Ae=s=>{h(s)},_e=s=>{F(s)},q=s=>{Z(s),setTimeout(()=>{ee.current?.scrollIntoView({behavior:"smooth",block:"start"})},50)};return e.jsxs(e.Fragment,{children:[e.jsx(Re,{}),e.jsx(Pe,{title:t("meta.title"),description:t("meta.description"),keywords:t("meta.keywords",{defaultValue:""})||void 0,canonical:"/stories"}),e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-sky-300 via-lime-200 to-fuchsia-300",children:e.jsxs("div",{className:"container px-4 md:px-6 py-8",children:[e.jsx(Oe,{}),e.jsx("div",{className:"mb-12",children:e.jsxs("div",{className:"flex flex-col lg:flex-row items-center justify-center gap-6 lg:gap-8",children:[e.jsx("div",{className:"w-48 h-48 lg:w-56 lg:h-56 flex-shrink-0",children:e.jsx(de.div,{animate:{y:[0,-12,0]},transition:{duration:3,repeat:1/0,ease:"easeInOut"},children:e.jsx("img",{src:"https://cdn.storysparkle.org/ui_elements/Hero%20Icons/StoryLibrary.webp",alt:"Story Library",className:"w-full h-full object-contain drop-shadow-2xl"})})}),e.jsxs("div",{className:"flex flex-col items-center lg:items-start text-center lg:text-left",children:[e.jsx("h1",{className:"text-5xl lg:text-6xl font-bold mb-4 text-black",children:t("header.title")}),e.jsx("p",{className:"text-lg lg:text-xl text-nature-red inline-block",children:t("header.subtitle")})]})]})}),!S&&e.jsx(Je,{stories:c,readStoryIds:G,isStoryInCart:Q,updateCartState:X,getLocalizedPath:V,canAccessStory:s=>K(s),isAuthenticated:I,visible:!Se}),e.jsx($e,{open:J,onOpenChange:he,children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-lg mb-8",children:[e.jsx(De,{asChild:!0,children:e.jsxs("button",{className:"w-full flex items-center justify-between p-6 hover:bg-gray-50 transition-colors rounded-2xl",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(oe,{className:"h-5 w-5 text-nature-teal"}),e.jsx("span",{className:"text-lg font-semibold text-gray-800",children:t("search.label")})]}),e.jsx(Ue,{className:`h-5 w-5 text-gray-600 transition-transform duration-300 ${J?"rotate-180":""}`})]})}),e.jsxs(Ve,{className:"px-6 pb-6",children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("label",{htmlFor:"search",className:"block text-sm font-medium text-gray-700 mb-2",children:t("search.label")}),e.jsxs("div",{className:"relative",children:[e.jsx(Be,{id:"search",type:"text",placeholder:t("search.placeholder"),value:f,onChange:ye,className:"pl-10 pr-4 py-3 text-base border-gray-300 focus:border-nature-teal focus:ring-nature-teal"}),e.jsx(oe,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-4 gap-4 mb-6",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"age-filter",className:"block text-sm font-medium text-gray-700 mb-2",children:t("age.label")}),e.jsxs(P,{value:l,onValueChange:Ne,children:[e.jsx(T,{id:"age-filter",className:"w-full",children:e.jsx(M,{placeholder:t("age.placeholder")})}),e.jsx(B,{children:xe.map(s=>e.jsx($,{value:s.value,children:s.label},s.value))})]})]}),e.jsxs("div",{children:[e.jsxs("label",{htmlFor:"sesl-filter",className:"text-sm font-medium text-gray-700 mb-2 flex items-center gap-2",children:[t("sesl.filterLabel"),e.jsx("a",{href:V("/research"),target:"_blank",rel:"noopener noreferrer",className:"text-xs text-nature-teal hover:underline",children:t("readMore")})]}),e.jsxs(P,{value:m,onValueChange:_e,children:[e.jsx(T,{id:"sesl-filter",className:"w-full",children:e.jsx(M,{placeholder:t("sesl.filter.placeholder")})}),e.jsx(B,{children:be.map(s=>e.jsx($,{value:s.value,children:s.label},s.value))})]})]}),e.jsxs("div",{children:[e.jsxs("label",{htmlFor:"level-filter",className:"text-sm font-medium text-gray-700 mb-2 flex items-center gap-2",children:[t("level.label"),e.jsx("a",{href:"https://www.cambridgeenglish.org/exams-and-tests/cefr/",target:"_blank",rel:"noopener noreferrer",className:"text-xs text-nature-teal hover:underline",children:t("readMore")})]}),e.jsxs(P,{value:r,onValueChange:Ce,children:[e.jsx(T,{id:"level-filter",className:"w-full",children:e.jsx(M,{placeholder:t("level.placeholder")})}),e.jsx(B,{children:ve.map(s=>e.jsx($,{value:s.value,children:s.label},s.value))})]})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"theme-filter",className:"block text-sm font-medium text-gray-700 mb-2",children:t("theme.label")}),e.jsxs(P,{value:i,onValueChange:Ae,children:[e.jsx(T,{id:"theme-filter",className:"w-full",children:e.jsx(M,{placeholder:t("theme.placeholder")})}),e.jsx(B,{children:pe.map(s=>e.jsx($,{value:s.value,children:s.label},s.value))})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"text-sm font-medium text-gray-700 mb-2 block",children:[t("duration.label"),": ",Math.floor(p[0]/60),":",(p[0]%60).toString().padStart(2,"0")," – ",Math.floor(p[1]/60),":",(p[1]%60).toString().padStart(2,"0")]}),e.jsx(ne,{value:p,onValueChange:z,max:600,min:0,step:30,className:"w-full"}),e.jsxs("div",{className:"flex justify-between text-xs text-gray-500 mt-1",children:[e.jsxs("span",{children:["0 ",t("duration.minutes")]}),e.jsxs("span",{children:["10 ",t("duration.minutes")]})]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-sm font-medium text-gray-700 mb-2 block",children:[t("wordCount.label"),": ",A[0]," – ",A[1]]}),e.jsx(ne,{value:A,onValueChange:H,max:1e3,min:0,step:50,className:"w-full"}),e.jsxs("div",{className:"flex justify-between text-xs text-gray-500 mt-1",children:[e.jsxs("span",{children:["0 ",t("wordCount.words")]}),e.jsxs("span",{children:["1000 ",t("wordCount.words")]})]})]})]}),e.jsx("div",{className:"mt-6 flex justify-end",children:e.jsxs(R,{onClick:fe,variant:"outline",className:"text-nature-teal border-nature-teal hover:bg-nature-teal hover:text-white",children:[e.jsx(We,{className:"h-4 w-4 mr-2"}),t("filters.resetAll")]})})]})]})}),e.jsx("div",{className:"mb-6",children:e.jsxs("h2",{className:"text-2xl font-semibold text-gray-800",children:[E.length," Stories Found"]})}),e.jsx("div",{ref:ee,className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:S?Array.from({length:8}).map((s,a)=>e.jsx(ze,{},a)):te.length>0?te.map((s,a)=>e.jsx(me,{story:s,isMarkedAsRead:G.includes(String(s.id)),isInCart:Q(s.id),onCartChange:X,index:a,getLocalizedPath:V,hasAccess:K(s.accessLevel||"paid"),isAuthenticated:I},s.id)):e.jsxs("div",{className:"col-span-1 sm:col-span-2 lg:col-span-3 xl:col-span-4 text-center py-8",children:[e.jsx("h2",{className:"text-xl font-semibold text-gray-500",children:t("error.noStoriesTitle")}),e.jsx("p",{className:"text-gray-400 mt-2",children:t("error.noStoriesDescription")})]})}),W>1&&e.jsx("div",{className:"flex justify-center mt-8",children:e.jsxs("div",{className:"join",children:[e.jsx(R,{className:"join-item",disabled:_===1,onClick:()=>q(_-1),children:"«"}),Array.from({length:W},(s,a)=>a+1).map(s=>e.jsx(R,{className:"join-item",disabled:_===s,onClick:()=>q(s),children:s},s)),e.jsx(R,{className:"join-item",disabled:_===W,onClick:()=>q(_+1),children:"»"})]})})]})})]})};export{ys as default};
//# sourceMappingURL=StoriesPage-Bb7V9xmA.js.map