UNPKG

@gv-sh/specgen-user

Version:

[![Version](https://img.shields.io/badge/version-0.14.1-blue.svg)](https://github.com/gv-sh/specgen-user)

1 lines 34.4 kB
"use strict";(self.webpackChunk_gv_sh_specgen_user=self.webpackChunk_gv_sh_specgen_user||[]).push([[849],{7413:(e,t,a)=>{a.d(t,{Fc:()=>m,TN:()=>g});var r=a(9379),s=a(3986),n=a(9950),o=a(90),l=a(4414);const i=["className","variant"],c=["className","children"],d=["className"],m=n.forwardRef(((e,t)=>{let{className:a,variant:n="default"}=e,c=(0,s.A)(e,i);return(0,l.jsx)("div",(0,r.A)({ref:t,role:"alert",className:(0,o.cn)("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",{"bg-destructive/15 text-destructive border-destructive/50":"destructive"===n,"bg-muted border-border":"default"===n},a)},c))}));m.displayName="Alert";n.forwardRef(((e,t)=>{let{className:a,children:n}=e,i=(0,s.A)(e,c);return(0,l.jsx)("h5",(0,r.A)((0,r.A)({ref:t,className:(0,o.cn)("mb-1 font-medium leading-none tracking-tight",a)},i),{},{children:n}))})).displayName="AlertTitle";const g=n.forwardRef(((e,t)=>{let{className:a}=e,n=(0,s.A)(e,d);return(0,l.jsx)("div",(0,r.A)({ref:t,className:(0,o.cn)("text-sm [&_p]:leading-relaxed",a)},n))}));g.displayName="AlertDescription"},9294:(e,t,a)=>{a.d(t,{jE:()=>d,nM:()=>m,B8:()=>h,lX:()=>g});var r=a(9379),s=a(6910);const n={API_URL:"/api",PORT:{NODE_ENV:"production",PUBLIC_URL:"",WDS_SOCKET_HOST:void 0,WDS_SOCKET_PATH:void 0,WDS_SOCKET_PORT:void 0,FAST_REFRESH:!0,REACT_APP_API_URL:"/api"}.PORT||3002,TIMEOUT:5e3};console.log("Using API URL:",n.API_URL);const o=n;const l=new class{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:50;this.cache=new Map,this.maxSize=e}get(e){if(this.cache.has(e)){const{value:t,expiry:a}=this.cache.get(e);if(!a||a>Date.now())return t;this.cache.delete(e)}}set(e,t){let a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;if(this.cache.size>=this.maxSize){const e=this.cache.keys().next().value;this.cache.delete(e)}const r=a?Date.now()+a:null;this.cache.set(e,{value:t,expiry:r})}clear(){this.cache.clear()}},i="".concat(o.API_URL,"/api");console.log("API Base URL:",i);const c=s.A.create({baseURL:i,headers:{"Content-Type":"application/json"}}),d=async()=>{try{const e="categories",t=l.get(e);if(t)return console.log("Using cached categories data"),t;const a=await c.get("/categories");return l.set(e,a.data,3e5),a.data}catch(e){throw console.error("Error fetching categories:",e),e}},m=async e=>{try{const t="parameters_".concat(e),a=l.get(t);if(a)return console.log("Using cached parameters data for category ".concat(e)),a;const r=await c.get("/parameters?categoryId=".concat(e));return l.set(t,r.data,3e5),r.data}catch(t){throw console.error("Error fetching parameters for category ".concat(e,":"),t),t}},g=async function(e,t){let a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"combined",s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;try{const t="request-".concat(Date.now());if(!e||0===Object.keys(e).length)return{success:!1,error:"No parameters provided for generation"};const o={parameterValues:e,contentType:a};s&&(o.year=parseInt(s,10)),n&&(o.title=n),console.log("Generation payload:",JSON.stringify(o,null,2));const l=await c.post("/generate",o),i={id:t,title:l.data.title||n||"Untitled Story",createdAt:(new Date).toISOString(),content:l.data.content,imageData:l.data.imageData?"data:image/png;base64,".concat(l.data.imageData):null,parameterValues:e,metadata:l.data.metadata,year:l.data.year||s||null};return u(i),(0,r.A)((0,r.A)({},l.data),{},{success:!0,generatedStory:i})}catch(l){var o;return console.error("Content generation error:",l),l.response?{success:!1,error:(null===(o=l.response.data)||void 0===o?void 0:o.error)||"Server error: ".concat(l.response.status)}:l.request?{success:!1,error:"No response from server. Please check your connection."}:{success:!1,error:l.message||"Failed to generate content. Please try again."}}},u=e=>{try{const a=localStorage.getItem("specgen-history");let s=a?JSON.parse(a):[];s=[e,...s],s.length>10&&(s=s.slice(0,10)),s=s.map((e=>(0,r.A)((0,r.A)({},e),{},{imageData:e.imageData?"stored-externally":null})));try{localStorage.setItem("specgen-history",JSON.stringify(s)),console.log("Saved story to history:",e.id)}catch(t){"QuotaExceededError"===t.name&&(localStorage.removeItem("specgen-cached-stories"),s=s.slice(0,5),localStorage.setItem("specgen-history",JSON.stringify(s)),console.warn("Storage quota nearly exceeded, reduced history size"))}}catch(a){console.error("Error saving to generation history:",a)}},h=async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};try{const t=await c.get("/content");if(t.data&&t.data.success){let a=t.data.data||[];if(a=a.filter((e=>e.content)),e.year&&(a=a.filter((t=>{var a;return t.year===parseInt(e.year,10)||(null===(a=t.year)||void 0===a?void 0:a.toString())===e.year}))),e.search){const t=e.search.toLowerCase();a=a.filter((e=>e.title&&e.title.toLowerCase().includes(t)||e.content&&e.content.toLowerCase().includes(t)))}return"oldest"===e.sort?a.sort(((e,t)=>new Date(e.createdAt)-new Date(t.createdAt))):a.sort(((e,t)=>new Date(t.createdAt)-new Date(e.createdAt))),{success:!0,data:a}}return x(e)}catch(t){return console.error("Error fetching stories from API:",t),x(e)}},x=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};try{const t=localStorage.getItem("specgen-history"),a=(t?JSON.parse(t):[]).map((e=>({id:e.id||"gen-".concat(Date.now()+Math.random()),title:e.title||p(e.content),content:e.content||"",imageData:y(e.imageData),createdAt:e.timestamp||e.createdAt||(new Date).toISOString(),year:e.year||null,parameterValues:e.parameterValues||{},metadata:e.metadata||{}})));console.log("Fallback: Using localStorage for stories");let r=[...a];if(e.year&&(r=r.filter((t=>t.year===parseInt(e.year,10)))),e.search){const t=e.search.toLowerCase();r=r.filter((e=>e.title&&e.title.toLowerCase().includes(t)||e.content&&e.content.toLowerCase().includes(t)))}return"oldest"===e.sort?r.sort(((e,t)=>new Date(e.createdAt)-new Date(t.createdAt))):r.sort(((e,t)=>new Date(t.createdAt)-new Date(e.createdAt))),{success:!0,data:r}}catch(t){return console.error("Error in localStorage fallback:",t),{success:!1,error:"Failed to fetch stories",data:[]}}},y=e=>e&&"string"===typeof e?e.startsWith("data:image")?e:"data:image/png;base64,".concat(e):null,p=e=>{if(!e)return"Untitled Story";if(e.includes("**Title:")){const t=e.match(/\*\*Title:(.*?)\*\*/);if(t&&t[1])return t[1].trim()}const t=e.split(/[.!?]|\n/)[0].trim();return t.length<=40?t:t.substring(0,37)+"..."}},9849:(e,t,a)=>{a.r(t),a.d(t,{default:()=>te});var r=a(9950),s=a(8429),n=a(2074),o=a(1111),l=a(7413),i=a(3052),c=a(5924),d=a(6987),m=a(9379),g=a(3986),u=a(90),h=a(4414);const x=["className"],y=["className"],p=["className"],f=["className"],v=["className"],w=["className"],j=r.forwardRef(((e,t)=>{let{className:a}=e,r=(0,g.A)(e,x);return(0,h.jsx)("div",(0,m.A)({ref:t,className:(0,u.cn)("rounded-2xl border bg-card text-card-foreground shadow-sm",a)},r))}));j.displayName="Card";r.forwardRef(((e,t)=>{let{className:a}=e,r=(0,g.A)(e,y);return(0,h.jsx)("div",(0,m.A)({ref:t,className:(0,u.cn)("flex flex-col space-y-1.5 p-6",a)},r))})).displayName="CardHeader";r.forwardRef(((e,t)=>{let{className:a}=e,r=(0,g.A)(e,p);return(0,h.jsx)("h3",(0,m.A)((0,m.A)({ref:t,className:(0,u.cn)("text-lg font-semibold leading-none tracking-tight",a)},r),{},{children:r.children||"Card Title"}))})).displayName="CardTitle";r.forwardRef(((e,t)=>{let{className:a}=e,r=(0,g.A)(e,f);return(0,h.jsx)("p",(0,m.A)({ref:t,className:(0,u.cn)("text-sm text-muted-foreground",a)},r))})).displayName="CardDescription";const N=r.forwardRef(((e,t)=>{let{className:a}=e,r=(0,g.A)(e,v);return(0,h.jsx)("div",(0,m.A)({ref:t,className:(0,u.cn)("p-6 pt-0",a)},r))}));N.displayName="CardContent";r.forwardRef(((e,t)=>{let{className:a}=e,r=(0,g.A)(e,w);return(0,h.jsx)("div",(0,m.A)({ref:t,className:(0,u.cn)("flex items-center p-6 pt-0",a)},r))})).displayName="CardFooter";var b=a(9201);const S=e=>{let{story:t,isHighlighted:a,onClick:r}=e;const n=(0,s.Zp)(),o=e=>{if(!e)return"Untitled Story";if(e.title&&"Untitled Story"!==e.title)return e.title;if(e.content){const t=e.content.split("\n");for(const e of t)if(e.trim().startsWith("**Title:")){const t=e.trim().replace(/\*\*/g,"").replace("Title:","").trim();if(t)return t}}return"Untitled Story"},l=(e=>e?e.imageData&&"string"===typeof e.imageData?e.imageData.startsWith("data:image")?e.imageData:"data:image/png;base64,".concat(e.imageData):e.imageUrl?e.imageUrl:null:null)(t);return(0,h.jsxs)(j,{className:(0,u.cn)("overflow-hidden hover:shadow-md transition-shadow cursor-pointer relative group",a?"ring-2 ring-primary animate-pulse":""),onClick:()=>{r?r(t):n("/story?id=".concat(t.id))},children:[l&&(0,h.jsx)("div",{className:"h-48 w-full overflow-hidden",children:(0,h.jsx)("img",{src:l,alt:o(t),className:"w-full h-full object-cover",onError:e=>{console.error("Image failed to load:",l),e.target.onerror=null,e.target.src='data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><circle cx="8.5" cy="8.5" r="1.5"></circle><polyline points="21 15 16 10 5 21"></polyline></svg>'}})}),(0,h.jsxs)(N,{className:"p-5",children:[(0,h.jsx)("h3",{className:"text-xl font-semibold line-clamp-2 mb-2",children:o(t)}),(0,h.jsx)("div",{className:"flex items-center text-sm text-muted-foreground",children:t.year&&(0,h.jsxs)("div",{className:"flex items-center",children:[(0,h.jsx)(b.A,{className:"h-3.5 w-3.5 mr-1.5"}),"Year ",t.year]})}),!l&&t.content&&(0,h.jsx)("p",{className:"text-muted-foreground line-clamp-3 mt-3",children:t.content.split("\n\n")[0].replace(/\*\*Title:.*?\*\*/g,"")})]})]})},A=["className","type"],C=r.forwardRef(((e,t)=>{let{className:a,type:r="text"}=e,s=(0,g.A)(e,A);return(0,h.jsx)("input",(0,m.A)({type:r,className:(0,u.cn)("flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",a),ref:t},s))}));C.displayName="Input";var k=a(3147),I=a(6479),D=a(2407),T=a(4990);const R=e=>{let{searchQuery:t,yearFilter:a,sortOrder:r,allYears:s,onSearchChange:n,onYearFilterChange:l,onSortOrderChange:i,onClearFilters:c}=e;const d=t||a;return(0,h.jsxs)("div",{className:"mb-6 flex flex-col md:flex-row gap-4",children:[(0,h.jsxs)("div",{className:"relative flex-1",children:[(0,h.jsx)(k.A,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),(0,h.jsx)(C,{type:"text",placeholder:"Search stories...",value:t,onChange:n,className:"pl-9 w-full"}),t&&(0,h.jsx)(o.$,{variant:"ghost",size:"sm",onClick:()=>n({target:{value:""}}),className:"absolute right-1 top-1 h-7 w-7 p-0","aria-label":"Clear search",children:(0,h.jsx)(I.A,{className:"h-4 w-4"})})]}),(0,h.jsxs)("div",{className:"flex items-center gap-2",children:[(0,h.jsxs)("div",{className:"relative",children:[(0,h.jsxs)("select",{value:a,onChange:e=>l(e.target.value),className:"h-9 w-32 rounded-md border border-input bg-background px-3 pr-9 text-sm",children:[(0,h.jsx)("option",{value:"",children:"All Years"}),s.map((e=>(0,h.jsx)("option",{value:e,children:e},e)))]}),(0,h.jsx)(b.A,{className:"absolute right-3 top-2.5 h-4 w-4 pointer-events-none text-muted-foreground"})]}),(0,h.jsxs)(o.$,{variant:"outline",size:"sm",onClick:()=>i("newest"===r?"oldest":"newest"),title:"newest"===r?"Showing newest first":"Showing oldest first",children:["newest"===r?(0,h.jsx)(D.A,{className:"h-4 w-4 mr-1"}):(0,h.jsx)(T.A,{className:"h-4 w-4 mr-1"}),"newest"===r?"Newest":"Oldest"]}),d&&(0,h.jsxs)(o.$,{variant:"ghost",size:"sm",onClick:c,className:"text-muted-foreground hover:text-foreground",children:[(0,h.jsx)(I.A,{className:"h-3.5 w-3.5 mr-1"}),"Clear Filters"]})]})]})};var L=a(903);const P=e=>{let{onCreateNew:t}=e;return(0,h.jsxs)("div",{className:"text-center py-20",children:[(0,h.jsx)(L.A,{className:"h-12 w-12 text-muted-foreground mx-auto mb-4 opacity-25"}),(0,h.jsx)("h3",{className:"text-lg font-medium mb-2",children:"No stories yet"}),(0,h.jsx)("p",{className:"text-muted-foreground mb-6",children:"Generate your first story to get started"}),(0,h.jsxs)(o.$,{onClick:t,children:[(0,h.jsx)(i.A,{className:"h-4 w-4 mr-2"}),"Create Story"]})]})},E=e=>{let{onClearFilters:t}=e;return(0,h.jsxs)("div",{className:"text-center py-20 border rounded-lg",children:[(0,h.jsx)(k.A,{className:"h-12 w-12 text-muted-foreground mx-auto mb-4 opacity-25"}),(0,h.jsx)("h3",{className:"text-lg font-medium mb-2",children:"No matching stories"}),(0,h.jsx)("p",{className:"text-muted-foreground mb-6",children:"Try changing your search or filters"}),(0,h.jsx)(o.$,{variant:"outline",onClick:t,children:"Clear Filters"})]})},O=e=>{let{stories:t,onStorySelect:a,onCreateNew:s,onDeleteStory:n,highlightedStoryId:m,loading:g,error:u,onReload:x}=e;const[y,p]=(0,r.useState)(""),[f,v]=(0,r.useState)(""),[w,j]=(0,r.useState)("newest"),[N,b]=(0,r.useState)([]),A=()=>{p(""),v("")};(0,r.useEffect)((()=>{const e=new Set;null===t||void 0===t||t.forEach((t=>{t.year&&e.add(parseInt(t.year,10))})),b([...e].sort(((e,t)=>e-t)))}),[t]);const C=(0,r.useMemo)((()=>{let e=[...t||[]];if(f&&(e=e.filter((e=>{var t;return e.year===parseInt(f,10)||(null===(t=e.year)||void 0===t?void 0:t.toString())===f}))),y){const t=y.toLowerCase();e=e.filter((e=>{var a,r;return(null===(a=e.title)||void 0===a?void 0:a.toLowerCase().includes(t))||(null===(r=e.content)||void 0===r?void 0:r.toLowerCase().includes(t))}))}return"newest"===w?e.sort(((e,t)=>new Date(t.createdAt)-new Date(e.createdAt))):e.sort(((e,t)=>new Date(e.createdAt)-new Date(t.createdAt))),e}),[t,f,y,w]);return(0,h.jsxs)("div",{className:"container max-w-6xl mx-auto p-6",children:[(0,h.jsxs)("div",{className:"flex items-center justify-between mb-8",children:[(0,h.jsxs)("div",{children:[(0,h.jsx)("h1",{className:"text-3xl font-bold tracking-tight",children:"Your Stories"}),(0,h.jsx)("p",{className:"text-muted-foreground",children:"Collection of your generated speculative fiction"})]}),(0,h.jsxs)(o.$,{onClick:s,className:"flex items-center",children:[(0,h.jsx)(i.A,{className:"h-4 w-4 mr-2"}),"Create New Story"]})]}),g&&!(null!==t&&void 0!==t&&t.length)&&(0,h.jsxs)("div",{className:"my-8",children:[(0,h.jsx)("p",{className:"text-center text-sm text-muted-foreground mb-2",children:"Loading your stories..."}),(0,h.jsx)("div",{className:"w-full bg-muted rounded-full h-2 mb-4 mx-auto max-w-md",children:(0,h.jsx)("div",{className:"bg-primary h-2 rounded-full animate-pulse",style:{width:"60%"}})})]}),u&&(0,h.jsxs)(l.Fc,{className:"mb-6",variant:"destructive",children:[(0,h.jsx)(c.A,{className:"h-4 w-4 mr-2"}),(0,h.jsxs)(l.TN,{className:"flex items-center justify-between w-full",children:[(0,h.jsx)("span",{children:u}),(0,h.jsxs)(o.$,{variant:"outline",size:"sm",onClick:()=>{x&&"function"===typeof x&&x()},className:"ml-4",children:[(0,h.jsx)(d.A,{className:"h-3.5 w-3.5 mr-1.5"}),"Retry"]})]})]}),t&&t.length>0&&(0,h.jsx)(R,{searchQuery:y,yearFilter:f,sortOrder:w,allYears:N,onSearchChange:e=>{p(e.target.value)},onYearFilterChange:v,onSortOrderChange:j,onClearFilters:A}),g||t&&0!==t.length?g||0!==C.length?!g&&(0,h.jsx)("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:C.map((e=>(0,h.jsx)(S,{story:e,isHighlighted:m===e.id,onClick:()=>a(e)},e.id)))}):(0,h.jsx)(E,{onClearFilters:A}):(0,h.jsx)(P,{onCreateNew:s})]})};var F=a(7255),U=a(5107),_=a(9040),B=a(9019),z=a(1052),G=a.n(z),Y=a(1352);const V=e=>{let{story:t,onRegenerateStory:a,onCreateNew:r,loading:n}=e;const l=(0,s.Zp)(),c=t.content?t.content.split("\n\n").filter((e=>e.trim())):[],m=(e=>e?e.imageData&&"string"===typeof e.imageData?e.imageData.startsWith("data:image")?e.imageData:"data:image/png;base64,".concat(e.imageData):e.imageUrl?e.imageUrl:null:null)(t);return(0,h.jsxs)("div",{className:"container max-w-6xl mx-auto h-full flex flex-col",id:"jsx-template",children:[(0,h.jsx)("header",{className:"py-6 border-b",children:(0,h.jsxs)("div",{className:"flex items-center justify-between",children:[(0,h.jsxs)("div",{children:[(0,h.jsx)("h1",{className:"text-4xl font-bold tracking-tight mb-2",children:t.title}),(0,h.jsx)("div",{className:"flex items-center text-muted-foreground",children:(0,h.jsxs)("span",{children:["Year ",t.year]})})]}),(0,h.jsxs)("div",{className:"flex space-x-2",children:[(0,h.jsxs)(o.$,{variant:"outline",size:"sm",onClick:()=>{l("/generating"),a()},disabled:n,children:[(0,h.jsx)(d.A,{className:"h-4 w-4 mr-2 ".concat(n?"animate-spin":"")}),"Regenerate"]}),(0,h.jsxs)(o.$,{variant:"outline",size:"sm",onClick:r,children:[(0,h.jsx)(i.A,{className:"h-4 w-4 mr-2"}),"Create New Story"]})]})]})}),(0,h.jsx)("div",{className:"py-8",children:(0,h.jsxs)("div",{className:"prose prose-lg max-w-3xl mx-auto",children:[m&&(0,h.jsx)("div",{className:"mb-8 not-prose",children:(0,h.jsx)("img",{src:m,alt:t.title,className:"w-full h-auto rounded-lg shadow-md",onError:e=>{console.error("Story image failed to load:",m),e.target.onerror=null,e.target.src='data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="800" height="400" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><circle cx="8.5" cy="8.5" r="1.5"></circle><polyline points="21 15 16 10 5 21"></polyline></svg>'}})}),c.map(((e,t)=>e.includes("**Title:")?null:(0,h.jsx)("p",{className:" text-sm/8 mb-4",children:e},t)))]})}),(0,h.jsx)("footer",{className:"py-6 border-t mt-auto",children:(0,h.jsxs)("div",{className:"flex items-center justify-between max-w-3xl mx-auto",children:[(0,h.jsxs)("div",{className:"flex items-center space-x-4",children:[(0,h.jsxs)(o.$,{variant:"outline",size:"sm",onClick:()=>W({story:{title:t.title,year:t.year,createdAt:t.createdAt},imageSource:m,contentParagraphs:c}),children:[(0,h.jsx)(F.A,{className:"h-4 w-4 mr-2"}),"Download"]}),(0,h.jsxs)(o.$,{variant:"outline",size:"sm",onClick:()=>$({story:{title:t.title,year:t.year,createdAt:t.createdAt},imageSource:m,contentParagraphs:c}),children:[(0,h.jsx)(U.A,{className:"h-4 w-4 mr-2"}),"Print"]}),(0,h.jsxs)(o.$,{variant:"outline",size:"sm",onClick:async()=>{const e={title:t.title,text:"".concat(t.title," - Year ").concat(t.year,"\n\n").concat(t.content.substring(0,100),"..."),url:window.location.href},a=await(async e=>{if(!navigator.share)return console.warn("Web Share API not supported"),!1;try{return await navigator.share(e),!0}catch(t){return console.error("Error sharing:",t),!1}})(e);if(!a){(async e=>{try{return await navigator.clipboard.writeText(e),!0}catch(t){console.error("Failed to copy text: ",t);const a=document.createElement("textarea");a.value=e,a.style.position="fixed",document.body.appendChild(a),a.focus(),a.select();try{const e=document.execCommand("copy");return document.body.removeChild(a),e}catch(t){return console.error("Fallback copy failed: ",t),document.body.removeChild(a),!1}}})("".concat(t.title," - Year ").concat(t.year,"\n\n").concat(t.content)),alert("Text copied to clipboard for sharing")}},children:[(0,h.jsx)(_.A,{className:"h-4 w-4 mr-2"}),"Share"]})]}),(0,h.jsx)("div",{className:"text-sm text-muted-foreground",children:(0,h.jsxs)("div",{className:"flex items-center",children:[(0,h.jsx)(b.A,{className:"h-3.5 w-3.5 mr-1.5"}),(0,h.jsx)("span",{children:(g=t.createdAt,new Date(g).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"}))}),(0,h.jsx)("span",{className:"mx-2",children:"\u2022"}),(0,h.jsx)("span",{className:"text-primary",children:"Speculative Fiction"})]})})]})})]});var g},W=async e=>{let{story:t,imageSource:a,contentParagraphs:r,returnInstance:s=!1}=e;const n=[];for(let c=1;c<r.length;c+=10)n.push(r.slice(c,c+10));const o=new B.Ay("p","mm","a4"),l=o.internal.pageSize.getWidth();for(let c=0;c<n.length;c++){const e=document.createElement("div");e.id="pdf-render-container-".concat(c),e.style.position="absolute",e.style.left="-9999px",e.style.top="0",e.style.width="794px",e.style.padding="15mm",e.style.backgroundColor="#fff",e.style.columnCount="2",e.style.columnGap="40px",e.style.fontSize="10px",e.style.lineHeight="1.8",document.body.appendChild(e);const r=(0,h.jsxs)("div",{children:[0===c&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("h1",{className:"text-3xl text-gray-900 font-bold mb-2 tracking-tight ",children:t.title}),(0,h.jsxs)("p",{className:"text-gray-500 mb-4 text-base ",children:["Year ",t.year]}),a&&(0,h.jsx)("div",{className:"mb-5 break-inside-avoid",children:(0,h.jsx)("img",{src:a,alt:t.title,className:"w-full mx-auto rounded-sm shadow-md"})})]}),n[c].map(((e,t)=>(0,h.jsx)("p",{className:"mb-5 text-[13px] text-gray-900 font-worksans leading-relaxed",children:e},t))),(0,h.jsxs)("div",{className:"flex items-center text-[10px] text-gray-700 space-x-2 text-sm border-t mb-2",children:[(0,h.jsx)("span",{children:"Created on"}),(0,h.jsx)("span",{children:J(t.createdAt)}),(0,h.jsx)("span",{children:"|"}),(0,h.jsx)("span",{children:"Anantabhavi"})]})]}),s=Y.createRoot(e);s.render(r),await new Promise((e=>setTimeout(e,500)));const i=await G()(e,{scale:2,useCORS:!0,scrollY:-window.scrollY,backgroundColor:"#fff",windowWidth:e.scrollWidth}),d=i.toDataURL("image/jpeg",1),m=l,g=i.height*m/i.width;c>0&&o.addPage(),o.addImage(d,"JPEG",0,0,m,g),s.unmount(),document.body.removeChild(e)}const i=t.title.replace(/\s+/g,"_").toLowerCase();if(s)return o;o.save("".concat(i,".pdf"))},$=async e=>{let{story:t,imageSource:a,contentParagraphs:r}=e;const s=(await W({story:t,imageSource:a,contentParagraphs:r,returnInstance:!0})).output("blob"),n=URL.createObjectURL(s),o=window.open(n);o.onload=function(){o.focus(),o.print()}},J=e=>new Date(e).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"}),M=e=>{let{loading:t,error:a,showRecoveryBanner:s,onGenerationComplete:n}=e;const[o,i]=(0,r.useState)(0);return(0,r.useEffect)((()=>{let e=null;return t?e=setInterval((()=>{i((e=>Math.min(e+2,95)))}),500):o<100&&(i(100),setTimeout((()=>{n&&n()}),500)),()=>{e&&clearInterval(e)}}),[t,o,n]),(0,h.jsx)("div",{className:"container max-w-6xl mx-auto h-full",children:(0,h.jsx)("div",{className:"h-full flex items-center justify-center",children:(0,h.jsxs)("div",{className:"text-center",children:[(0,h.jsx)(d.A,{className:"h-10 w-10 text-primary animate-spin mx-auto mb-4"}),(0,h.jsx)("h3",{className:"text-lg font-medium mb-2",children:"Generating your story"}),(0,h.jsx)("p",{className:"text-muted-foreground mb-4",children:s?"Resuming generation after navigation...":"This may take a few moments..."}),(0,h.jsx)("div",{className:"w-64 bg-muted rounded-full h-2.5 mb-4 mx-auto",children:(0,h.jsx)("div",{className:"bg-primary h-2.5 rounded-full transition-all duration-500",style:{width:"".concat(o,"%")}})}),(0,h.jsxs)("div",{className:"text-sm text-amber-600 dark:text-amber-400 mt-6 mb-4 max-w-md mx-auto p-3 border border-amber-200 dark:border-amber-900 rounded-md bg-amber-50 dark:bg-amber-950/30",children:[(0,h.jsx)(c.A,{className:"h-4 w-4 inline-block mr-2"}),"Please stay on this page while the content is generating. This usually takes around 30\u201345 seconds."]}),a&&(0,h.jsxs)(l.Fc,{className:"mt-4",variant:"destructive",children:[(0,h.jsx)(c.A,{className:"h-4 w-4 mr-2"}),(0,h.jsx)(l.TN,{children:a})]})]})})})};var H=a(8108);const q=e=>{let{activeStory:t,generatedContent:a,onBackToLibrary:r,storyTitle:s}=e;return(0,h.jsx)("nav",{className:"flex mb-4 px-6 pt-6","aria-label":"Breadcrumb",children:(0,h.jsx)("ol",{className:"inline-flex items-center space-x-1 md:space-x-3",children:t||a?(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("li",{className:"inline-flex items-center",children:(0,h.jsxs)(o.$,{variant:"link",className:"inline-flex items-center text-sm font-medium text-muted-foreground hover:text-foreground p-0 h-auto",onClick:r,children:[(0,h.jsx)(L.A,{className:"w-4 h-4 mr-2"}),"Story Library"]})}),(0,h.jsx)("li",{"aria-current":"page",children:(0,h.jsxs)("div",{className:"flex items-center",children:[(0,h.jsx)(H.A,{className:"w-4 h-4 text-muted-foreground"}),(0,h.jsx)("span",{className:"ml-1 text-sm font-medium text-foreground md:ml-2",children:(null===t||void 0===t?void 0:t.title)||s||"View Story"})]})})]}):(0,h.jsx)("li",{className:"inline-flex items-center",children:(0,h.jsxs)("div",{className:"flex items-center",children:[(0,h.jsx)(L.A,{className:"w-4 h-4 mr-2 text-primary"}),(0,h.jsx)("span",{className:"text-sm font-medium",children:"Story Library"})]})})})})};var K=a(9294),Q=a(8815);const X=e=>{let{loading:t,error:a,showRecoveryBanner:r,onGenerationComplete:s,handleBackToLibrary:n}=e;return(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)(q,{activeStory:null,onBackToLibrary:n,storyTitle:"Generating..."}),(0,h.jsx)(M,{loading:t,error:a,showRecoveryBanner:r,onGenerationComplete:s})]})},Z=e=>{let{activeStory:t,generatedContent:a,storyTitle:r,handleBackToLibrary:s,regenerateStory:n,handleCreateNew:o,loading:l}=e;return(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)(q,{activeStory:t,generatedContent:a,onBackToLibrary:s,storyTitle:(null===t||void 0===t?void 0:t.title)||r}),(0,h.jsx)(V,{story:t,onBackToLibrary:s,onRegenerateStory:()=>n(t),onCreateNew:o,loading:l})]})},ee=e=>{let{stories:t,setActiveStory:a,handleCreateNew:r,highlightedStoryId:s,loading:n,error:o,storyTitle:l}=e;return(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)(q,{onBackToLibrary:()=>{},storyTitle:l}),(0,h.jsx)(O,{stories:t,onStorySelect:a,onCreateNew:r,highlightedStoryId:s,loading:n,error:o})]})},te=e=>{let{setGeneratedContent:t,generatedContent:a,selectedParameters:o,setSelectedParameters:i,generationInProgress:g,setGenerationInProgress:u,viewMode:x=null}=e;const y=(0,s.Zp)(),p=(0,s.zy)(),[f]=(0,n.ok)(),v=f.get("id"),{loading:w,error:j,stories:N,activeStory:b,setActiveStory:S,storyTitle:A,showRecoveryBanner:C,highlightedStoryId:k,regenerateStory:I}=((e,t,a)=>{const[s,n]=(0,r.useState)(!1),[o,l]=(0,r.useState)(null),[i,c]=(0,r.useState)(null),[d,g]=(0,r.useState)([]),[u,h]=(0,r.useState)(null),[x,y]=(0,r.useState)("Untitled Story"),[p,f]=(0,r.useState)((0,Q.A)()),[v]=(0,r.useState)(null),[w,j]=(0,r.useState)(!1),[N,b]=(0,r.useState)(null),S=(0,r.useRef)(!1),A=(0,r.useCallback)((async()=>{if(!s){n(!0),l(null);try{const t=await(0,K.B8)();if(!t.success||!t.data)throw new Error(t.error||"Failed to load stories");console.log("Loaded ".concat(t.data.length," stories from API")),g(t.data),l(null);try{const e=t.data.slice(0,5).map((e=>({id:e.id,title:e.title,createdAt:e.createdAt,year:e.year,parameterValues:e.parameterValues,isMinimal:!0})));localStorage.setItem("specgen-cached-stories",JSON.stringify(e)),localStorage.setItem("specgen-cached-timestamp",Date.now().toString())}catch(e){console.warn("Storage error:",e.message),localStorage.removeItem("specgen-history")}}catch(t){console.error("Error fetching stories:",t);try{const e=localStorage.getItem("specgen-cached-stories");if(e){const t=JSON.parse(e);if(t&&t.length>0){console.log("Using cached story data");const e=t.map((e=>e.isMinimal?(0,m.A)((0,m.A)({},e),{},{content:"Content unavailable in offline mode. Please reconnect to view full content.",imageData:null}):e));return g(e),l(null),void n(!1)}}}catch(a){console.error("Cache error:",a)}l("Failed to load story library. Storage quota may be exceeded.")}finally{n(!1)}}}),[s]);(0,r.useEffect)((()=>{S.current||(A(),S.current=!0)}),[A]);const C=(0,r.useCallback)((async function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;if(s)return null;let o=null;l(null),c(null),b(null);const i=null!==r?r:p,m=t||e;let u={};if(Array.isArray(m)){if(m.filter((e=>void 0===e.value||null===e.value)).length>0)return l("Please set values for all selected parameters."),null;m.forEach((e=>{u[e.categoryId]||(u[e.categoryId]={}),u[e.categoryId][e.id]=e.value}))}else{if("object"!==typeof m||null===m)return l("Invalid parameter format"),null;u=m}try{n(!0);const e=await(0,K.lX)(u,Object.keys(u),"combined",i,null);if(e.success){var f;if(e.content){c(e.content);let t="Untitled Story";const a=e.content.split("\n");for(const e of a)if(e.trim().startsWith("**Title:")){t=e.trim().replace(/\*\*/g,"").replace("Title:","").trim();break}y(e.title||t)}const t=e.generatedStory||{id:"story-".concat(Date.now()),title:e.title||x||"Untitled Story",createdAt:(new Date).toISOString(),content:e.content,imageData:null!==(f=e.imageData)&&void 0!==f&&f.startsWith("data:image")?e.imageData:e.imageData?"data:image/png;base64,".concat(e.imageData):null,parameterValues:u,metadata:e.metadata,year:e.year||i};o=t.id,b(o),h(t);try{const e=[t,...d];g(e);const a=e.slice(0,5).map((e=>({id:e.id,title:e.title,createdAt:e.createdAt,year:e.year,parameterValues:e.parameterValues,isMinimal:!0})));localStorage.setItem("specgen-cached-stories",JSON.stringify(a)),localStorage.setItem("specgen-cached-timestamp",Date.now().toString())}catch(v){console.warn("Storage error during cache update:",v.message)}}else l(e.error||"Generation failed")}catch(w){console.error("Generation error:",w),l(w.message||"Failed to generate content")}finally{return n(!1),a(!1),sessionStorage.removeItem("specgen-auto-generate"),sessionStorage.removeItem("specgen-generating"),o}}),[p,x,e,a,s,d]),k=(0,r.useCallback)((async e=>{if(!e||s)return null;try{n(!0),a(!0);const s=e.parameterValues,o=e.year||p;f(o),sessionStorage.setItem("specgen-regenerating-story-id",e.id);const i=await(0,K.lX)(s,Object.keys(s),"combined",o,e.title);if(i.success){var t;const a=(0,m.A)((0,m.A)({},e),{},{content:i.content,title:i.title||e.title,imageData:null!==(t=i.imageData)&&void 0!==t&&t.startsWith("data:image")?i.imageData:i.imageData?"data:image/png;base64,".concat(i.imageData):null,updatedAt:(new Date).toISOString()});h(a);const s=d.map((t=>t.id===e.id?a:t));g(s);try{const e=s.slice(0,5).map((e=>({id:e.id,title:e.title,createdAt:e.createdAt,year:e.year,parameterValues:e.parameterValues,isMinimal:!0})));localStorage.setItem("specgen-cached-stories",JSON.stringify(e)),localStorage.setItem("specgen-cached-timestamp",Date.now().toString())}catch(r){console.warn("Storage error during regeneration:",r.message)}return a.id}return l(i.error||"Regeneration failed"),null}catch(o){return console.error("Regeneration error:",o),l(o.message||"Failed to regenerate content"),null}finally{n(!1),a(!1)}}),[s,d,p,a]);return(0,r.useEffect)((()=>{if("/generating"!==window.location.pathname)return;const e=sessionStorage.getItem("specgen-auto-generate"),t=sessionStorage.getItem("specgen-generating");if("true"===e&&!t&&!s){sessionStorage.setItem("specgen-generating","true");try{const e=sessionStorage.getItem("specgen-parameters");if(e){const t=JSON.parse(e),r=sessionStorage.getItem("specgen-story-year"),s=r?parseInt(r,10):p;r&&f(parseInt(r,10)),(t.length>0||"object"===typeof t&&Object.keys(t).length>0)&&(j(!0),a(!0),setTimeout((()=>{C(t,s)}),50))}}catch(o){console.error("Auto-generation error:",o),sessionStorage.removeItem("specgen-parameters"),sessionStorage.removeItem("specgen-auto-generate"),sessionStorage.removeItem("specgen-generating"),a(!1)}}}),[C,s,a,p]),{loading:s,error:o,generatedContent:i,stories:d,setStories:g,activeStory:u,setActiveStory:h,storyTitle:x,storyYear:p,setStoryYear:f,highlightedStoryId:v,showRecoveryBanner:w,lastGeneratedStoryId:N,handleGeneration:C,regenerateStory:k,loadStories:A}})(o,0,u),D=()=>{i([]),y("/parameters")},T=()=>{S(null),t(null),y("/library",{replace:!0})};(0,r.useEffect)((()=>{N.length>0&&(async()=>{if("story"===x||"/story"===p.pathname){if(v&&!b){const e=N.find((e=>e.id===v));e&&S(e)}}else"/library"===p.pathname&&b&&S(null)})()}),[x,p.pathname,v,N,b,S]),(0,r.useEffect)((()=>{if(!w&&b&&("/generating"===p.pathname||"generating"===x)){const e=sessionStorage.getItem("specgen-regenerating-story-id");e&&e===b.id&&sessionStorage.removeItem("specgen-regenerating-story-id"),y("/story?id=".concat(b.id))}}),[w,b,p.pathname,y,x]);const R=()=>{u(!1)},L="generating"===x||g||"/generating"===p.pathname?"generating":"story"===x||"/story"===p.pathname||b?"story":"library";return"generating"===L?(0,h.jsx)("div",{className:"bg-card rounded-md h-full overflow-auto",children:(0,h.jsx)(X,{loading:w,error:j,showRecoveryBanner:C,onGenerationComplete:R,handleBackToLibrary:T})}):"story"===L?!b&&w?(0,h.jsxs)("div",{className:"bg-card rounded-md h-full overflow-auto",children:[(0,h.jsx)(q,{onBackToLibrary:T,storyTitle:"Loading story..."}),(0,h.jsx)("div",{className:"flex items-center justify-center h-[calc(100%-4rem)]",children:(0,h.jsxs)("div",{className:"text-center",children:[(0,h.jsx)(d.A,{className:"h-10 w-10 text-primary animate-spin mx-auto mb-4"}),(0,h.jsx)("h3",{className:"text-lg font-medium mb-2",children:"Loading story"}),(0,h.jsx)("p",{className:"text-muted-foreground",children:"Please wait..."})]})})]}):b||w?(0,h.jsx)("div",{className:"bg-card rounded-md h-full overflow-auto",children:(0,h.jsx)(Z,{activeStory:b,generatedContent:a,storyTitle:A,handleBackToLibrary:T,regenerateStory:I,handleCreateNew:D,loading:w})}):(0,h.jsxs)("div",{className:"bg-card rounded-md h-full overflow-auto",children:[(0,h.jsx)(q,{onBackToLibrary:T,storyTitle:"Error"}),(0,h.jsx)("div",{className:"flex items-center justify-center h-[calc(100%-4rem)]",children:(0,h.jsxs)("div",{className:"text-center max-w-md",children:[(0,h.jsx)(c.A,{className:"h-10 w-10 text-destructive mx-auto mb-4"}),(0,h.jsx)("h3",{className:"text-lg font-medium mb-2",children:"Story not found"}),(0,h.jsx)(l.Fc,{variant:"destructive",className:"mt-4",children:(0,h.jsx)(l.TN,{children:j||"Could not find story with ID: ".concat(v||"unknown")})}),(0,h.jsx)("div",{className:"mt-6",children:(0,h.jsx)("button",{onClick:T,className:"text-primary hover:underline",children:"Return to Library"})})]})})]}):(0,h.jsx)("div",{className:"bg-card rounded-md h-full overflow-auto",children:(0,h.jsx)(ee,{stories:N,setActiveStory:e=>{S(e),y("/story?id=".concat(e.id))},handleCreateNew:D,highlightedStoryId:k,loading:w,error:j,storyTitle:"Story Library"})})}}}]);