Files
igny8/frontend/dist/assets/js/pages-writer-BGmP8pSS.js
IGNY8 VPS (Salman) ca5bf13c74 buid node modules
2025-11-13 14:02:26 +00:00

117 lines
76 KiB
JavaScript

const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/js/vendor-charts-BCGhWx_0.js","assets/js/vendor-react-core-DRQGgXXF.js","assets/js/vendor-other-DTCyBslD.js","assets/css/vendor-other-BsM4JrO0.css"])))=>i.map(i=>d[i]);
import{_ as st}from"./marketing-marketingapp.tsx-D0Y0OkFz.js";import{r as a,j as e}from"./vendor-react-core-DRQGgXXF.js";import{b as ze,L as at,c as rt}from"./vendor-react-router-P1WQ4rUN.js";import{P as Ne,l as Le,e as be,v as We,g as nt,b as lt,w as ot,k as Ge,s as it,x as qe,p as Ae,y as dt,n as Fe,f as Pe,o as ct,L as ut,B as Re}from"./page-authpages-BaiNliVr.js";import{a as gt,b as Ee,E as ve,C as pe,m as He,a0 as Ve,a1 as Qe,u as _e,a2 as mt,a3 as pt,a4 as xt,a5 as ht,a6 as ft,k as bt,a7 as yt,a8 as kt,a9 as jt,aa as vt,n as wt,ab as Nt,ac as _t,ad as St,ae as Ct}from"./page-dashboard-CuOyqq-s.js";import{W as It,P as Be,u as Ye,a as Je,b as Ke,T as $e,c as Xe,F as Tt,S as Mt}from"./pages-planner-dv4ygB5K.js";import{P as Se}from"./page-reference-wEKoPZ-s.js";import{c as Ft}from"./page-content.config.tsx-Bu5_tL3S.js";import{c as Pt}from"./page-images.config.tsx-D2qUfhK2.js";import{M as Oe}from"./page-components.tsx-4vErPdxY.js";import{c as Et}from"./page-tasks.config.tsx-DbwIlrdw.js";const we=a.lazy(()=>st(()=>import("./vendor-charts-BCGhWx_0.js").then(t=>t.r),__vite__mapDeps([0,1,2,3])).then(t=>({default:t.default})));function $t(){const t=ze(),{activeSite:c}=gt(),{activeSector:d}=Ee(),[s,_]=a.useState(null),[k,S]=a.useState(!0),[I,P]=a.useState(new Date),[g,D]=a.useState({tasks:0,content:0,images:0}),E=async()=>{try{S(!0);const[b,j,u]=await Promise.all([He({page_size:1e3,sector_id:d==null?void 0:d.id}),Ve({page_size:1e3,sector_id:d==null?void 0:d.id}),Qe({page_size:1e3,sector_id:d==null?void 0:d.id})]),M=b.results||[],V={};let n=0,p=0;M.forEach(h=>{V[h.status||"draft"]=(V[h.status||"draft"]||0)+1,h.word_count&&(n+=h.word_count,p++)});const l=M.filter(h=>h.status==="draft"||h.status==="pending").length,m=M.filter(h=>h.status==="in_progress"||h.status==="review").length,i=M.filter(h=>h.status==="completed"||h.status==="published").length,w=p>0?Math.round(n/p):0,N=j.results||[],A={},y={};let v=0,O=0;N.forEach(h=>{A[h.status||"draft"]=(A[h.status||"draft"]||0)+1,h.word_count&&(v+=h.word_count,O++)});const G=N.filter(h=>h.status==="draft").length,ee=N.filter(h=>h.status==="review").length,re=N.filter(h=>h.status==="published").length,he=O>0?Math.round(v/O):0,te=u.results||[],ue={},F={};te.forEach(h=>{ue[h.status||"pending"]=(ue[h.status||"pending"]||0)+1,h.image_type&&(F[h.image_type]=(F[h.image_type]||0)+1)});const ce=te.filter(h=>h.status==="generated"&&h.image_url).length,ge=te.filter(h=>h.status==="pending"||h.status==="draft"||!h.image_url).length,xe=te.filter(h=>h.status==="failed"||h.status==="error").length,se=new Date,me=new Date(se.getTime()-7*24*60*60*1e3),de=new Date(se.getTime()-30*24*60*60*1e3),X=N.filter(h=>h.generated_at?new Date(h.generated_at)>=me:!1).length,q=N.filter(h=>h.generated_at?new Date(h.generated_at)>=de:!1).length,fe=N.length>0?Math.round(re/N.length*100):0;s&&D({tasks:M.length-s.tasks.total,content:N.length-s.content.total,images:te.length-s.images.total}),_({tasks:{total:M.length,byStatus:V,pending:l,inProgress:m,completed:i,avgWordCount:w,totalWordCount:n},content:{total:N.length,drafts:G,review:ee,published:re,totalWordCount:v,avgWordCount:he,byContentType:y},images:{total:te.length,generated:ce,pending:ge,failed:xe,byType:F},workflow:{tasksCreated:M.length>0,contentGenerated:N.length>0,imagesGenerated:ce>0,readyToPublish:re>0},productivity:{contentThisWeek:X,contentThisMonth:q,avgGenerationTime:0,publishRate:fe}}),P(new Date)}catch(b){console.error("Error fetching dashboard data:",b)}finally{S(!1)}};a.useEffect(()=>{E();const b=setInterval(E,3e4);return()=>clearInterval(b)},[d==null?void 0:d.id,c==null?void 0:c.id]);const z=a.useMemo(()=>{if(!s)return null;const b={chart:{type:"donut",fontFamily:"Outfit, sans-serif",toolbar:{show:!1}},labels:Object.keys(s.tasks.byStatus).filter(u=>s.tasks.byStatus[u]>0),colors:["#465FFF","#F59E0B","#10B981","#EF4444","#8B5CF6"],legend:{position:"bottom",fontFamily:"Outfit",show:!0},dataLabels:{enabled:!1},tooltip:{enabled:!0,y:{formatter:(u,{seriesIndex:M,w:V})=>`${V.globals.labels[M]||""}: ${u}`}},plotOptions:{pie:{donut:{size:"70%",labels:{show:!0,name:{show:!1},value:{show:!0,fontSize:"24px",fontWeight:700,color:"#465FFF",fontFamily:"Outfit",formatter:()=>{const u=Object.values(s.tasks.byStatus).reduce((M,V)=>M+V,0);return u>0?u.toString():"0"}},total:{show:!1}}}}}},j=Object.keys(s.tasks.byStatus).filter(u=>s.tasks.byStatus[u]>0).map(u=>s.tasks.byStatus[u]);return{options:b,series:j}},[s]),x=a.useMemo(()=>{if(!s)return null;const b={chart:{type:"bar",fontFamily:"Outfit, sans-serif",toolbar:{show:!1},height:250},colors:["#465FFF","#F59E0B","#10B981"],plotOptions:{bar:{horizontal:!1,columnWidth:"55%",borderRadius:5}},dataLabels:{enabled:!0},xaxis:{categories:["Drafts","In Review","Published"],labels:{style:{fontFamily:"Outfit"}}},yaxis:{labels:{style:{fontFamily:"Outfit"}}},grid:{strokeDashArray:4}},j=[{name:"Content",data:[s.content.drafts,s.content.review,s.content.published]}];return{options:b,series:j}},[s]),Q=a.useMemo(()=>{if(!s||Object.keys(s.images.byType).length===0)return null;const b={chart:{type:"bar",fontFamily:"Outfit, sans-serif",toolbar:{show:!1},height:250},colors:["#10B981"],plotOptions:{bar:{horizontal:!0,borderRadius:5}},dataLabels:{enabled:!0},xaxis:{categories:Object.keys(s.images.byType),labels:{style:{fontFamily:"Outfit",fontSize:"12px"}}},yaxis:{labels:{style:{fontFamily:"Outfit"}}}},j=[{name:"Images",data:Object.values(s.images.byType)}];return{options:b,series:j}},[s]),W=a.useMemo(()=>{if(!s)return null;const b={chart:{type:"area",fontFamily:"Outfit, sans-serif",toolbar:{show:!1},height:200},colors:["#465FFF"],stroke:{curve:"smooth",width:2},fill:{type:"gradient",gradient:{opacityFrom:.6,opacityTo:.1}},xaxis:{categories:["Week","Month"],labels:{style:{fontFamily:"Outfit"}}},yaxis:{labels:{style:{fontFamily:"Outfit"}}},grid:{strokeDashArray:4},dataLabels:{enabled:!0}},j=[{name:"Content Created",data:[s.productivity.contentThisWeek,s.productivity.contentThisMonth]}];return{options:b,series:j}},[s]);if(k&&!s)return e.jsxs(e.Fragment,{children:[e.jsx(Ne,{title:"Writer Dashboard - IGNY8",description:"Content creation overview"}),e.jsx("div",{className:"flex items-center justify-center h-96",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"inline-block animate-spin rounded-full h-12 w-12 border-4 border-brand-500 border-t-transparent"}),e.jsx("p",{className:"mt-4 text-gray-600 dark:text-gray-400",children:"Loading dashboard data..."})]})})]});if(!s&&!k)return e.jsxs(e.Fragment,{children:[e.jsx(Ne,{title:"Writer Dashboard - IGNY8",description:"Content creation overview"}),e.jsx("div",{className:"text-center py-12",children:e.jsx("p",{className:"text-gray-600 dark:text-gray-400",children:d?"No data available for the selected sector.":"No data available. Select a sector or wait for data to load."})})]});if(!s)return null;const J=[{number:1,title:"Create Tasks",status:s.workflow.tasksCreated?"completed":"pending",count:s.tasks.total,path:"/writer/tasks"},{number:2,title:"Generate Content",status:s.workflow.contentGenerated?"completed":"pending",count:s.content.total,path:"/writer/content"},{number:3,title:"Generate Images",status:s.workflow.imagesGenerated?"completed":"pending",count:s.images.generated,path:"/writer/images"},{number:4,title:"Publish",status:s.workflow.readyToPublish?"completed":"pending",count:s.content.published,path:"/writer/published"}],H=s.tasks.total>0?Math.round(s.tasks.completed/s.tasks.total*100):0,Z=[...s.tasks.pending>0?[{text:`${s.tasks.pending} tasks pending content generation`,action:"Generate Content",path:"/writer/tasks"}]:[],...s.content.drafts>0?[{text:`${s.content.drafts} drafts ready for review`,action:"Review Content",path:"/writer/content"}]:[],...s.images.pending>0?[{text:`${s.images.pending} images pending generation`,action:"Generate Images",path:"/writer/images"}]:[],...s.content.review>0?[{text:`${s.content.review} content pieces ready to publish`,action:"Publish Content",path:"/writer/published"}]:[]];return e.jsxs(e.Fragment,{children:[e.jsx(Ne,{title:"Writer Dashboard - IGNY8",description:"Content creation overview"}),e.jsxs("div",{className:"space-y-5 sm:space-y-6",children:[e.jsx(Se,{title:"Writer Dashboard",lastUpdated:I,showRefresh:!0,onRefresh:E,badge:{icon:e.jsx(Le,{}),color:"blue"}}),e.jsx("div",{className:"rounded-2xl border border-gray-200 bg-gradient-to-br from-brand-50 to-white dark:from-brand-500/10 dark:to-gray-800/50 dark:border-gray-800 p-6 md:p-8",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-gray-600 dark:text-gray-400",children:"Content Creation Progress"}),e.jsx("h3",{className:"mt-2 text-3xl font-bold text-gray-800 dark:text-white/90",children:s.content.published>0?e.jsxs(e.Fragment,{children:[s.content.published," Content Pieces Published"]}):s.content.review>0?e.jsxs(e.Fragment,{children:[s.content.review," Pieces Ready to Publish"]}):s.content.drafts>0?e.jsxs(e.Fragment,{children:[s.content.drafts," Drafts Ready for Review"]}):s.tasks.total>0?e.jsxs(e.Fragment,{children:[s.tasks.total," Tasks Created"]}):e.jsx(e.Fragment,{children:"Ready to Create Content"})}),e.jsxs("p",{className:"mt-2 text-sm text-gray-500 dark:text-gray-400",children:[s.tasks.total," tasks • ",s.content.total," content pieces • ",s.images.generated," images generated"]})]}),e.jsxs("div",{className:"hidden md:flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsxs("div",{className:"text-2xl font-bold text-brand-500",children:[H,"%"]}),e.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Complete"})]}),e.jsxs("div",{className:"text-center",children:[e.jsxs("div",{className:"text-2xl font-bold text-success-500",children:[s.productivity.publishRate,"%"]}),e.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Published"})]}),e.jsxs("div",{className:"text-center",children:[e.jsxs("div",{className:"text-2xl font-bold text-warning-500",children:[s.images.generated>0?Math.round(s.images.generated/s.images.total*100):0,"%"]}),e.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Images"})]})]})]})}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-4 md:gap-6",children:[e.jsx(ve,{title:"Total Tasks",value:s.tasks.total,subtitle:`${s.tasks.completed} completed • ${s.tasks.pending} pending`,trend:g.tasks,icon:e.jsx(be,{className:"size-6"}),accentColor:"blue",href:"/writer/tasks",details:[{label:"Total Tasks",value:s.tasks.total},{label:"Completed",value:s.tasks.completed},{label:"Pending",value:s.tasks.pending},{label:"In Progress",value:s.tasks.inProgress},{label:"Avg Word Count",value:s.tasks.avgWordCount}]}),e.jsx(ve,{title:"Content Pieces",value:s.content.total,subtitle:`${s.content.published} published • ${s.content.drafts} drafts`,trend:g.content,icon:e.jsx(Le,{className:"size-6"}),accentColor:"green",href:"/writer/content",details:[{label:"Total Content",value:s.content.total},{label:"Published",value:s.content.published},{label:"In Review",value:s.content.review},{label:"Drafts",value:s.content.drafts},{label:"Avg Word Count",value:s.content.avgWordCount.toLocaleString()}]}),e.jsx(ve,{title:"Images Generated",value:s.images.generated,subtitle:`${s.images.total} total • ${s.images.pending} pending`,trend:g.images,icon:e.jsx(We,{className:"size-6"}),accentColor:"orange",href:"/writer/images",details:[{label:"Generated",value:s.images.generated},{label:"Total Images",value:s.images.total},{label:"Pending",value:s.images.pending},{label:"Failed",value:s.images.failed}]}),e.jsx(ve,{title:"Publish Rate",value:`${s.productivity.publishRate}%`,subtitle:`${s.content.published} of ${s.content.total} published`,icon:e.jsx(nt,{className:"size-6"}),accentColor:"purple",href:"/writer/published",details:[{label:"Publish Rate",value:`${s.productivity.publishRate}%`},{label:"Published",value:s.content.published},{label:"Total Content",value:s.content.total},{label:"This Week",value:s.productivity.contentThisWeek},{label:"This Month",value:s.productivity.contentThisMonth}]})]}),e.jsx(pe,{title:"Writer Workflow Pipeline",desc:"Track your content creation progress through each stage",children:e.jsx(It,{steps:J.map(b=>({number:b.number,title:b.title,status:b.status==="completed"?"completed":b.status==="in_progress"?"in_progress":"pending",count:b.count||0,path:b.path,description:b.title,details:b.status==="completed"?`${b.title} completed with ${b.count} items`:b.status==="pending"?`${b.title} pending - ${b.count} items ready`:`${b.title} in progress`})),onStepClick:b=>{t(b.path)},showConnections:!0})}),e.jsxs("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-3",children:[e.jsx(pe,{title:"Productivity Metrics",desc:"Content creation performance",className:"lg:col-span-1",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:"Task Completion"}),e.jsxs("span",{className:"text-sm font-semibold text-gray-800 dark:text-white/90",children:[H,"%"]})]}),e.jsx(Be,{value:H,color:"primary",size:"md"}),e.jsxs("p",{className:"mt-1 text-xs text-gray-500 dark:text-gray-400",children:[s.tasks.completed," of ",s.tasks.total," tasks completed"]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:"Publish Rate"}),e.jsxs("span",{className:"text-sm font-semibold text-gray-800 dark:text-white/90",children:[s.productivity.publishRate,"%"]})]}),e.jsx(Be,{value:s.productivity.publishRate,color:"success",size:"md"}),e.jsxs("p",{className:"mt-1 text-xs text-gray-500 dark:text-gray-400",children:[s.content.published," of ",s.content.total," content published"]})]}),e.jsx("div",{className:"pt-4 border-t border-gray-200 dark:border-gray-800",children:e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mb-1",children:"This Week"}),e.jsx("p",{className:"text-lg font-bold text-gray-800 dark:text-white/90",children:s.productivity.contentThisWeek})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mb-1",children:"This Month"}),e.jsx("p",{className:"text-lg font-bold text-gray-800 dark:text-white/90",children:s.productivity.contentThisMonth})]})]})}),e.jsx("div",{className:"pt-4 border-t border-gray-200 dark:border-gray-800",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mb-1",children:"Avg Word Count"}),e.jsx("p",{className:"text-lg font-bold text-gray-800 dark:text-white/90",children:s.content.avgWordCount.toLocaleString()}),e.jsxs("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1",children:[s.content.totalWordCount.toLocaleString()," total words"]})]})})]})}),x&&e.jsx(pe,{title:"Content by Status",desc:"Distribution across workflow stages",className:"lg:col-span-2",children:e.jsx(a.Suspense,{fallback:e.jsx("div",{className:"flex items-center justify-center h-[300px]",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-4 border-brand-500 border-t-transparent"})}),children:e.jsx(we,{options:x.options,series:x.series,type:"bar",height:300})})})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2",children:[z&&e.jsx(pe,{title:"Tasks by Status",desc:"Task distribution across statuses",children:e.jsx(a.Suspense,{fallback:e.jsx("div",{className:"flex items-center justify-center h-[300px]",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-4 border-brand-500 border-t-transparent"})}),children:e.jsx(we,{options:z.options,series:z.series,type:"donut",height:300})})}),Q?e.jsx(pe,{title:"Images by Type",desc:"Image generation breakdown",children:e.jsx(a.Suspense,{fallback:e.jsx("div",{className:"flex items-center justify-center h-[300px]",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-4 border-brand-500 border-t-transparent"})}),children:e.jsx(we,{options:Q.options,series:Q.series,type:"bar",height:300})})}):e.jsx(pe,{title:"Images Overview",desc:"Image generation status",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg bg-gray-50 dark:bg-gray-900/50",children:[e.jsx("span",{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:"Generated"}),e.jsx("span",{className:"text-lg font-bold text-success-500",children:s.images.generated})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg bg-gray-50 dark:bg-gray-900/50",children:[e.jsx("span",{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:"Pending"}),e.jsx("span",{className:"text-lg font-bold text-warning-500",children:s.images.pending})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg bg-gray-50 dark:bg-gray-900/50",children:[e.jsx("span",{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:"Failed"}),e.jsx("span",{className:"text-lg font-bold text-error-500",children:s.images.failed})]})]})})]}),W&&e.jsx(pe,{title:"Content Creation Trend",desc:"Content created this week and month",children:e.jsx(a.Suspense,{fallback:e.jsx("div",{className:"flex items-center justify-center h-[200px]",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-4 border-brand-500 border-t-transparent"})}),children:e.jsx(we,{options:W.options,series:W.series,type:"area",height:200})})}),Z.length>0&&e.jsx(pe,{title:"Next Actions",desc:"Actionable items requiring attention",children:e.jsx("div",{className:"space-y-3",children:Z.map((b,j)=>e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg bg-gradient-to-r from-gray-50 to-white dark:from-gray-900/50 dark:to-gray-800/50 border border-gray-200 dark:border-gray-800 hover:border-brand-300 dark:hover:border-brand-500/30 transition-all group",children:[e.jsx("span",{className:"text-sm font-medium text-gray-700 dark:text-gray-300",children:b.text}),e.jsxs(at,{to:b.path,className:"inline-flex items-center gap-2 text-sm font-medium text-brand-500 hover:text-brand-600 group-hover:translate-x-1 transition-transform",children:[b.action,e.jsx(lt,{className:"size-4"})]})]},j))})})]})]})}const is=Object.freeze(Object.defineProperty({__proto__:null,default:$t},Symbol.toStringTag,{value:"Module"}));function De(){const t=_e(),{activeSector:c}=Ee(),{pageSize:d}=Ye(),[s,_]=a.useState([]),[k,S]=a.useState([]),[I,P]=a.useState(!0),[g,D]=a.useState(""),[E,z]=a.useState(""),[x,Q]=a.useState(""),[W,J]=a.useState(""),[H,Z]=a.useState(""),[b,j]=a.useState([]),[u,M]=a.useState(1),[V,n]=a.useState(1),[p,l]=a.useState(0),[m,i]=a.useState("created_at"),[w,N]=a.useState("desc"),[A,y]=a.useState(!1),[v,O]=a.useState(!1),[G,ee]=a.useState(!1),[re,he]=a.useState(null),[te,ue]=a.useState({title:"",description:"",keywords:"",cluster_id:null,content_structure:"blog_post",content_type:"blog_post",status:"queued",word_count:0}),F=Je(),[ce,ge]=a.useState([]),xe=Ke(),se=a.useRef(null),me=a.useRef(-1),de=a.useRef(!1),X=a.useCallback(r=>{xe&&ge(f=>[...f,r])},[xe]);a.useEffect(()=>{(async()=>{try{const f=await bt({ordering:"name"});S(f.results||[])}catch(f){console.error("Error fetching clusters:",f)}})()},[]);const q=a.useCallback(async()=>{P(!0),y(!1);try{const r=m?`${w==="desc"?"-":""}${m}`:"-created_at",f={...g&&{search:g},...E&&{status:E},...x&&{cluster_id:x},...W&&{content_structure:W},...H&&{content_type:H},page:u,page_size:d,ordering:r},T=await He(f);_(T.results||[]),l(T.count||0),n(Math.ceil((T.count||0)/d)),setTimeout(()=>{y(!0),P(!1)},100)}catch(r){console.error("Error loading tasks:",r),t.error(`Failed to load tasks: ${r.message}`),y(!0),P(!1)}},[u,E,x,W,H,m,w,g,c,d]);a.useEffect(()=>{q()},[q]),a.useEffect(()=>{const r=()=>{q()},f=()=>{q()};return window.addEventListener("siteChanged",r),window.addEventListener("sectorChanged",f),()=>{window.removeEventListener("siteChanged",r),window.removeEventListener("sectorChanged",f)}},[q]),a.useEffect(()=>{M(1)},[d]),a.useEffect(()=>{const r=setTimeout(()=>{u===1?q():M(1)},500);return()=>clearTimeout(r)},[g,u,q]);const fe=(r,f)=>{i(r||"created_at"),N(f),M(1)},h=a.useCallback(async(r,f)=>{try{const T=r.map(R=>parseInt(R));await mt(T,f),await q()}catch(T){throw T}},[q]),ie=a.useCallback(async r=>{try{if(!r||r.length===0)throw new Error("No records selected for export");t.info("Export functionality coming soon")}catch(f){throw f}},[]),Ce=a.useCallback(async(r,f)=>{if(r==="generate_content"){if(!f.title){t.error("Task must have a title to generate content");return}const T={ids:[f.id],task_title:f.title,task_id:f.id};X({timestamp:new Date().toISOString(),type:"request",action:"generate_content (Row Action)",data:T});try{const R=await pt([f.id]);R.success?R.task_id?(X({timestamp:new Date().toISOString(),type:"success",action:"generate_content (Row Action)",data:{task_id:R.task_id,message:R.message}}),F.openModal(R.task_id,"Generating Content","ai-generate-content-03"),t.success("Content generation started")):(X({timestamp:new Date().toISOString(),type:"success",action:"generate_content (Row Action)",data:{tasks_updated:R.tasks_updated||0,message:R.message}}),t.success(`Content generated successfully: ${R.tasks_updated||0} article generated`),await q()):(X({timestamp:new Date().toISOString(),type:"error",action:"generate_content (Row Action)",data:{error:R.error||"Failed to generate content"}}),t.error(R.error||"Failed to generate content"))}catch(R){X({timestamp:new Date().toISOString(),type:"error",action:"generate_content (Row Action)",data:{error:R.message||"Unknown error occurred"}}),t.error(`Failed to generate content: ${R.message}`)}}},[t,q,F]),Ie=a.useCallback(async(r,f)=>{if(r==="generate_images"){if(f.length===0){t.error("Please select at least one task to generate images");return}if(f.length>10){t.error("Maximum 10 tasks allowed for image generation");return}const T=f.map(B=>parseInt(B)),R=s.filter(B=>T.includes(B.id)),L={ids:T,task_count:T.length,task_titles:R.map(B=>B.title)};X({timestamp:new Date().toISOString(),type:"request",action:"generate_images (Bulk Action)",data:L});try{const B=await xt(T);B.success?B.task_id?(X({timestamp:new Date().toISOString(),type:"success",action:"generate_images (Bulk Action)",data:{task_id:B.task_id,message:B.message,task_count:T.length}}),F.openModal(B.task_id,"Generating Images"),t.success("Image generation started")):(X({timestamp:new Date().toISOString(),type:"success",action:"generate_images (Bulk Action)",data:{images_created:B.images_created||0,message:B.message,task_count:T.length}}),t.success(`Image generation complete: ${B.images_created||0} images generated`),await q()):(X({timestamp:new Date().toISOString(),type:"error",action:"generate_images (Bulk Action)",data:{error:B.error||"Failed to generate images",task_count:T.length}}),t.error(B.error||"Failed to generate images"))}catch(B){X({timestamp:new Date().toISOString(),type:"error",action:"generate_images (Bulk Action)",data:{error:B.message||"Unknown error occurred",task_count:T.length}}),t.error(`Failed to generate images: ${B.message}`)}}else t.info(`Bulk action "${r}" for ${f.length} items`)},[t,q,F,s]);a.useEffect(()=>{var B;if(!F.taskId||!F.isOpen)return;const r=F.progress,f=((B=r.details)==null?void 0:B.phase)||"",T=r.percentage,R=r.message,L=r.status;if(f&&f!==se.current){const o=L==="error"?"error":L==="completed"?"success":"step";X({timestamp:new Date().toISOString(),type:o,action:F.title||"AI Function",stepName:f,percentage:T,data:{step:f,message:R,percentage:T,status:L,details:r.details}}),se.current=f,me.current=T}else if(f&&Math.abs(T-me.current)>=10){const o=L==="error"?"error":L==="completed"?"success":"step";X({timestamp:new Date().toISOString(),type:o,action:F.title||"AI Function",stepName:f,percentage:T,data:{step:f,message:R,percentage:T,status:L,details:r.details}}),me.current=T}else if((L==="error"||L==="completed")&&(f!==se.current||L==="error"&&se.current!=="error"||L==="completed"&&se.current!=="completed")){const o=L==="error"?"error":"success";X({timestamp:new Date().toISOString(),type:o,action:F.title||"AI Function",stepName:f||"Final",percentage:T,data:{step:f||"Final",message:R,percentage:T,status:L,details:r.details}}),se.current=f||L}},[F.progress,F.taskId,F.isOpen,F.title,X]),a.useEffect(()=>{F.isOpen||(se.current=null,me.current=-1),de.current=!1},[F.isOpen,F.taskId]);const oe=a.useMemo(()=>Et({clusters:k,activeSector:c,formData:te,setFormData:ue,searchTerm:g,setSearchTerm:D,statusFilter:E,setStatusFilter:z,clusterFilter:x,setClusterFilter:Q,structureFilter:W,setStructureFilter:J,typeFilter:H,setTypeFilter:Z,setCurrentPage:M}),[k,c,te,g,E,x,W,H]),Te=a.useMemo(()=>oe!=null&&oe.headerMetrics?oe.headerMetrics.map(r=>({label:r.label,value:r.calculate({tasks:s,totalCount:p}),accentColor:r.accentColor})):[],[oe==null?void 0:oe.headerMetrics,s,p]),ye=a.useCallback(()=>{ue({title:"",description:"",keywords:"",cluster_id:null,content_structure:"blog_post",content_type:"blog_post",status:"queued",word_count:0}),ee(!1),he(null)},[]),ke=async()=>{try{G&&re?(await yt(re.id,te),t.success("Task updated successfully")):(await kt(te),t.success("Task created successfully")),O(!1),ye(),q()}catch(r){t.error(`Failed to save: ${r.message}`)}};return e.jsxs(e.Fragment,{children:[e.jsx(Se,{title:"Tasks",badge:{icon:e.jsx(ot,{}),color:"indigo"}}),e.jsx($e,{columns:oe.columns,data:s,loading:I,showContent:A,filters:oe.filters,filterValues:{search:g,status:E,cluster_id:x,content_structure:W,content_type:H},onFilterChange:(r,f)=>{const T=f==null?"":String(f);r==="search"?D(T):r==="status"?z(T):r==="cluster_id"?Q(T):r==="content_structure"?J(T):r==="content_type"&&Z(T),M(1)},onEdit:r=>{he(r),ue({title:r.title||"",description:r.description||"",keywords:r.keywords||"",cluster_id:r.cluster_id||null,content_structure:r.content_structure||"blog_post",content_type:r.content_type||"blog_post",status:r.status||"queued",word_count:r.word_count||0}),ee(!0),O(!0)},onCreate:()=>{ye(),O(!0)},createLabel:"Add Task",onCreateIcon:e.jsx(it,{}),onDelete:async r=>{await ft(r),q()},onBulkDelete:async r=>{const f=await ht(r);return j([]),u>1&&s.length<=r.length&&M(1),await q(),f},onBulkExport:ie,onBulkUpdateStatus:h,onBulkAction:Ie,onRowAction:Ce,getItemDisplayName:r=>r.title,onExport:async()=>{t.info("Export functionality coming soon")},onExportIcon:e.jsx(Ge,{}),selectionLabel:"task",pagination:{currentPage:u,totalPages:V,totalCount:p,onPageChange:M},selection:{selectedIds:b,onSelectionChange:j},sorting:{sortBy:m,sortDirection:w,onSort:fe},headerMetrics:Te,onFilterReset:()=>{D(""),z(""),Q(""),J(""),Z(""),M(1)}}),e.jsx(Xe,{isOpen:F.isOpen,title:F.title,percentage:F.progress.percentage,status:F.progress.status,message:F.progress.message,details:F.progress.details,taskId:F.taskId||void 0,functionId:F.functionId,onClose:()=>{const r=F.progress.status==="completed";F.closeModal(),r&&!de.current&&(de.current=!0,q(),setTimeout(()=>{de.current=!1},1e3))}}),xe&&ce.length>0&&e.jsxs("div",{className:"mt-6 bg-gray-50 dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h3",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"AI Function Logs"}),e.jsx("button",{onClick:()=>ge([]),className:"text-xs text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200",children:"Clear Logs"})]}),e.jsx("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:ce.slice().reverse().map((r,f)=>e.jsxs("div",{className:`p-3 rounded border text-xs font-mono ${r.type==="request"?"bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800":r.type==="success"?"bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800":r.type==="error"?"bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800":"bg-purple-50 dark:bg-purple-900/20 border-purple-200 dark:border-purple-800"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:`font-semibold ${r.type==="request"?"text-blue-700 dark:text-blue-300":r.type==="success"?"text-green-700 dark:text-green-300":r.type==="error"?"text-red-700 dark:text-red-300":"text-purple-700 dark:text-purple-300"}`,children:["[",r.type.toUpperCase(),"]"]}),e.jsx("span",{className:"text-gray-700 dark:text-gray-300",children:r.action}),r.stepName&&e.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-gray-200 dark:bg-gray-700 text-gray-600 dark:text-gray-400",children:r.stepName}),r.percentage!==void 0&&e.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:[r.percentage,"%"]})]}),e.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:new Date(r.timestamp).toLocaleTimeString()})]}),e.jsx("pre",{className:"text-xs text-gray-700 dark:text-gray-300 whitespace-pre-wrap break-words",children:JSON.stringify(r.data,null,2)})]},f))})]}),e.jsx(Tt,{isOpen:v,onClose:()=>{O(!1),ye()},onSubmit:ke,title:G?"Edit Task":"Add Task",submitLabel:G?"Update":"Create",fields:oe.formFields(k)})]})}const ds=Object.freeze(Object.defineProperty({__proto__:null,default:De},Symbol.toStringTag,{value:"Module"}));function Ot(){const t=_e(),{activeSector:c}=Ee(),{pageSize:d}=Ye(),[s,_]=a.useState([]),[k,S]=a.useState(!0),[I,P]=a.useState(""),[g,D]=a.useState(""),[E,z]=a.useState([]),[x,Q]=a.useState(1),[W,J]=a.useState(1),[H,Z]=a.useState(0),[b,j]=a.useState("generated_at"),[u,M]=a.useState("desc"),[V,n]=a.useState(!1),p=Je(),l=a.useRef(!1),m=a.useCallback(async()=>{S(!0),n(!1);try{const y=b?`${u==="desc"?"-":""}${b}`:"-generated_at",v={...I&&{search:I},...g&&{status:g},page:x,page_size:d,ordering:y},O=await Ve(v);_(O.results||[]),Z(O.count||0),J(Math.ceil((O.count||0)/d)),setTimeout(()=>{n(!0),S(!1)},100)}catch(y){console.error("Error loading content:",y),t.error(`Failed to load content: ${y.message}`),n(!0),S(!1)}},[x,g,b,u,I,c,d,t]);a.useEffect(()=>{m()},[m]),a.useEffect(()=>{const y=()=>{m()},v=()=>{m()};return window.addEventListener("siteChanged",y),window.addEventListener("sectorChanged",v),()=>{window.removeEventListener("siteChanged",y),window.removeEventListener("sectorChanged",v)}},[m]),a.useEffect(()=>{Q(1)},[d]),a.useEffect(()=>{const y=setTimeout(()=>{x===1?m():Q(1)},500);return()=>clearTimeout(y)},[I,x,m]);const i=(y,v)=>{j(y||"generated_at"),M(v),Q(1)},w=a.useMemo(()=>Ft({activeSector:c}),[c,I,g]),N=a.useMemo(()=>w!=null&&w.headerMetrics?w.headerMetrics.map(y=>({label:y.label,value:y.calculate({content:s,totalCount:H}),accentColor:y.accentColor})):[],[w==null?void 0:w.headerMetrics,s,H]),A=a.useCallback(async(y,v)=>{if(y==="generate_image_prompts")try{const O=await jt([v.id]);O.success?O.task_id?p.openModal(O.task_id,"Smart Image Prompts","ai-generate-image-prompts-01-desktop"):(t.success(`Image prompts generated: ${O.prompts_created||0} prompt${(O.prompts_created||0)===1?"":"s"} created`),m()):t.error(O.error||"Failed to generate image prompts")}catch(O){t.error(`Failed to generate prompts: ${O.message}`)}},[t,p,m]);return e.jsxs(e.Fragment,{children:[e.jsx(Se,{title:"Content",badge:{icon:e.jsx(be,{}),color:"purple"}}),e.jsx($e,{columns:w.columns,data:s,loading:k,showContent:V,filters:w.filters,filterValues:{search:I,status:g},onFilterChange:(y,v)=>{y==="search"?P(v):y==="status"&&(D(v),Q(1))},pagination:{currentPage:x,totalPages:W,totalCount:H,onPageChange:Q},sorting:{sortBy:b,sortDirection:u,onSort:i},selection:{selectedIds:E,onSelectionChange:z},headerMetrics:N,onRowAction:A,getItemDisplayName:y=>y.meta_title||y.title||`Content #${y.id}`}),e.jsx(Xe,{isOpen:p.isOpen,title:p.title,percentage:p.progress.percentage,status:p.progress.status,message:p.progress.message,details:p.progress.details,taskId:p.taskId||void 0,functionId:p.functionId,onClose:()=>{const y=p.progress.status==="completed";p.closeModal(),y&&!l.current&&(l.current=!0,m(),setTimeout(()=>{l.current=!1},1e3))}})]})}const cs=Object.freeze(Object.defineProperty({__proto__:null,default:Ot},Symbol.toStringTag,{value:"Module"})),Dt={generated:"bg-emerald-100 text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-200",pending:"bg-amber-100 text-amber-700 dark:bg-amber-500/20 dark:text-amber-200",queued:"bg-amber-100 text-amber-700 dark:bg-amber-500/20 dark:text-amber-200",failed:"bg-rose-100 text-rose-700 dark:bg-rose-500/20 dark:text-rose-200",error:"bg-rose-100 text-rose-700 dark:bg-rose-500/20 dark:text-rose-200"},Me=t=>t.map(c=>c.nodeType===Node.ELEMENT_NODE?c.outerHTML:c.nodeType===Node.TEXT_NODE?c.textContent??"":"").join(""),Ue=(t,c)=>t.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||`section-${c+1}`,Lt=t=>{if(!t)return{introHtml:"",sections:[]};let c=null;if(typeof window<"u"&&typeof window.DOMParser<"u"?c=new window.DOMParser:typeof DOMParser<"u"&&(c=new DOMParser),!c)return{introHtml:t,sections:[]};try{const s=c.parseFromString(t,"text/html").body,_=[],k=[];let S=null;return Array.from(s.childNodes).forEach(I=>{var P;if(I.nodeType===Node.ELEMENT_NODE){const g=I;if(g.tagName==="H2"){S&&k.push({id:Ue(S.heading,k.length),heading:S.heading||`Section ${k.length+1}`,headingLevel:S.level,bodyHtml:Me(S.nodes).trim()}),S={heading:((P=g.textContent)==null?void 0:P.trim())||"",level:2,nodes:[]};return}}S?S.nodes.push(I):_.push(I)}),S&&k.push({id:Ue(S.heading,k.length),heading:S.heading||`Section ${k.length+1}`,headingLevel:S.level,bodyHtml:Me(S.nodes).trim()}),{introHtml:Me(_).trim(),sections:k}}catch{return{introHtml:t,sections:[]}}},At=t=>{if(!t||typeof t!="object")return null;const c=new WeakSet,d=s=>{if(!s||typeof s!="object"||c.has(s))return null;if(c.add(s),Array.isArray(s)){for(const I of s){const P=d(I);if(P)return P}return null}const _=s,k=typeof _.featured_prompt=="string",S=Array.isArray(_.in_article_prompts);if(k||S)return{featured_prompt:k?_.featured_prompt:void 0,in_article_prompts:S?_.in_article_prompts.filter(I=>typeof I=="string"):void 0};for(const I of Object.keys(_)){const P=d(_[I]);if(P)return P}return null};return d(t)},Ze=t=>{if(t){if(t.image_url)return t.image_url;if(t.image_path)return`/api/v1/writer/images/${t.id}/file/`}},et=({status:t,className:c=""})=>{if(!t)return null;const d=t.toLowerCase(),s=Dt[d]||"bg-slate-100 text-slate-700 dark:bg-slate-700/70 dark:text-slate-200";return e.jsx("span",{className:`inline-flex items-center gap-1 rounded-full px-3 py-1 text-xs font-semibold uppercase tracking-wide ${s} ${c}`,children:t})},tt=({prompt:t,label:c,minHeight:d=220})=>e.jsx("div",{className:"flex w-full items-center justify-center rounded-3xl bg-gradient-to-br from-slate-100 via-slate-50 to-white p-8 text-center dark:from-gray-800 dark:via-gray-900 dark:to-gray-950",style:{minHeight:d},children:e.jsxs("div",{className:"max-w-xl space-y-3",children:[c&&e.jsx("p",{className:"text-[0.7rem] font-semibold uppercase tracking-[0.3em] text-slate-500 dark:text-slate-400",children:c}),e.jsx("p",{className:"text-sm font-medium leading-relaxed text-slate-600 dark:text-slate-300 whitespace-pre-wrap",children:t||"Image prompt available, awaiting generation."})]})}),Rt=({image:t,loading:c})=>{const d=Ze(t);return!c&&!t&&!d?null:e.jsxs("div",{className:"overflow-hidden rounded-3xl border border-slate-200/80 bg-white/80 shadow-lg shadow-slate-200/40 backdrop-blur-sm dark:border-gray-800/70 dark:bg-gray-900/70 dark:shadow-black/10",children:[e.jsxs("div",{className:"flex items-center justify-between px-8 pt-8",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-[0.35em] text-slate-500 dark:text-slate-400",children:"Featured Visual"}),e.jsx(et,{status:t==null?void 0:t.status})]}),e.jsxs("div",{className:"relative mt-6",children:[c&&!d?e.jsx("div",{className:"h-[420px] animate-pulse bg-slate-200/70 dark:bg-gray-800/60"}):d?e.jsx("img",{src:d,alt:t!=null&&t.prompt?`Featured visual: ${t.prompt}`:"Featured visual",className:"h-full w-full object-cover",loading:"lazy"}):e.jsx(tt,{prompt:t==null?void 0:t.prompt,minHeight:420,label:"Featured Image Prompt"}),(t==null?void 0:t.prompt)&&d&&e.jsx("div",{className:"absolute bottom-5 left-5 rounded-full bg-white/80 px-4 py-2 text-xs font-medium text-slate-600 backdrop-blur-sm dark:bg-gray-950/70 dark:text-slate-300",children:"Prompt aligned to hero section"})]}),(t==null?void 0:t.prompt)&&e.jsx("div",{className:"border-t border-slate-200/70 bg-white/70 px-8 py-6 text-sm leading-relaxed text-slate-600 backdrop-blur-sm dark:border-gray-800/60 dark:bg-gray-900/70 dark:text-slate-300",children:t.prompt})]})},Bt=({image:t,loading:c,heading:d})=>{if(!t&&!c)return null;const s=Ze(t);return e.jsxs("figure",{className:"overflow-hidden rounded-3xl border border-slate-200/70 bg-slate-50/70 shadow-inner shadow-slate-200/70 dark:border-gray-800/60 dark:bg-gray-900/40 dark:shadow-black/30",children:[e.jsxs("div",{className:"relative",children:[c&&!t?e.jsx("div",{className:"h-[260px] animate-pulse bg-slate-200/60 dark:bg-gray-800/60"}):s?e.jsx("img",{src:s,alt:t!=null&&t.prompt?`${d} visual: ${t.prompt}`:`${d} visual`,className:"w-full object-cover",loading:"lazy"}):e.jsx(tt,{prompt:t==null?void 0:t.prompt,minHeight:260,label:"In-Article Prompt"}),e.jsx("div",{className:"absolute right-4 top-4",children:e.jsx(et,{status:t==null?void 0:t.status})})]}),(t==null?void 0:t.prompt)&&e.jsxs("figcaption",{className:"space-y-3 px-6 py-5 text-sm leading-relaxed text-slate-600 dark:text-slate-300",children:[e.jsx("p",{className:"font-semibold uppercase tracking-[0.25em] text-slate-400 dark:text-slate-500",children:"Visual Direction"}),e.jsx("p",{className:"font-medium whitespace-pre-wrap",children:t.prompt})]})]})},Ut=({html:t})=>e.jsxs("section",{className:"overflow-hidden rounded-3xl border border-slate-200/80 bg-gradient-to-br from-white via-slate-50 to-white p-8 shadow-sm shadow-slate-200/60 dark:border-gray-800/70 dark:from-gray-900 dark:via-gray-950 dark:to-gray-900 dark:shadow-black/20",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-[0.35em] text-slate-500 dark:text-slate-400",children:"Opening Narrative"}),e.jsx("div",{className:"content-html prose prose-lg mt-6 max-w-none text-gray-800 dark:prose-invert",children:e.jsx("div",{dangerouslySetInnerHTML:{__html:t}})})]}),zt=({section:t,image:c,loading:d,index:s})=>{const _=!!c,k=t.heading||`Section ${s+1}`;return e.jsx("section",{id:t.id,className:"group/section scroll-mt-24",children:e.jsx("div",{className:"overflow-hidden rounded-3xl border border-slate-200/80 bg-white/90 shadow-lg shadow-slate-200/50 backdrop-blur-sm transition-transform duration-300 group-hover/section:-translate-y-1 dark:border-gray-800/70 dark:bg-gray-900/70 dark:shadow-black/20",children:e.jsxs("div",{className:"flex flex-col gap-6 p-8 sm:p-10",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("span",{className:"inline-flex h-10 w-10 items-center justify-center rounded-full bg-brand-500/10 text-sm font-semibold text-brand-600 dark:bg-brand-500/20 dark:text-brand-300",children:s+1}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-[0.7rem] font-semibold uppercase tracking-[0.35em] text-slate-400 dark:text-slate-500",children:"Section Spotlight"}),e.jsx("h2",{className:"text-2xl font-bold text-slate-900 dark:text-white sm:text-3xl",children:k})]})]}),e.jsxs("div",{className:_?"grid gap-10 lg:grid-cols-[minmax(0,3fr)_minmax(0,2fr)]":"",children:[e.jsx("div",{className:"content-html prose prose-lg max-w-none text-gray-800 dark:prose-invert ",children:e.jsx("div",{dangerouslySetInnerHTML:{__html:t.bodyHtml}})}),_&&e.jsx("div",{className:"flex flex-col gap-4",children:e.jsx(Bt,{image:c,loading:d,heading:k})})]})]})})})},Wt=({introHtml:t,sections:c,sectionImages:d,imagesLoading:s,rawHtml:_})=>!(c.length>0)&&!t&&_?e.jsx("div",{className:"overflow-hidden rounded-3xl border border-slate-200/80 bg-white/90 p-8 shadow-lg shadow-slate-200/50 dark:border-gray-800/70 dark:bg-gray-900/70 dark:shadow-black/20",children:e.jsx("div",{className:"content-html prose prose-lg max-w-none text-gray-800 dark:prose-invert",children:e.jsx("div",{dangerouslySetInnerHTML:{__html:_}})})}):e.jsxs("div",{className:"space-y-12",children:[t&&e.jsx(Ut,{html:t}),c.map((S,I)=>e.jsx(zt,{section:S,image:d[I]??null,loading:s,index:I},S.id||`section-${I}`))]});function Gt({content:t,loading:c,onBack:d}){var b;const[s,_]=a.useState([]),[k,S]=a.useState(!1),[I,P]=a.useState(null),g=a.useMemo(()=>At(t==null?void 0:t.metadata),[t==null?void 0:t.metadata]);a.useEffect(()=>{let j=!0;return t!=null&&t.id?(S(!0),Qe({content_id:t.id,ordering:"position",page_size:50}).then(u=>{j&&(_(((u==null?void 0:u.results)??[]).filter(Boolean)),P(null))}).catch(u=>{j&&(P((u==null?void 0:u.message)||"Unable to load images for this content."),_([]))}).finally(()=>{j&&S(!1)}),()=>{j=!1}):(_([]),P(null),S(!1),()=>{j=!1})},[t==null?void 0:t.id]);const D=a.useMemo(()=>s.length?[...s].sort((j,u)=>{const M=j.position??0,V=u.position??0;return j.image_type===u.image_type?M-V:j.image_type==="featured"?-1:u.image_type==="featured"?1:M-V}):[],[s]),E=a.useMemo(()=>D.find(j=>j.image_type==="featured")??null,[D]),z=a.useMemo(()=>D.filter(j=>j.image_type==="in_article"),[D]),x=a.useMemo(()=>E||(g!=null&&g.featured_prompt?{id:-1,task_id:(t==null?void 0:t.task_id)??null,task_title:(t==null?void 0:t.task_title)??null,content_id:(t==null?void 0:t.id)??null,content_title:(t==null?void 0:t.title)??(t==null?void 0:t.meta_title)??null,image_type:"featured",image_url:void 0,image_path:void 0,prompt:g.featured_prompt,status:"pending",position:0,created_at:"",updated_at:"",account_id:void 0}:null),[E,g,t==null?void 0:t.task_id,t==null?void 0:t.task_title,t==null?void 0:t.id,t==null?void 0:t.title,t==null?void 0:t.meta_title]),Q=a.useMemo(()=>{const j=[...z].sort((p,l)=>(p.position??0)-(l.position??0)),u=(g==null?void 0:g.in_article_prompts)??[];if(!u.length)return j;const M=new Map;j.forEach((p,l)=>{const m=p.position??l+1;M.set(m,p)});const V=new Set,n=u.map((p,l)=>{const m=l+1,i=M.get(m);return V.add(m),i?{...i,prompt:i.prompt||p}:{id:-1*(l+1),task_id:(t==null?void 0:t.task_id)??null,task_title:(t==null?void 0:t.task_title)??null,content_id:(t==null?void 0:t.id)??null,content_title:(t==null?void 0:t.title)??(t==null?void 0:t.meta_title)??null,image_type:"in_article",image_url:void 0,image_path:void 0,prompt:p,status:"pending",position:m,created_at:"",updated_at:"",account_id:void 0}});return j.forEach((p,l)=>{const m=p.position??l+1;V.has(m)||n.push(p)}),n.sort((p,l)=>(p.position??0)-(l.position??0))},[z,g,t==null?void 0:t.task_id,t==null?void 0:t.task_title,t==null?void 0:t.id,t==null?void 0:t.title,t==null?void 0:t.meta_title]),W=a.useMemo(()=>Lt((t==null?void 0:t.html_content)??""),[t==null?void 0:t.html_content]),J=k||!!x;if(c)return e.jsx("div",{className:"min-h-screen bg-gray-50 dark:bg-gray-900 py-8",children:e.jsx("div",{className:"max-w-[1200px] mx-auto px-4 sm:px-6 lg:px-8",children:e.jsxs("div",{className:"animate-pulse",children:[e.jsx("div",{className:"h-8 bg-gray-200 dark:bg-gray-700 rounded w-1/4 mb-6"}),e.jsx("div",{className:"h-12 bg-gray-200 dark:bg-gray-700 rounded w-3/4 mb-4"}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"h-4 bg-gray-200 dark:bg-gray-700 rounded"}),e.jsx("div",{className:"h-4 bg-gray-200 dark:bg-gray-700 rounded w-5/6"})]})]})})});if(!t)return e.jsx("div",{className:"min-h-screen bg-gray-50 dark:bg-gray-900 py-8",children:e.jsx("div",{className:"max-w-[1200px] mx-auto px-4 sm:px-6 lg:px-8",children:e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-2xl shadow-sm border border-gray-200 dark:border-gray-700 p-8 text-center",children:[e.jsx(qe,{className:"w-16 h-16 text-gray-400 mx-auto mb-4"}),e.jsx("h2",{className:"text-2xl font-semibold text-gray-900 dark:text-white mb-2",children:"Content Not Found"}),e.jsx("p",{className:"text-gray-600 dark:text-gray-400 mb-6",children:"The content you're looking for doesn't exist or has been deleted."}),d&&e.jsxs("button",{onClick:d,className:"inline-flex items-center gap-2 px-4 py-2 bg-brand-500 text-white rounded-lg hover:bg-brand-600 transition-colors",children:[e.jsx(Ae,{className:"w-4 h-4"}),"Back to Content List"]})]})})});const H=j=>{try{return new Date(j).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return j}},Z=j=>{const u=j.toLowerCase();return u==="generated"||u==="published"||u==="complete"?"bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400":u==="pending"||u==="draft"?"bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400":u==="failed"||u==="error"?"bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400":"bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300"};return e.jsxs("div",{className:"min-h-screen bg-gray-50 dark:bg-gray-900 py-8",children:[e.jsxs("div",{className:"max-w-[1200px] mx-auto px-4 sm:px-6 lg:px-8",children:[d&&e.jsxs("button",{onClick:d,className:"mb-6 inline-flex items-center gap-2 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors",children:[e.jsx(Ae,{className:"w-5 h-5"}),e.jsx("span",{className:"font-medium",children:"Back to Content"})]}),e.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-2xl shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden",children:[e.jsx("div",{className:"bg-gradient-to-r from-brand-500 to-brand-600 px-8 py-6 text-white",children:e.jsx("div",{className:"flex items-start justify-between gap-4",children:e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[e.jsx(be,{className:"w-6 h-6"}),e.jsx("span",{className:`px-3 py-1 rounded-full text-sm font-medium ${Z(t.status)}`,children:t.status})]}),e.jsx("h1",{className:"text-3xl font-bold mb-2",children:t.meta_title||t.title||`Content #${t.id}`}),t.meta_description&&e.jsx("p",{className:"text-brand-50 text-lg leading-relaxed",children:t.meta_description})]})})}),e.jsxs("div",{className:"px-8 py-6 border-b border-gray-200 dark:border-gray-700",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-sm font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide",children:"Basic Information"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(dt,{className:"w-5 h-5 text-gray-400 mt-0.5 flex-shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Generated"}),e.jsx("p",{className:"text-sm font-medium text-gray-900 dark:text-white",children:H(t.generated_at)})]})]}),t.updated_at&&t.updated_at!==t.generated_at&&e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Fe,{className:"w-5 h-5 text-gray-400 mt-0.5 flex-shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Last Updated"}),e.jsx("p",{className:"text-sm font-medium text-gray-900 dark:text-white",children:H(t.updated_at)})]})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(be,{className:"w-5 h-5 text-gray-400 mt-0.5 flex-shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Word Count"}),e.jsxs("p",{className:"text-sm font-medium text-gray-900 dark:text-white",children:[((b=t.word_count)==null?void 0:b.toLocaleString())||"N/A"," words"]})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-sm font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide",children:"Related Information"}),e.jsxs("div",{className:"space-y-3",children:[t.task_title&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Task"}),e.jsx("p",{className:"text-sm font-medium text-gray-900 dark:text-white",children:t.task_title}),e.jsxs("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1",children:["ID: ",t.task_id]})]}),t.sector_name&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Sector"}),e.jsx("p",{className:"text-sm font-medium text-gray-900 dark:text-white",children:t.sector_name})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-sm font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide",children:"SEO & Tags"}),e.jsxs("div",{className:"space-y-3",children:[t.primary_keyword&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Primary Keyword"}),e.jsx("p",{className:"text-sm font-medium text-gray-900 dark:text-white",children:t.primary_keyword})]}),t.secondary_keywords&&t.secondary_keywords.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mb-2",children:"Secondary Keywords"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:t.secondary_keywords.map((j,u)=>e.jsx("span",{className:"px-2 py-1 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded text-xs",children:j},u))})]})]})]})]}),t.tags&&t.tags.length>0||t.categories&&t.categories.length>0?e.jsx("div",{className:"mt-6 pt-6 border-t border-gray-200 dark:border-gray-700",children:e.jsxs("div",{className:"flex flex-wrap gap-4",children:[t.tags&&t.tags.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(We,{className:"w-4 h-4 text-gray-400"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:t.tags.map((j,u)=>e.jsx("span",{className:"px-3 py-1 bg-brand-50 dark:bg-brand-900/20 text-brand-700 dark:text-brand-300 rounded-full text-xs font-medium",children:j},u))})]}),t.categories&&t.categories.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Categories:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:t.categories.map((j,u)=>e.jsx("span",{className:"px-3 py-1 bg-purple-50 dark:bg-purple-900/20 text-purple-700 dark:text-purple-300 rounded-full text-xs font-medium",children:j},u))})]})]})}):null]}),(t.has_image_prompts||t.has_generated_images)&&e.jsx("div",{className:"px-8 py-4 bg-gray-50 dark:bg-gray-900/50 border-b border-gray-200 dark:border-gray-700",children:e.jsxs("div",{className:"flex items-center gap-4",children:[t.has_image_prompts&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pe,{className:"w-5 h-5 text-green-500"}),e.jsx("span",{className:"text-sm text-gray-700 dark:text-gray-300",children:"Image Prompts Generated"})]}),t.has_generated_images&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pe,{className:"w-5 h-5 text-green-500"}),e.jsx("span",{className:"text-sm text-gray-700 dark:text-gray-300",children:"Images Generated"})]})]})}),J&&e.jsx("div",{className:"px-8 pt-8",children:e.jsx(Rt,{image:x,loading:k})}),I&&e.jsx("div",{className:"px-8 pt-4",children:e.jsx("div",{className:"rounded-2xl border border-rose-200 bg-rose-50/80 px-4 py-3 text-sm font-medium text-rose-700 dark:border-rose-900/40 dark:bg-rose-950/30 dark:text-rose-300",children:I})}),e.jsx("div",{className:"px-8 pb-10 pt-10",children:e.jsx(Wt,{introHtml:W.introHtml,sections:W.sections,sectionImages:Q,imagesLoading:k,rawHtml:t.html_content})}),t.metadata&&Object.keys(t.metadata).length>0&&e.jsx("div",{className:"px-8 py-6 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900/50",children:e.jsxs("details",{className:"group",children:[e.jsx("summary",{className:"cursor-pointer text-sm font-semibold text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white",children:"View Full Metadata"}),e.jsx("div",{className:"mt-4 p-4 bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700",children:e.jsx("pre",{className:"text-xs text-gray-600 dark:text-gray-400 overflow-x-auto",children:JSON.stringify(t.metadata,null,2)})})]})})]})]}),e.jsx("style",{children:`
.content-html {
line-height: 1.85;
font-size: 1.05rem;
}
.content-html h2,
.content-html h3,
.content-html h4,
.content-html h5,
.content-html h6 {
margin-top: 2.5rem;
margin-bottom: 1.25rem;
font-weight: 600;
letter-spacing: -0.01em;
color: inherit;
}
.content-html h3 { font-size: 1.6rem; }
.content-html h4 { font-size: 1.35rem; }
.content-html h5 { font-size: 1.15rem; }
.content-html p {
margin-bottom: 1.3rem;
}
.content-html ul,
.content-html ol {
margin-bottom: 1.5rem;
padding-left: 1.75rem;
}
.content-html li {
margin-bottom: 0.6rem;
}
.content-html blockquote {
margin: 2rem 0;
padding: 1.25rem 1.5rem;
border-left: 4px solid rgba(59, 130, 246, 0.25);
background: rgba(59, 130, 246, 0.08);
border-radius: 1rem;
font-style: italic;
}
.content-html table {
width: 100%;
border-collapse: collapse;
margin: 2rem 0;
border-radius: 1rem;
overflow: hidden;
}
.content-html table th,
.content-html table td {
border: 1px solid #e5e7eb;
padding: 0.875rem 1rem;
text-align: left;
}
.content-html table th {
background: #f9fafb;
font-weight: 600;
}
.content-html img {
max-width: 100%;
height: auto;
border-radius: 1.25rem;
margin: 1.75rem auto;
display: block;
box-shadow: 0 20px 45px -25px rgba(15, 23, 42, 0.35);
}
.content-html a {
color: #2563eb;
text-decoration: none;
border-bottom: 1px solid rgba(37, 99, 235, 0.3);
transition: color 0.2s ease, border-bottom-color 0.2s ease;
}
.content-html a:hover {
color: #1d4ed8;
border-bottom-color: rgba(37, 99, 235, 0.6);
}
.content-html code {
background: rgba(15, 23, 42, 0.06);
padding: 0.2rem 0.45rem;
border-radius: 0.4rem;
font-size: 0.9rem;
}
.content-html pre {
background: rgba(15, 23, 42, 0.08);
padding: 1.25rem;
border-radius: 1.25rem;
overflow-x: auto;
margin: 2rem 0;
}
.content-html hr {
border: none;
border-top: 1px solid rgba(148, 163, 184, 0.4);
margin: 3rem 0;
}
.dark .content-html blockquote {
border-left-color: rgba(96, 165, 250, 0.45);
background: rgba(30, 41, 59, 0.65);
}
.dark .content-html table th,
.dark .content-html table td {
border-color: rgba(148, 163, 184, 0.25);
}
.dark .content-html table th {
background: rgba(30, 41, 59, 0.65);
}
.dark .content-html a {
color: #93c5fd;
border-bottom-color: rgba(147, 197, 253, 0.4);
}
.dark .content-html a:hover {
color: #bfdbfe;
border-bottom-color: rgba(191, 219, 254, 0.6);
}
.dark .content-html code,
.dark .content-html pre {
background: rgba(15, 23, 42, 0.7);
}
`})]})}function qt(){const{id:t}=rt(),c=ze(),d=_e(),[s,_]=a.useState(null),[k,S]=a.useState(!0);a.useEffect(()=>{(async()=>{if(!t){d.error("Content ID is required"),c("/writer/content");return}const g=parseInt(t,10);if(isNaN(g)||g<=0){d.error("Invalid content ID"),c("/writer/content");return}S(!0);try{const D=await vt(g);_(D)}catch(D){console.error("Error loading content:",D),d.error(`Failed to load content: ${D.message||"Unknown error"}`),_(null)}finally{S(!1)}})()},[t,c,d]);const I=()=>{c("/writer/content")};return e.jsxs(e.Fragment,{children:[e.jsx(Ne,{title:s?`${s.meta_title||s.title||`Content #${s.id}`} - IGNY8`:"Content View - IGNY8",description:(s==null?void 0:s.meta_description)||"View content details and metadata"}),e.jsx(Gt,{content:s,loading:k,onBack:I})]})}const us=Object.freeze(Object.defineProperty({__proto__:null,default:qt},Symbol.toStringTag,{value:"Module"}));function Ht(){return e.jsx(De,{})}const gs=Object.freeze(Object.defineProperty({__proto__:null,default:Ht},Symbol.toStringTag,{value:"Module"}));function Vt({isOpen:t,onClose:c,queue:d,totalImages:s,taskId:_,model:k,provider:S,onUpdateQueue:I,onLog:P}){const[g,D]=a.useState(d),[E,z]=a.useState({}),x=a.useRef({});a.useEffect(()=>{D(d)},[d]),a.useEffect(()=>{I&&I(g)},[g,I]),a.useEffect(()=>{const n=(l,m)=>{x.current[l]&&(clearInterval(x.current[l]),delete x.current[l]);let i=Math.max(m,50);const w=setInterval(()=>{z(N=>{const A=N[l]??i,y=g.find(v=>v.index===l);if(A<80&&(y==null?void 0:y.status)==="processing"){const v=Math.min(A+2,80);return i=v,v>=80&&(clearInterval(w),delete x.current[l]),{...N,[l]:v}}else return clearInterval(w),delete x.current[l],N})},200);x.current[l]=w},p=[];return g.forEach(l=>{if(l.status==="processing"){const m=E[l.index]??(l.progress>0?l.progress:1);if(m<50&&!x.current[l.index]){let i=Math.max(m,1);const w=setInterval(()=>{z(N=>{const A=N[l.index]??i;if(A<50&&l.status==="processing"){const y=Math.min(A+1,50);return i=y,y>=50&&(clearInterval(w),delete x.current[l.index],y<80&&n(l.index,y)),{...N,[l.index]:y}}else return clearInterval(w),delete x.current[l.index],N})},200);x.current[l.index]=w}else if(m>=50&&m<80&&!x.current[l.index])n(l.index,m);else if(l.imageUrl&&m<100&&!x.current[l.index]){x.current[l.index]&&(clearInterval(x.current[l.index]),delete x.current[l.index]);let i=Math.max(m,80);const w=i,N=100,A=800,y=Date.now(),v=setInterval(()=>{const O=Date.now()-y,G=Math.min(1,O/A),ee=1-Math.pow(1-G,2);i=w+(N-w)*ee,(i>=100||O>=A)&&(i=100,clearInterval(v),delete x.current[l.index]),z(re=>({...re,[l.index]:Math.round(i)}))},16);x.current[l.index]=v}}else x.current[l.index]&&(clearInterval(x.current[l.index]),delete x.current[l.index]),E[l.index]!==void 0&&p.push(l.index)}),p.length>0&&z(l=>{const m={...l};return p.forEach(i=>{delete m[i]}),m}),()=>{Object.values(x.current).forEach(l=>clearInterval(l)),x.current={}}},[g,E]),a.useEffect(()=>{if(!t||!_)return;let n=0;const p=300,l=setInterval(async()=>{var m;if(n++,n>p){console.warn("Polling timeout reached, stopping"),clearInterval(l);return}try{console.log(`[ImageQueueModal] Polling task status (attempt ${n}):`,_);const i=await wt(`/v1/system/settings/task_progress/${_}/`);if(console.log("[ImageQueueModal] Task status response:",i),!i||typeof i!="object"){console.warn("Invalid task status response:",i);return}const w=i.state||i.status;if(console.log("[ImageQueueModal] Task state:",w),w==="SUCCESS"||w==="FAILURE"){if(console.log("[ImageQueueModal] Task completed with state:",w),clearInterval(l),P)if(w==="SUCCESS"){const N=i.result||i.meta&&i.meta.result,A=(N==null?void 0:N.completed)||0,y=(N==null?void 0:N.failed)||0,v=(N==null?void 0:N.total_images)||s;P({timestamp:new Date().toISOString(),type:y>0?"error":"success",action:"generate_images",stepName:"Task Completed",data:{state:"SUCCESS",completed:A,failed:y,total:v,results:(N==null?void 0:N.results)||[]}})}else P({timestamp:new Date().toISOString(),type:"error",action:"generate_images",stepName:"Task Failed",data:{state:"FAILURE",error:i.error||((m=i.meta)==null?void 0:m.error)||"Task failed",meta:i.meta}});w==="SUCCESS"&&i.result?(console.log("[ImageQueueModal] Updating queue from result:",i.result),J(i.result)):w==="SUCCESS"&&i.meta&&i.meta.result&&(console.log("[ImageQueueModal] Updating queue from meta result:",i.meta.result),J(i.meta.result));return}i.meta?(console.log("[ImageQueueModal] Updating queue from meta:",i.meta),W(i.meta)):console.log("[ImageQueueModal] No meta data in response")}catch(i){if(i.message&&(i.message.includes("JSON")||i.message.includes("API Error"))){if(console.error("Task status endpoint error:",{message:i.message,status:i.status,taskId:_,endpoint:`/v1/system/settings/task_progress/${_}/`,error:i}),i.status===404){console.error("Task progress endpoint not found (404). Stopping polling."),clearInterval(l);return}}else console.error("Error polling task status:",i)}},1e3);return()=>clearInterval(l)},[t,_]);const Q=n=>{if(!n)return null;if(n.includes("ai-images")){const l=n.split("ai-images/")[1]||n.split("ai-images\\")[1];if(l)return`/images/ai-images/${l}`}if(n.startsWith("/images/"))return n;const p=n.split("/").pop()||n.split("\\").pop();return p?`/images/ai-images/${p}`:null},W=n=>{const{current_image:p,total_images:l,completed:m,failed:i,results:w,current_image_progress:N,current_image_id:A}=n;D(y=>y.map((v,O)=>{const G=w==null?void 0:w.find(ee=>ee.image_id===v.imageId);if(G){(G.status==="completed"||G.status==="failed")&&x.current[v.index]&&(clearInterval(x.current[v.index]),delete x.current[v.index]);const ee=G.status==="completed"&&G.image_path?Q(G.image_path):null,re=A===v.imageId&&N!==void 0?N:G.status==="completed"?100:G.status==="failed"?0:v.progress;return{...v,status:G.status==="completed"?"completed":G.status==="failed"?"failed":"processing",progress:re,imageUrl:ee||v.imageUrl,error:G.error||null}}if(O+1<p)return x.current[v.index]&&(clearInterval(x.current[v.index]),delete x.current[v.index]),{...v,status:"completed",progress:100};if(A===v.imageId){const ee=N!==void 0?N:E[v.index]??0;return{...v,status:"processing",progress:ee}}return v}))},J=n=>{const{results:p}=n;D(l=>l.map(m=>{const i=p==null?void 0:p.find(w=>w.image_id===m.imageId);if(i){x.current[m.index]&&(clearInterval(x.current[m.index]),delete x.current[m.index]);const w=i.status==="completed"&&i.image_path?Q(i.image_path):null;return{...m,status:i.status==="completed"?"completed":"failed",progress:i.status==="completed"?100:0,imageUrl:w||m.imageUrl,error:i.error||null}}return m}))};if(!t)return null;const H=n=>{switch(n){case"pending":return e.jsx(Fe,{className:"w-4 h-4"});case"processing":return e.jsxs("svg",{className:"w-4 h-4 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]});case"completed":return e.jsx(Pe,{className:"w-4 h-4"});case"failed":return e.jsx(qe,{className:"w-4 h-4"});default:return e.jsx(Fe,{className:"w-4 h-4"})}},Z=n=>{switch(n){case"pending":return"Pending";case"processing":return"Generating...";case"completed":return"Complete";case"failed":return"Failed";default:return"Pending"}},b=n=>{switch(n){case"completed":return"bg-green-500";case"failed":return"bg-red-500";case"processing":return"bg-blue-500";default:return"bg-gray-300"}},j=g.some(n=>n.status==="processing"),u=g.filter(n=>n.status==="completed").length,M=g.filter(n=>n.status==="failed").length,V=g.every(n=>n.status==="completed"||n.status==="failed");return e.jsxs(Oe,{isOpen:t,onClose:c,className:"max-w-4xl w-full max-h-[80vh] overflow-hidden flex flex-col",showCloseButton:!j,children:[e.jsx("div",{className:"px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(be,{className:"w-6 h-6 text-blue-500"}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white",children:"Generating Images"}),e.jsxs("p",{className:"text-sm text-gray-500 dark:text-gray-400 mt-1",children:["Total: ",s," image",s!==1?"s":""," in queue"]}),k&&e.jsxs("p",{className:"text-xs text-gray-400 dark:text-gray-500 mt-1",children:["Model: ",S==="openai"?"OpenAI":S==="runware"?"Runware":S||"Unknown"," ",k==="dall-e-2"?"DALL·E 2":k==="dall-e-3"?"DALL·E 3":k]})]})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto px-6 py-4",children:e.jsx("div",{className:"space-y-3",children:g.map(n=>e.jsx("div",{className:`p-4 rounded-lg border-2 transition-colors ${n.status==="processing"?"bg-blue-50 dark:bg-blue-900/20 border-blue-500":n.status==="completed"?"bg-green-50 dark:bg-green-900/20 border-green-500":n.status==="failed"?"bg-red-50 dark:bg-red-900/20 border-red-500":"bg-gray-50 dark:bg-gray-700/50 border-gray-300 dark:border-gray-600"}`,children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("span",{className:"flex items-center justify-center w-6 h-6 rounded-full bg-blue-500 text-white text-xs font-bold",children:n.index}),e.jsx("span",{className:"font-semibold text-sm text-gray-900 dark:text-white",children:n.label}),e.jsx("span",{className:"flex-1 text-xs text-gray-500 dark:text-gray-400 truncate",children:n.prompt?(()=>{const p=n.prompt.split(" "),l=p.slice(0,10).join(" ");return p.length>10?`${l}...`:n.prompt})():n.contentTitle}),e.jsxs("span",{className:"text-xs font-semibold text-gray-600 dark:text-gray-300 whitespace-nowrap flex items-center gap-1",children:[H(n.status),e.jsx("span",{children:Z(n.status)})]})]}),e.jsxs("div",{className:"relative h-5 bg-gray-200 dark:bg-gray-600 rounded-full overflow-hidden",children:[e.jsx("div",{className:`h-full ${b(n.status)} transition-all duration-150 ease-out`,style:{width:`${E[n.index]??n.progress??0}%`}}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsxs("span",{className:`text-xs font-bold ${(E[n.index]??n.progress??0)>=50?"text-white":"text-gray-700 dark:text-gray-200"}`,children:[E[n.index]??n.progress??0,"%"]})})]}),n.error&&e.jsx("div",{className:"mt-2 p-2 bg-red-100 dark:bg-red-900/30 border-l-4 border-red-500 rounded text-xs text-red-700 dark:text-red-300",children:n.error})]}),e.jsx("div",{className:"w-20 h-20 bg-gray-100 dark:bg-gray-700 rounded-lg overflow-hidden flex-shrink-0 flex items-center justify-center",children:n.status==="completed"&&n.imageUrl?e.jsx("img",{src:n.imageUrl,alt:n.label,className:"w-full h-full object-cover",onError:p=>{const l=p.target;l.style.display="none";const m=l.parentElement;m&&(m.innerHTML='<span class="text-xs text-gray-400 dark:text-gray-500">No image</span>')}}):e.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500",children:"No image"})})]})},n.index))})}),e.jsx("div",{className:"px-6 py-4 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-sm text-gray-600 dark:text-gray-400",children:[u," completed",M>0?`, ${M} failed`:""," of ",s," total"]}),V&&e.jsx("button",{onClick:c,className:"px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors",children:"Close"})]})})]})}function Qt({isOpen:t,onClose:c,onConfirm:d,title:s,recordName:_,confirmText:k="Update Status",statusOptions:S,isLoading:I=!1}){const[P,g]=a.useState(""),D=async()=>{P&&(await d(P),g(""))},E=()=>{g(""),c()};return e.jsx(Oe,{isOpen:t,onClose:E,className:"max-w-md",children:e.jsxs("div",{className:"p-6",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("div",{className:"flex items-center justify-center w-10 h-10 bg-blue-50 rounded-xl dark:bg-blue-500/10",children:e.jsx(ct,{className:"w-5 h-5 text-blue-500"})}),e.jsx("h2",{className:"text-xl font-bold text-gray-800 dark:text-white",children:s})]}),e.jsxs("p",{className:"text-gray-600 dark:text-gray-400 mb-4",children:["Update status for all images in ",e.jsx("span",{className:"font-semibold text-gray-900 dark:text-white",children:_})]}),e.jsxs("div",{className:"mb-6",children:[e.jsx(ut,{className:"mb-2",children:"New Status"}),e.jsx(Mt,{options:S,placeholder:"Select status",value:P,onChange:z=>g(z||""),className:"w-full"})]}),e.jsxs("div",{className:"flex justify-end gap-4",children:[e.jsx(Re,{variant:"outline",onClick:E,disabled:I,children:"Cancel"}),e.jsx(Re,{variant:"primary",onClick:D,disabled:I||!P,children:I?"Updating...":k})]})]})})}function Yt(){const t=_e(),c=Ke(),[d,s]=a.useState([]),_=a.useCallback(o=>{c&&s(C=>[...C,o])},[c]),[k,S]=a.useState([]),[I,P]=a.useState(!0),[g,D]=a.useState(""),[E,z]=a.useState(""),[x,Q]=a.useState([]),[W,J]=a.useState(1),[H,Z]=a.useState(1),[b,j]=a.useState(0),u=10,[M,V]=a.useState("content_title"),[n,p]=a.useState("asc"),[l,m]=a.useState(!1),[i,w]=a.useState(!1),[N,A]=a.useState([]),[y,v]=a.useState(null),[O,G]=a.useState(null),[ee,re]=a.useState(null),[he,te]=a.useState(null),[ue,F]=a.useState(!1),[ce,ge]=a.useState(null),[xe,se]=a.useState(""),[me,de]=a.useState(!1),[X,q]=a.useState(!1),[fe,h]=a.useState(null),ie=a.useCallback(async()=>{P(!0),m(!1);try{let C=(await Nt({})).results||[];g&&(C=C.filter(K=>{var le;return(le=K.content_title)==null?void 0:le.toLowerCase().includes(g.toLowerCase())})),E&&(C=C.filter(K=>K.overall_status===E)),C.sort((K,le)=>{let ae=K.content_title,$=le.content_title;return M==="overall_status"&&(ae=K.overall_status,$=le.overall_status),ae<$?n==="asc"?-1:1:ae>$?n==="asc"?1:-1:0});const U=(W-1)*u,Y=U+u,ne=C.slice(U,Y);S(ne),j(C.length),Z(Math.ceil(C.length/u)),setTimeout(()=>{m(!0),P(!1)},100)}catch(o){console.error("Error loading images:",o),t.error(`Failed to load images: ${o.message}`),m(!0),P(!1)}},[W,E,M,n,g,t]);a.useEffect(()=>{ie()},[ie]),a.useEffect(()=>{const o=setTimeout(()=>{W===1?ie():J(1)},500);return()=>clearTimeout(o)},[g,W,ie]);const Ce=(o,C)=>{V(o||"content_title"),p(C),J(1)},Ie=a.useCallback(async o=>{try{if(!o||o.length===0)throw new Error("No records selected for export");t.info("Export functionality coming soon")}catch(C){throw C}},[t]),oe=a.useCallback(async(o,C)=>{t.info(`Bulk action "${o}" for ${C.length} items`)},[t]),Te=a.useCallback(async(o,C)=>{o==="update_status"&&(ge(C.content_id),se(C.content_title||`Content #${C.content_id}`),F(!0))},[]),ye=a.useCallback(async o=>{if(ce){de(!0);try{const C=await _t(ce,o);t.success(`Successfully updated ${C.updated_count} image(s) status to ${o}`),F(!1),ge(null),se(""),ie()}catch(C){t.error(`Failed to update status: ${C.message}`)}finally{de(!1)}}},[ce,t,ie]),ke=a.useCallback((o,C)=>{var le,ae;const U=k.find($=>$.content_id===o);if(!U)return[];const Y=[];let ne=1;return((le=U.featured_image)==null?void 0:le.status)==="pending"&&((ae=U.featured_image)!=null&&ae.prompt)&&Y.push({imageId:U.featured_image.id||null,index:ne++,label:"Featured Image",type:"featured",contentTitle:U.content_title||`Content #${o}`,prompt:U.featured_image.prompt,status:"pending",progress:0,imageUrl:null,error:null}),U.in_article_images.filter($=>$.status==="pending"&&$.prompt).slice(0,C).sort(($,je)=>($.position||0)-(je.position||0)).forEach(($,je)=>{Y.push({imageId:$.id||null,index:ne++,label:`In-Article Image ${$.position||je+1}`,type:"in_article",position:$.position||je+1,contentTitle:U.content_title||`Content #${o}`,prompt:$.prompt,status:"pending",progress:0,imageUrl:null,error:null})}),Y},[k]),r=a.useCallback(async o=>{try{if(!k.find($=>$.content_id===o)){t.error("Content not found");return}let U=2,Y=null,ne=null;try{const $=await St();$.success&&$.config&&(U=$.config.max_in_article_images||2,Y=$.config.model||null,ne=$.config.provider||null)}catch($){console.warn("Failed to fetch image settings, using default:",$)}re(Y),te(ne);const K=ke(o,U);if(K.length===0){t.info("No pending images with prompts found for this content");return}A(K),v(o),w(!0);const le=K.map($=>$.imageId).filter($=>$!==null);console.log("[Generate Images] Stage 1 Complete: Modal opened with",K.length,"images"),console.log("[Generate Images] Image IDs to generate:",le),console.log("[Generate Images] Max in-article images from settings:",U),_({timestamp:new Date().toISOString(),type:"request",action:"generate_images",data:{imageIds:le,contentId:o,totalImages:le.length}});const ae=await Ct(le,o);ae.success&&ae.task_id?(G(ae.task_id),console.log("[Generate Images] Stage 2: Task started with ID:",ae.task_id),_({timestamp:new Date().toISOString(),type:"step",action:"generate_images",stepName:"Task Queued",data:{task_id:ae.task_id,message:"Image generation task queued"}})):(t.error(ae.error||"Failed to start image generation"),w(!1),G(null),_({timestamp:new Date().toISOString(),type:"error",action:"generate_images",data:{error:ae.error||"Failed to start image generation"}}))}catch(C){console.error("[Generate Images] Exception:",C),t.error(`Failed to initialize image generation: ${C.message}`)}},[t,k,ke]),f=a.useCallback(o=>{if(!o||!o.image_path||!(Y=>Y.startsWith("http://")||Y.startsWith("https://")?!1:Y.includes("ai-images"))(o.image_path))return null;if(o.image_path.includes("ai-images")){const Y=o.image_path.split("ai-images/")[1]||o.image_path.split("ai-images\\")[1];if(Y)return`/images/ai-images/${Y}`}if(o.image_path.startsWith("/images/"))return o.image_path;const U=o.image_path.split("/").pop()||o.image_path.split("\\").pop();return U?`/images/ai-images/${U}`:null},[]),T=a.useCallback((o,C,U)=>{const Y=k.find(K=>K.content_id===o);if(!Y)return;let ne=null;if(C==="featured"&&Y.featured_image?ne=Y.featured_image:C==="in_article"&&U&&(ne=Y.in_article_images.find(K=>K.position===U)||null),ne&&ne.status==="generated"){const K=f(ne);K&&(h(K),q(!0))}},[k,f]),R=a.useMemo(()=>{if(k.length===0)return 5;const o=Math.max(...k.map(C=>C.in_article_images.length));return Math.max(o,5)},[k]),L=a.useMemo(()=>Pt({searchTerm:g,setSearchTerm:D,statusFilter:E,setStatusFilter:z,setCurrentPage:J,maxInArticleImages:R,onGenerateImages:r,onImageClick:T}),[g,E,R,r,T]),B=a.useMemo(()=>L!=null&&L.headerMetrics?L.headerMetrics.map(o=>({label:o.label,value:o.calculate({images:k,totalCount:b}),accentColor:o.accentColor})):[],[L==null?void 0:L.headerMetrics,k,b]);return e.jsxs(e.Fragment,{children:[e.jsx(Se,{title:"Content Images",badge:{icon:e.jsx(be,{}),color:"orange"}}),e.jsx($e,{columns:L.columns,data:k,loading:I,showContent:l,filters:L.filters,filterValues:{search:g,status:E},onFilterChange:(o,C)=>{const U=C==null?"":String(C);o==="search"?D(U):o==="status"&&z(U),J(1)},onBulkExport:Ie,onBulkAction:oe,getItemDisplayName:o=>o.content_title||`Content #${o.content_id}`,onExport:async()=>{t.info("Export functionality coming soon")},onExportIcon:e.jsx(Ge,{}),selectionLabel:"content",pagination:{currentPage:W,totalPages:H,totalCount:b,onPageChange:J},selection:{selectedIds:x,onSelectionChange:Q},sorting:{sortBy:M,sortDirection:n,onSort:Ce},headerMetrics:B,onFilterReset:()=>{D(""),z(""),J(1)},onRowAction:Te}),e.jsx(Vt,{isOpen:i,onClose:()=>{w(!1),A([]),v(null),G(null),re(null),te(null),ie()},queue:N,totalImages:N.length,taskId:O,model:ee||void 0,provider:he||void 0,onUpdateQueue:A,onLog:_}),e.jsx(Qt,{isOpen:ue,onClose:()=>{F(!1),ge(null),se("")},onConfirm:ye,title:"Update Image Status",recordName:xe,statusOptions:[{value:"pending",label:"Pending"},{value:"generated",label:"Generated"},{value:"failed",label:"Failed"}],isLoading:me}),e.jsx(Oe,{isOpen:X,onClose:()=>{q(!1),h(null)},className:"max-w-[800px] w-full mx-4",children:fe&&e.jsx("div",{className:"p-6",children:e.jsx("img",{src:fe,alt:"Content image",className:"w-full h-auto object-contain rounded-lg",style:{maxHeight:"90vh"}})})}),c&&d.length>0&&e.jsxs("div",{className:"mt-6 bg-gray-50 dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h3",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"AI Function Logs"}),e.jsx("button",{onClick:()=>s([]),className:"text-xs text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200",children:"Clear Logs"})]}),e.jsx("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:d.slice().reverse().map((o,C)=>e.jsxs("div",{className:`p-3 rounded border text-xs font-mono ${o.type==="request"?"bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800":o.type==="success"?"bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800":o.type==="error"?"bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800":"bg-purple-50 dark:bg-purple-900/20 border-purple-200 dark:border-purple-800"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:`font-semibold ${o.type==="request"?"text-blue-700 dark:text-blue-300":o.type==="success"?"text-green-700 dark:text-green-300":o.type==="error"?"text-red-700 dark:text-red-300":"text-purple-700 dark:text-purple-300"}`,children:["[",o.type.toUpperCase(),"]"]}),e.jsx("span",{className:"text-gray-700 dark:text-gray-300",children:o.action}),o.stepName&&e.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-gray-200 dark:bg-gray-700 text-gray-600 dark:text-gray-400",children:o.stepName}),o.percentage!==void 0&&e.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:[o.percentage,"%"]})]}),e.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:new Date(o.timestamp).toLocaleTimeString()})]}),e.jsx("pre",{className:"text-xs text-gray-700 dark:text-gray-300 whitespace-pre-wrap break-words",children:JSON.stringify(o.data,null,2)})]},C))})]})]})}const ms=Object.freeze(Object.defineProperty({__proto__:null,default:Yt},Symbol.toStringTag,{value:"Module"}));function Jt(){return e.jsx(De,{})}const ps=Object.freeze(Object.defineProperty({__proto__:null,default:Jt},Symbol.toStringTag,{value:"Module"}));export{cs as C,is as D,ms as I,ps as P,ds as T,us as a,gs as b};