- Added primary_keyword, secondary_keywords, tags, and categories fields to Tasks model - Updated generate_content function to handle full JSON response with all SEO fields - Improved progress bar animation: smooth 1% increments every 300ms - Enhanced step detection for content generation vs clustering vs ideas - Fixed progress modal to show correct messages for each function type - Added comprehensive logging to Keywords and Tasks pages for AI functions - Fixed error handling to show meaningful error messages instead of generic failures
4 lines
98 KiB
JavaScript
4 lines
98 KiB
JavaScript
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/js/page-dashboard-DxYTR5eF.js","assets/js/vendor-react-core-DjsjKnCi.js","assets/js/vendor-other-CdRIx1s3.js","assets/css/vendor-other-BsM4JrO0.css","assets/js/page-analytics.tsx-1KCk8AGD.js","assets/js/vendor-helmet-MZDArkdS.js","assets/js/vendor-state-CYwAWrAU.js"])))=>i.map(i=>d[i]);
|
|
import{r,j as e,R as je}from"./vendor-react-core-DjsjKnCi.js";import{u as Vt,L as Ae,a as Ut}from"./vendor-react-router-BJY_70Cr.js";import{P as Ht,C as Ke}from"./page-analytics.tsx-1KCk8AGD.js";import{f as Ft,g as Rt,b as pt,h as qt,S as Wt,i as Gt,c as Jt,j as xt,k as Pt,B as ye,L as et,l as Qt,m as Yt,n as Xt,I as Zt,C as At,o as Ve,p as es,q as ts,a as yt}from"./page-authpages-CY7hjDHU.js";import{g as Tt,_ as Me,h as ss,i as rs,A as bt,j as as,k as ns,l as os,m as ls,n as is,a as ft,o as tt,u as cs,p as ds,q as us,r as Lt,s as ms,t as gs,v as fs,w as hs,x as ps,y as xs,z as Ot,B as ys,C as bs,D as ws,E as vs,F as ks}from"./page-dashboard-DxYTR5eF.js";import{e as wt,h as vt,j as js,B as ut,g as Ss}from"./page-clusters.config.tsx-9GAd-_h-.js";import{u as Ue}from"./page-reference-aC0iABvU.js";import{M as He,D as ht,a as st,A as Ns}from"./page-components.tsx-DYfg5dka.js";import{c as Cs}from"./page-keywords.config.tsx-CxJn1kF1.js";import{c as _s}from"./page-ideas.config.tsx-Cr6kWRFa.js";import{g as Is}from"./page-delete-modal.config.ts-B7nUJ-QI.js";import{g as Es}from"./page-bulk-action-modal.config.ts-D-0XtKwF.js";import{g as Ms}from"./page-table-actions.config.tsx-BSR5Zo7l.js";import{c as kt,p as jt}from"./vendor-state-CYwAWrAU.js";const zt=r.createContext(void 0),$s=()=>{const t=r.useContext(zt);if(!t)throw new Error("useHeaderMetrics must be used within a HeaderMetricsProvider");return t},pr=({children:t})=>{const[s,a]=r.useState([]),l=()=>{a([])};return e.jsx(zt.Provider,{value:{metrics:s,setMetrics:a,clearMetrics:l},children:t})},St=kt()(jt((t,s)=>({activeSite:null,loading:!1,error:null,setActiveSite:a=>{if(t({activeSite:a,error:null}),typeof window<"u")try{const l=s();localStorage.setItem("site-storage",JSON.stringify({state:{activeSite:a},version:0}))}catch(l){console.warn("Failed to persist site to localStorage:",l)}window.dispatchEvent(new CustomEvent("siteChanged",{detail:{siteId:a==null?void 0:a.id}})),a&&typeof window<"u"&&Me(async()=>{const{useSectorStore:l}=await Promise.resolve().then(()=>As);return{useSectorStore:l}},void 0).then(({useSectorStore:l})=>{l.getState().loadSectorsForSite(a.id)}).catch(()=>{})},loadActiveSite:async()=>{t({loading:!0,error:null});try{const l=(await Tt()).results||[],c=l.filter(d=>d.is_active),f=s().activeSite;let m=null;if(f){const d=l.find(h=>h.id===f.id);d&&d.is_active?m=d:(d&&d.is_active,m=c.length>0?c[0]:null)}else c.length>0&&(m=c[0]);if(t({activeSite:m,loading:!1}),m&&typeof window<"u")try{localStorage.setItem("site-storage",JSON.stringify({state:{activeSite:m},version:0}))}catch(d){console.warn("Failed to persist site to localStorage:",d)}}catch(a){t({error:a.message||"Failed to load active site",loading:!1})}},refreshActiveSite:async()=>{const a=s().activeSite;if(!a){await s().loadActiveSite();return}t({loading:!0,error:null});try{const c=((await Tt()).results||[]).find(f=>f.id===a.id);c&&c.is_active?t({activeSite:c,loading:!1}):await s().loadActiveSite()}catch(l){t({error:l.message||"Failed to refresh active site",loading:!1})}}}),{name:"site-storage",partialize:t=>({activeSite:t.activeSite})})),Oe=kt()(jt((t,s)=>({activeSector:null,sectors:[],loading:!1,error:null,setActiveSector:a=>{if(t({activeSector:a,error:null}),typeof window<"u")try{const l=s();localStorage.setItem("sector-storage",JSON.stringify({state:{activeSector:a},version:0}))}catch(l){console.warn("Failed to persist sector to localStorage:",l)}window.dispatchEvent(new CustomEvent("sectorChanged",{detail:{sectorId:a==null?void 0:a.id,siteId:a==null?void 0:a.site_id}}))},loadSectorsForSite:async a=>{t({loading:!0,error:null});try{if(!a)return t({sectors:[],loading:!1}),[];const c=(await ss(a)).map(m=>({id:m.id,name:m.name,slug:m.slug,site_id:a,is_active:m.is_active!==!1,industry_sector:m.industry_sector||null}));t({sectors:c,loading:!1});const f=s().activeSector;if(f&&f.site_id!==a){if(t({activeSector:null}),typeof window<"u")try{localStorage.setItem("sector-storage",JSON.stringify({state:{activeSector:null},version:0}))}catch(m){console.warn("Failed to persist sector to localStorage:",m)}window.dispatchEvent(new CustomEvent("sectorChanged",{detail:{sectorId:null,siteId:a}}))}else if(f&&f.site_id===a&&!c.find(d=>d.id===f.id)){if(t({activeSector:null}),typeof window<"u")try{localStorage.setItem("sector-storage",JSON.stringify({state:{activeSector:null},version:0}))}catch(d){console.warn("Failed to persist sector to localStorage:",d)}window.dispatchEvent(new CustomEvent("sectorChanged",{detail:{sectorId:null,siteId:a}}))}return c}catch(l){return l.status===403||l.status===404?(console.warn(`Cannot load sectors for site ${a}: site may be inactive or inaccessible`),t({sectors:[],activeSector:null,loading:!1,error:null}),[]):(t({error:l.message||"Failed to load sectors",loading:!1}),[])}},clearActiveSector:()=>{if(t({activeSector:null,sectors:[],error:null}),typeof window<"u")try{localStorage.setItem("sector-storage",JSON.stringify({state:{activeSector:null},version:0}))}catch(a){console.warn("Failed to persist sector to localStorage:",a)}}}),{name:"sector-storage",partialize:t=>({activeSector:t.activeSector})})),As=Object.freeze(Object.defineProperty({__proto__:null,useSectorStore:Oe},Symbol.toStringTag,{value:"Module"})),Le=({value:t,color:s="primary",size:a="md",showLabel:l=!1,label:c,className:f=""})=>{const m={sm:"h-1",md:"h-2",lg:"h-3"},d={primary:"bg-brand-500",success:"bg-success-500",error:"bg-error-500",warning:"bg-warning-500",info:"bg-blue-light-500"},h=Math.min(100,Math.max(0,t));return e.jsxs("div",{className:f,children:[l&&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:c||`${h}%`}),e.jsxs("span",{className:"text-sm text-gray-500 dark:text-gray-400",children:[h,"%"]})]}),e.jsx("div",{className:`w-full rounded-full bg-gray-200 dark:bg-gray-700 ${m[a]}`,children:e.jsx("div",{className:`rounded-full transition-all duration-300 ${m[a]} ${d[s]}`,style:{width:`${h}%`}})})]})};function Ts(){const t=Vt(),s={keywords:245,clusters:18,ideas:52,mappedKeywords:180,clustersWithIdeas:12,queuedIdeas:35},a=Math.round(s.mappedKeywords/s.keywords*100),l=Math.round(s.clustersWithIdeas/s.clusters*100),c=Math.round(s.queuedIdeas/s.ideas*100),f=[{number:1,title:"Add Keywords",status:"completed",count:s.keywords,path:"/planner/keywords"},{number:2,title:"Select Sector",status:"completed",count:null,path:"/planner"},{number:3,title:"Auto Cluster",status:"pending",count:s.clusters,path:"/planner/clusters"},{number:4,title:"Generate Ideas",status:"pending",count:s.ideas,path:"/planner/ideas"}],m=[{name:"SEO Optimization",volume:45800,keywords:24},{name:"Content Marketing",volume:32100,keywords:18},{name:"Link Building",volume:28700,keywords:15},{name:"Keyword Research",volume:24100,keywords:12},{name:"Analytics",volume:18900,keywords:9}],d=[{status:"New",count:20,color:"blue"},{status:"Scheduled",count:15,color:"amber"},{status:"Published",count:17,color:"green"}],h=[{text:"65 keywords unmapped",action:"Map Keywords",path:"/planner/keywords"},{text:"6 clusters without ideas",action:"Generate Ideas",path:"/planner/ideas"},{text:"17 ideas not queued to writer",action:"Queue to Writer",path:"/writer/tasks"}];return e.jsxs(e.Fragment,{children:[e.jsx(Ht,{title:"Planner Dashboard - IGNY8",description:"Content planning overview"}),e.jsxs("div",{className:"space-y-5 sm:space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-4 md:gap-6",children:[e.jsxs(Ae,{to:"/planner/keywords",className:"rounded-2xl border border-gray-200 bg-white p-5 dark:border-gray-800 dark:bg-white/[0.03] md:p-6 hover:shadow-md transition-shadow cursor-pointer group relative overflow-hidden",children:[e.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-1 bg-brand-500"}),e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400",children:"Keywords Ready"}),e.jsx("h4",{className:"mt-2 font-bold text-gray-800 text-title-sm dark:text-white/90",children:s.keywords.toLocaleString()}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1",children:"Research, analyze, and manage keywords strategy"})]}),e.jsx("div",{className:"flex items-center justify-center w-12 h-12 bg-blue-50 rounded-xl dark:bg-blue-500/10 group-hover:bg-blue-100 dark:group-hover:bg-blue-500/20 transition-colors",children:e.jsx(Ft,{className:"text-brand-500 size-6"})})]})]}),e.jsxs(Ae,{to:"/planner/clusters",className:"rounded-2xl border border-gray-200 bg-white p-5 dark:border-gray-800 dark:bg-white/[0.03] md:p-6 hover:shadow-md transition-shadow cursor-pointer group relative overflow-hidden",children:[e.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-1 bg-success-500"}),e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400",children:"Clusters Built"}),e.jsx("h4",{className:"mt-2 font-bold text-gray-800 text-title-sm dark:text-white/90",children:s.clusters.toLocaleString()}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1",children:"Organize keywords into strategic topical clusters"})]}),e.jsx("div",{className:"flex items-center justify-center w-12 h-12 bg-green-50 rounded-xl dark:bg-green-500/10 group-hover:bg-green-100 dark:group-hover:bg-green-500/20 transition-colors",children:e.jsx(Rt,{className:"text-success-500 size-6"})})]})]}),e.jsxs(Ae,{to:"/planner/ideas",className:"rounded-2xl border border-gray-200 bg-white p-5 dark:border-gray-800 dark:bg-white/[0.03] md:p-6 hover:shadow-md transition-shadow cursor-pointer group relative overflow-hidden",children:[e.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-1 bg-warning-500"}),e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400",children:"Ideas Generated"}),e.jsx("h4",{className:"mt-2 font-bold text-gray-800 text-title-sm dark:text-white/90",children:s.ideas.toLocaleString()}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1",children:"Generate creative content ideas based on semantic strategy"})]}),e.jsx("div",{className:"flex items-center justify-center w-12 h-12 bg-amber-50 rounded-xl dark:bg-amber-500/10 group-hover:bg-amber-100 dark:group-hover:bg-amber-500/20 transition-colors",children:e.jsx(pt,{className:"text-warning-500 size-6"})})]})]}),e.jsxs(Ae,{to:"/planner/keywords",className:"rounded-2xl border border-gray-200 bg-white p-5 dark:border-gray-800 dark:bg-white/[0.03] md:p-6 hover:shadow-md transition-shadow cursor-pointer group relative overflow-hidden",children:[e.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-1 bg-purple-500"}),e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400",children:"Mapped Keywords"}),e.jsx("h4",{className:"mt-2 font-bold text-gray-800 text-title-sm dark:text-white/90",children:s.mappedKeywords.toLocaleString()}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1",children:"Keywords successfully mapped to content pages"})]}),e.jsx("div",{className:"flex items-center justify-center w-12 h-12 bg-purple-50 rounded-xl dark:bg-purple-500/10 group-hover:bg-purple-100 dark:group-hover:bg-purple-500/20 transition-colors",children:e.jsx(qt,{className:"text-purple-500 size-6"})})]})]})]}),e.jsx(Ke,{title:"Planner Workflow Steps",desc:"Track your planning progress",children:e.jsx("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4",children:f.map(u=>e.jsxs(Ae,{to:u.path,className:"rounded-xl border border-gray-200 bg-gray-50 p-4 dark:border-gray-800 dark:bg-gray-900/50 hover:border-brand-300 hover:bg-brand-50 dark:hover:bg-brand-500/10 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[e.jsx("div",{className:"flex items-center justify-center w-8 h-8 bg-white border-2 border-gray-300 rounded-full text-sm font-semibold text-gray-600 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-400",children:u.number}),e.jsx("h4",{className:"font-medium text-gray-800 dark:text-white/90",children:u.title})]}),e.jsx("div",{className:"flex items-center justify-between text-sm",children:e.jsx("div",{className:"flex items-center gap-1.5",children:u.status==="completed"?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"size-4 text-success-500"}),e.jsx("span",{className:"text-gray-600 dark:text-gray-300 font-medium",children:"Completed"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Gt,{className:"size-4 text-amber-500"}),e.jsx("span",{className:"text-gray-600 dark:text-gray-300 font-medium",children:"Pending"})]})})}),u.count!==null&&e.jsxs("p",{className:"mt-2 text-xs text-gray-600 dark:text-gray-400",children:[u.count," ",u.title.includes("Keywords")?"keywords":u.title.includes("Clusters")?"clusters":"ideas"," ",u.status==="completed"?"added":""]}),u.status==="pending"&&e.jsx("button",{type:"button",onClick:g=>{g.preventDefault(),g.stopPropagation(),t(u.path)},className:"mt-3 inline-block text-xs font-medium text-brand-500 hover:text-brand-600 cursor-pointer",children:"Start Now →"})]},u.number))})}),e.jsxs("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-3",children:[e.jsx(Ke,{title:"Progress & Readiness Summary",desc:"Planning workflow progress tracking",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:"Keyword Mapping"}),e.jsxs("span",{className:"text-sm font-semibold text-gray-800 dark:text-white/90",children:[a,"%"]})]}),e.jsx(Le,{value:a,color:"primary",size:"md"}),e.jsxs("p",{className:"mt-1 text-xs text-gray-500 dark:text-gray-400",children:[s.mappedKeywords," of ",s.keywords," keywords mapped"]})]}),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:"Clusters With Ideas"}),e.jsxs("span",{className:"text-sm font-semibold text-gray-800 dark:text-white/90",children:[l,"%"]})]}),e.jsx(Le,{value:l,color:"success",size:"md"}),e.jsxs("p",{className:"mt-1 text-xs text-gray-500 dark:text-gray-400",children:[s.clustersWithIdeas," of ",s.clusters," clusters have ideas"]})]}),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:"Ideas Queued to Writer"}),e.jsxs("span",{className:"text-sm font-semibold text-gray-800 dark:text-white/90",children:[c,"%"]})]}),e.jsx(Le,{value:c,color:"warning",size:"md"}),e.jsxs("p",{className:"mt-1 text-xs text-gray-500 dark:text-gray-400",children:[s.queuedIdeas," of ",s.ideas," ideas queued"]})]})]})}),e.jsx(Ke,{title:"Top 5 Clusters by Volume",desc:"Highest volume keyword clusters",className:"lg:col-span-1",children:e.jsx("div",{className:"space-y-4",children:m.map((u,g)=>{const n=m[0].volume,j=Math.round(u.volume/n*100);return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-sm font-medium text-gray-800 dark:text-white/90",children:u.name}),e.jsx("span",{className:"text-sm font-semibold text-gray-600 dark:text-gray-400",children:u.volume.toLocaleString()})]}),e.jsx(Le,{value:j,color:g%2===0?"primary":"success",size:"sm"})]},g)})})}),e.jsx(Ke,{title:"Ideas by Status",desc:"Content ideas workflow status",className:"lg:col-span-1",children:e.jsx("div",{className:"space-y-4",children:d.map((u,g)=>{const n=d.reduce((O,P)=>O+P.count,0),j=Math.round(u.count/n*100);return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-sm font-medium text-gray-800 dark:text-white/90",children:u.status}),e.jsx("span",{className:"text-sm font-semibold text-gray-600 dark:text-gray-400",children:u.count})]}),e.jsx(Le,{value:j,color:u.color==="blue"?"primary":u.color==="amber"?"warning":"success",size:"sm"})]},g)})})})]}),e.jsx(Ke,{title:"Next Actions",desc:"Actionable items requiring attention",children:e.jsx("div",{className:"space-y-3",children:h.map((u,g)=>e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg bg-gray-50 dark:bg-gray-900/50 border border-gray-200 dark:border-gray-800",children:[e.jsx("span",{className:"text-sm text-gray-700 dark:text-gray-300",children:u.text}),e.jsxs(Ae,{to:u.path,className:"inline-flex items-center gap-1 text-sm font-medium text-brand-500 hover:text-brand-600",children:[u.action,e.jsx(Jt,{className:"size-4"})]})]},g))})})]})]})}const xr=Object.freeze(Object.defineProperty({__proto__:null,default:Ts},Symbol.toStringTag,{value:"Module"})),Ls=({children:t,className:s})=>e.jsx("table",{className:`min-w-full w-full ${s}`,children:t}),Os=({children:t,className:s})=>e.jsx("thead",{className:s,children:t}),Fs=({children:t,className:s})=>e.jsx("tbody",{className:s,children:t}),mt=({children:t,className:s})=>e.jsx("tr",{className:s,children:t}),Te=({children:t,isHeader:s=!1,className:a})=>{const l=s?"th":"td";return e.jsx(l,{className:` ${a}`,children:t})},rt=({options:t,placeholder:s="Select an option",onChange:a,className:l="",defaultValue:c="",value:f,disabled:m=!1})=>{const d=f!==void 0,[h,u]=r.useState(!1),[g,n]=r.useState(c),j=d?f||"":g,O=r.useRef(null),P=r.useRef(null);r.useEffect(()=>{d||n(c)},[c,d]);const F=String(j||""),ne=t.find(E=>String(E.value||"")===F),b=ne?ne.label:s,q=!ne;r.useEffect(()=>{const E=A=>{O.current&&!O.current.contains(A.target)&&P.current&&!P.current.contains(A.target)&&u(!1)};if(h)return document.addEventListener("mousedown",E),()=>{document.removeEventListener("mousedown",E)}},[h]);const D=E=>{const A=E==null?"":String(E);d||n(A),a(A),u(!1)},C=E=>{E.key==="Escape"?u(!1):(E.key==="Enter"||E.key===" ")&&(E.preventDefault(),u(!h))};return e.jsxs("div",{className:`relative ${l}`,children:[e.jsxs("button",{ref:P,type:"button",onClick:()=>!m&&u(!h),disabled:m,onKeyDown:C,className:`igny8-select-styled h-9 w-full appearance-none rounded-lg border border-gray-300 bg-transparent px-3 py-2 pr-10 text-sm shadow-theme-xs focus:border-brand-300 focus:outline-hidden focus:ring-3 focus:ring-brand-500/10 dark:border-gray-700 dark:bg-gray-900 dark:focus:border-brand-800 ${q?"text-gray-400 dark:text-gray-400":"text-gray-800 dark:text-white/90"} ${h?"border-brand-300 ring-3 ring-brand-500/10 dark:border-brand-800":""} ${m?"opacity-50 cursor-not-allowed":""}`,children:[e.jsx("span",{className:"block text-left truncate",children:b}),e.jsx("span",{className:"absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none",children:e.jsx(xt,{className:`h-4 w-4 text-gray-400 transition-transform ${h?"transform rotate-180":""}`})})]}),h&&e.jsx("div",{ref:O,className:"absolute z-50 left-0 right-0 mt-1 rounded-lg border border-gray-200 bg-white shadow-theme-lg dark:border-gray-800 dark:bg-gray-dark overflow-hidden max-h-60 overflow-y-auto",children:e.jsx("div",{className:"py-1",children:t.map(E=>{const A=String(E.value||""),S=String(j||"")===A;return e.jsxs("button",{type:"button",onClick:T=>{T.preventDefault(),T.stopPropagation(),D(A)},className:`w-full text-left px-3 py-2 text-sm transition-colors flex items-center gap-2 ${S?"bg-brand-500 text-white":"text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-800"}`,children:[E.icon&&e.jsx("span",{className:"flex-shrink-0",children:E.icon}),e.jsx("span",{children:E.label})]},`option-${E.value||"empty"}-${E.label}`)})})})]})};function Rs({isOpen:t,onClose:s,onConfirm:a,title:l,message:c,confirmText:f="Export",isLoading:m=!1}){return e.jsx(He,{isOpen:t,onClose:s,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(Pt,{className:"w-5 h-5 text-blue-500"})}),e.jsx("h2",{className:"text-xl font-bold text-gray-800 dark:text-white",children:l})]}),e.jsx("p",{className:"text-gray-600 dark:text-gray-400 mb-6",children:c}),e.jsxs("div",{className:"flex justify-end gap-4",children:[e.jsx(ye,{variant:"outline",onClick:s,disabled:m,children:"Cancel"}),e.jsx(ye,{variant:"primary",onClick:a,disabled:m,children:m?"Exporting...":f})]})]})})}function Ps({isOpen:t,onClose:s,onConfirm:a,title:l,message:c,confirmText:f="Update Status",statusOptions:m,isLoading:d=!1}){const[h,u]=r.useState(""),g=async()=>{h&&(await a(h),u(""))},n=()=>{u(""),s()};return e.jsx(He,{isOpen:t,onClose:n,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(Pt,{className:"w-5 h-5 text-blue-500"})}),e.jsx("h2",{className:"text-xl font-bold text-gray-800 dark:text-white",children:l})]}),e.jsx("p",{className:"text-gray-600 dark:text-gray-400 mb-4",children:c}),e.jsxs("div",{className:"mb-6",children:[e.jsx(et,{className:"mb-2",children:"New Status"}),e.jsx(rt,{options:m,placeholder:"Select status",value:h,onChange:j=>u(j||""),className:"w-full"})]}),e.jsxs("div",{className:"flex justify-end gap-4",children:[e.jsx(ye,{variant:"outline",onClick:n,disabled:d,children:"Cancel"}),e.jsx(ye,{variant:"primary",onClick:g,disabled:d||!h,children:d?"Updating...":f})]})]})})}const zs=({currentPage:t,totalPages:s,pageSize:a,onPageChange:l,onPageSizeChange:c,className:f=""})=>{const d=(()=>{const g=[];if(s<=7)for(let n=1;n<=s;n++)g.push(n);else if(t<=3){for(let n=1;n<=5;n++)g.push(n);g.push("..."),g.push(s)}else if(t>=s-2){g.push(1),g.push("...");for(let n=s-4;n<=s;n++)g.push(n)}else{g.push(1),g.push("...");for(let n=t-1;n<=t+1;n++)g.push(n);g.push("..."),g.push(s)}return g})(),h=t===1,u=t===s;return e.jsxs("div",{className:`flex items-center gap-3 ${f}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{htmlFor:"page-size",className:"text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap",children:"Show:"}),e.jsxs("select",{id:"page-size",value:a,onChange:g=>c(Number(g.target.value)),className:"h-8 px-2 text-sm rounded-lg border border-gray-300 bg-white text-gray-700 shadow-sm hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-brand-500 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-400 dark:hover:bg-gray-700",children:[e.jsx("option",{value:10,children:"10"}),e.jsx("option",{value:20,children:"20"}),e.jsx("option",{value:50,children:"50"})]}),e.jsx("span",{className:"text-sm text-gray-500 dark:text-gray-400 whitespace-nowrap",children:"per page"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:()=>!h&&l(t-1),disabled:h,type:"button",className:"flex items-center justify-center w-7 h-7 rounded-lg border border-gray-300 bg-white text-gray-700 shadow-sm hover:bg-gray-50 hover:text-gray-900 disabled:opacity-50 disabled:cursor-not-allowed dark:border-gray-700 dark:bg-gray-800 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-gray-200 transition-colors","aria-label":"Previous page",children:e.jsx(Qt,{className:"w-4 h-4"})}),e.jsx("div",{className:"flex items-center gap-0.5",children:d.map((g,n)=>{if(g==="...")return e.jsx("span",{className:"flex items-center justify-center w-7 h-7 text-xs font-medium text-gray-700 dark:text-gray-400",children:"..."},`ellipsis-${n}`);const j=g,O=j===t;return e.jsx("button",{className:`flex items-center justify-center w-7 h-7 text-xs font-medium rounded-lg transition-colors ${O?"text-white bg-brand-500 hover:bg-brand-600 shadow-sm":"text-gray-700 hover:bg-brand-500 hover:text-white dark:text-gray-400 dark:hover:text-white dark:hover:bg-brand-500"}`,onClick:()=>l(j),type:"button","aria-label":`Go to page ${j}`,"aria-current":O?"page":void 0,children:j},j)})}),e.jsx("button",{onClick:()=>!u&&l(t+1),disabled:u,type:"button",className:"flex items-center justify-center w-7 h-7 rounded-lg border border-gray-300 bg-white text-gray-700 shadow-sm hover:bg-gray-50 hover:text-gray-900 disabled:opacity-50 disabled:cursor-not-allowed dark:border-gray-700 dark:bg-gray-800 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-gray-200 transition-colors","aria-label":"Next page",children:e.jsx(Yt,{className:"w-4 h-4"})})]})]})};function Ds(){const{activeSite:t}=St(),{activeSector:s,sectors:a,setActiveSector:l,loading:c}=Oe(),[f,m]=r.useState(!1),d=r.useRef(null);if(!t)return null;if(!c&&a.length===0)return e.jsx("div",{className:"flex items-center gap-2 px-3 py-2 text-sm text-gray-500 dark:text-gray-400",children:e.jsx("span",{children:"No sectors available"})});const h=u=>{if(u===null)l(null),m(!1);else{const g=a.find(n=>n.id===u);g&&(l(g),m(!1))}};return e.jsxs("div",{className:"relative inline-block",children:[e.jsxs("button",{ref:d,onClick:()=>m(!f),className:"flex items-center gap-2 px-3 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 dark:bg-gray-800 dark:text-gray-300 dark:border-gray-700 dark:hover:bg-gray-700 dropdown-toggle","aria-label":"Select sector",disabled:c||a.length===0,children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"})}),e.jsx("span",{className:"max-w-[150px] truncate",children:c?"Loading...":(s==null?void 0:s.name)||"All Sectors"})]}),e.jsx("svg",{className:`w-4 h-4 transition-transform ${f?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),e.jsxs(ht,{isOpen:f,onClose:()=>m(!1),anchorRef:d,placement:"bottom-right",className:"w-64 p-2 overflow-y-auto max-h-[300px]",children:[e.jsxs(st,{onItemClick:()=>h(null),className:`flex items-center gap-3 px-3 py-2 font-medium rounded-lg text-sm text-left ${s?"text-gray-700 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-400 dark:hover:bg-white/5 dark:hover:text-gray-300":"bg-blue-50 text-blue-700 dark:bg-blue-500/20 dark:text-blue-300"}`,children:[e.jsx("span",{className:"flex-1",children:"All Sectors"}),!s&&e.jsx("svg",{className:"w-4 h-4 text-blue-600 dark:text-blue-400",fill:"currentColor",viewBox:"0 0 20 20",children:e.jsx("path",{fillRule:"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z",clipRule:"evenodd"})})]}),a.map(u=>e.jsxs(st,{onItemClick:()=>h(u.id),className:`flex items-center gap-3 px-3 py-2 font-medium rounded-lg text-sm text-left ${(s==null?void 0:s.id)===u.id?"bg-blue-50 text-blue-700 dark:bg-blue-500/20 dark:text-blue-300":"text-gray-700 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-400 dark:hover:bg-white/5 dark:hover:text-gray-300"}`,children:[e.jsx("span",{className:"flex-1",children:u.name}),(s==null?void 0:s.id)===u.id&&e.jsx("svg",{className:"w-4 h-4 text-blue-600 dark:text-blue-400",fill:"currentColor",viewBox:"0 0 20 20",children:e.jsx("path",{fillRule:"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z",clipRule:"evenodd"})})]},u.id))]})]})}const qe=kt()(jt(t=>({pageSize:10,setPageSize:s=>t({pageSize:s})}),{name:"igny8-page-size"}));function Bs(t){if(!t)return"";const s=document.createElement("div");return s.innerHTML=t,s.querySelectorAll("script").forEach(c=>c.remove()),s.querySelectorAll("*").forEach(c=>{const f=c.attributes;for(let m=f.length-1;m>=0;m--){const d=f[m];d.name.startsWith("on")&&c.removeAttribute(d.name),(d.name==="href"||d.name==="src")&&d.value.startsWith("javascript:")&&c.removeAttribute(d.name)}}),s.innerHTML}function Ks(t){return t?/<[a-z][\s\S]*>/i.test(t):!1}function gt(t){if(!t)return"";let s='<div class="content-outline">';return t.introduction&&(s+='<div class="outline-intro">',typeof t.introduction=="string"?s+=`<div class="outline-paragraph">${ce(t.introduction)}</div>`:typeof t.introduction=="object"&&(t.introduction.hook&&(s+=`<div class="outline-hook"><strong>Hook:</strong> ${ce(t.introduction.hook)}</div>`),t.introduction.paragraphs&&Array.isArray(t.introduction.paragraphs)&&t.introduction.paragraphs.forEach((a,l)=>{a.details&&(s+=`<div class="outline-paragraph"><strong>Intro Paragraph ${l+1}:</strong> ${ce(a.details)}</div>`)})),s+="</div>"),t.sections&&Array.isArray(t.sections)&&t.sections.forEach(a=>{if(a){if(s+='<div class="outline-section">',a.title){const l=a.title.replace(/^H2:\s*/i,"").trim();l.toLowerCase()==="conclusion"?s+=`<h3 class="section-heading">${ce(l)}</h3>`:s+=`<h3 class="section-heading">${ce(l)}</h3>`}a.content&&(Array.isArray(a.content)?a.content.forEach(l=>{if(l.title){const c=l.title.replace(/^H3:\s*/i,"").trim();s+=`<h4 class="subsection-heading">${ce(c)}</h4>`}l.content&&(s+=`<div class="section-details">${ce(String(l.content))}</div>`)}):typeof a.content=="string"&&(s+=`<div class="section-details">${ce(a.content)}</div>`)),s+="</div>"}}),t.H2&&(Array.isArray(t.H2)?t.H2.forEach(a=>{if(a.heading||typeof a=="string"){s+='<div class="outline-section">';const l=a.heading||a;s+=`<h3 class="section-heading">${ce(l)}</h3>`,a.content_type&&(s+=`<div class="content-type-badge">${ce(a.content_type.replace("_"," ").toUpperCase())}</div>`),a.subsections&&Array.isArray(a.subsections)&&a.subsections.forEach(c=>{const f=c.subheading||c.heading||c;s+=`<h4 class="subsection-heading">${ce(f)}</h4>`,c.details&&(s+=`<div class="section-details">${ce(c.details)}</div>`)}),a.details&&(s+=`<div class="section-details">${ce(a.details)}</div>`),s+="</div>"}}):typeof t.H2=="string"?(s+='<div class="outline-section">',s+=`<h3 class="section-heading">${ce(t.H2)}</h3>`,s+="</div>"):typeof t.H2=="object"&&Object.entries(t.H2).forEach(([a,l])=>{s+='<div class="outline-section">',s+=`<h3 class="section-heading">${ce(l)}</h3>`,s+="</div>"})),t.H3&&!t.H2&&(s+='<div class="outline-section">',typeof t.H3=="string"?s+=`<h4 class="subsection-heading">${ce(t.H3)}</h4>`:typeof t.H3=="object"&&Object.entries(t.H3).forEach(([a,l])=>{s+=`<h4 class="subsection-heading">${ce(l)}</h4>`}),s+="</div>"),s+="</div>",s}function ce(t){const s=document.createElement("div");return s.textContent=t,s.innerHTML}const Vs=({content:t,className:s="",maxHeight:a})=>{const l=r.useMemo(()=>{if(!t)return'<div class="text-gray-400 italic">No content available</div>';if(typeof t=="object"&&t!==null){if(t.H2||t.H3||t.introduction||t.sections)return gt(t);try{return Object.keys(t).length>0?gt(t):ce(JSON.stringify(t,null,2))}catch{return ce(JSON.stringify(t,null,2))}}if(typeof t=="string"){try{const d=JSON.parse(t);if(typeof d=="object"&&(d.H2||d.H3||d.introduction||d.sections))return gt(d)}catch{}if(Ks(t)){const d=Bs(t);return d.trim().startsWith("<article")||d.trim().startsWith("<div")?`<div class="normalized-html-content">${d}</div>`:`<div class="normalized-html-content"><article>${d}</article></div>`}const c=t.split(`
|
|
`);let f='<div class="content-outline">',m=!1;for(const d of c){const h=d.trim();if(!h){m&&(f+="</ul>",m=!1),f+="<br>";continue}if(h.match(/^[-*]\s+/)){m||(f+='<ul class="outline-list">',m=!0);const u=h.replace(/^[-*]\s+/,"");h.startsWith(" ")||h.startsWith(" ")?f+=`<li class="outline-item nested">${ce(u)}</li>`:f+=`<li class="outline-item">${ce(u)}</li>`}else if(h.match(/^[-*]\s*H2[:]/i)){m&&(f+="</ul>",m=!1);const u=h.replace(/^[-*]\s*H2[:]\s*/i,"");f+=`<h3 class="section-heading">${ce(u)}</h3>`}else if(h.match(/^[-*]\s*H3[:]/i)){m&&(f+="</ul>",m=!1);const u=h.replace(/^[-*]\s*H3[:]\s*/i,"");f+=`<h4 class="subsection-heading">${ce(u)}</h4>`}else m&&(f+="</ul>",m=!1),f+=`<p class="outline-paragraph">${ce(h)}</p>`}return m&&(f+="</ul>"),f+="</div>",f}return ce(String(t))},[t]);return e.jsx("div",{className:`html-content-renderer ${s}`,style:a?{maxHeight:a,overflow:"auto"}:void 0,dangerouslySetInnerHTML:{__html:l}})},Us=({row:t,contentKey:s,contentLabel:a="Content",colSpan:l,isExpanded:c,defaultExpanded:f=!1,onToggle:m,className:d=""})=>{const[h,u]=r.useState(f),g=c!==void 0?c:h,[n,j]=r.useState("auto"),O=r.useRef(null);let P=t[s];(!P||typeof P=="string"&&P.trim().length===0)&&(P=t.description||t.content_outline||null);const F=P&&(typeof P=="string"?P.trim().length>0:typeof P=="object"&&P!==null&&Object.keys(P).length>0);return r.useEffect(()=>{if(g&&O.current){const ne=O.current.scrollHeight;j(ne)}else j(0)},[g,P]),!F||!g?null:e.jsx("tr",{className:`toggle-content-row expanded ${d}`,"aria-hidden":!1,children:e.jsx("td",{colSpan:l,className:"px-5 py-0 bg-gray-50 dark:bg-gray-800/50 border-b border-gray-200 dark:border-white/[0.05]",children:e.jsx("div",{ref:O,className:"overflow-hidden",children:e.jsxs("div",{className:"py-4 px-2",children:[e.jsx("div",{className:"mb-2 text-xs font-semibold uppercase text-gray-500 dark:text-gray-400 tracking-wide",children:a}),e.jsx("div",{className:"html-content-wrapper",children:e.jsx(Vs,{content:P,className:"text-sm text-gray-700 dark:text-gray-300 leading-relaxed"})})]})})})})},Hs=({isExpanded:t,onClick:s,hasContent:a,className:l=""})=>a?e.jsx("button",{type:"button",onClick:s,className:`inline-flex items-center justify-center w-8 h-8 rounded-lg transition-all duration-200 ${t?"text-blue-600 dark:text-blue-400 bg-blue-50 dark:bg-blue-900/20":"text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800"} ${l}`,"aria-label":t?"Collapse content":"Expand content","aria-expanded":t,children:e.jsx(xt,{className:`w-4 h-4 transition-transform duration-200 ${t?"rotate-180":""}`})}):e.jsx("span",{className:`inline-flex items-center justify-center w-8 h-8 text-gray-300 dark:text-gray-600 ${l}`,children:e.jsx(Xt,{className:"w-4 h-4"})});function at({title:t,titleIcon:s,subtitle:a,columns:l,data:c,loading:f=!1,showContent:m=!0,filters:d=[],filterValues:h={},onFilterChange:u,onFilterReset:g,renderFilters:n,onEdit:j,onCreate:O,createLabel:P="+ Add",onCreateIcon:F,onExportCSV:ne,onExportIcon:b,onImport:q,onImportIcon:D,headerMetrics:C=[],selectionLabel:E="items",pagination:A,selection:i,sorting:S,onDelete:T,onBulkDelete:Z,onBulkExport:M,onBulkUpdateStatus:K,onBulkAction:Q,onRowAction:Y,onExport:L,getItemDisplayName:R=re=>re.name||re.keyword||re.title||String(re.id),className:X=""}){const re=Ut(),[ie,oe]=r.useState(!1),[be,we]=r.useState(new Map),ge=je.useRef(new Map),N=je.useRef(null),w=Is(re.pathname),x=Es(re.pathname),V=Ms(re.pathname),W=(V==null?void 0:V.rowActions)||[],H=(V==null?void 0:V.bulkActions)||[],[ee,te]=r.useState((i==null?void 0:i.selectedIds)||[]),[G,fe]=r.useState(new Set),[le,J]=r.useState({isOpen:!1,items:[],isBulk:!1,isLoading:!1}),[p,_]=r.useState({isOpen:!1,itemCount:0,isLoading:!1}),[I,me]=r.useState({isOpen:!1,itemCount:0,isLoading:!1}),{setMetrics:he}=$s(),ue=Ue(),{pageSize:$,setPageSize:z}=qe(),se=i!=null&&i.selectedIds?JSON.stringify(i.selectedIds):"";r.useEffect(()=>{i!=null&&i.selectedIds&&te(i.selectedIds)},[se]);const ae=o=>{!T||!w||J({isOpen:!0,items:[o],isBulk:!1,isLoading:!1})},Ne=o=>{if(!Z||!w)return;const y=c.filter(k=>o.includes(String(k.id)));J({isOpen:!0,items:y,isBulk:!0,isLoading:!1})},Ie=async()=>{if(!(le.items.length===0||!w)){J(o=>({...o,isLoading:!0}));try{if(le.isBulk){if(Z){const o=le.items.map(U=>U.id),y=await Z(o),k=(y==null?void 0:y.deleted_count)||le.items.length;ue.success(`${k} ${w.itemNamePlural} deleted successfully`)}}else T&&(await T(le.items[0].id),ue.success(`${w.itemNameSingular.charAt(0).toUpperCase()+w.itemNameSingular.slice(1)} deleted successfully`));J({isOpen:!1,items:[],isBulk:!1,isLoading:!1}),i&&i.onSelectionChange([])}catch(o){ue.error(`Failed to delete: ${o.message}`),J(y=>({...y,isLoading:!1}))}}},We=async(o,y)=>{var k;we(U=>{const de=new Map(U);return de.set(y.id||y,!1),de}),o==="edit"&&j?j(y):o==="delete"&&T&&w?ae(y):o==="export"&&L?await L(y):Y?Y(o,y).catch(U=>{ue.error(`Action failed: ${U.message}`)}):Q?Q(o,[((k=y.id)==null?void 0:k.toString())||String(y)]):ue.info(`Action "${o}" not yet implemented`)},Ge=(o,y)=>{if(!i)return;const k=i.selectedIds.length>0?i.selectedIds:y;if(o==="delete"&&Z&&w)Ne(k);else if(o==="export"&&M&&x){const U=k.length;_({isOpen:!0,itemCount:U,isLoading:!1})}else o==="update_status"&&K&&x?me({isOpen:!0,itemCount:k.length,isLoading:!1}):Q?Q(o,k).catch(U=>{ue.error(`Bulk action failed: ${U.message}`)}):ue.info(`Bulk action "${o}" not yet implemented`);oe(!1)},nt=async()=>{if(!M||!i)return;const o=i.selectedIds.length>0?i.selectedIds:ee;_(y=>({...y,isLoading:!0}));try{await M(o),ue.success("Export successful"),_({isOpen:!1,itemCount:0,isLoading:!1}),i.onSelectionChange([])}catch(y){ue.error(`Export failed: ${y.message}`),_(k=>({...k,isLoading:!1}))}},Fe=async o=>{if(!(!K||!i)){me(y=>({...y,isLoading:!0}));try{await K(i.selectedIds,o),ue.success("Status updated successfully"),me({isOpen:!1,itemCount:0,isLoading:!1}),i.onSelectionChange([])}catch(y){ue.error(`Failed to update status: ${y.message}`),me(k=>({...k,isLoading:!1}))}}},Re=r.useRef(""),Ee=r.useRef(!1),xe=r.useMemo(()=>{if(!C||C.length===0)return"";try{return C.map(o=>`${o.label}:${String(o.value)}`).join("|")}catch{return""}},[C]);r.useEffect(()=>{if(xe!==Re.current)return xe?(he(C),Ee.current=!0,Re.current=xe):Ee.current&&(he([]),Ee.current=!1,Re.current=""),()=>{Ee.current&&(he([]),Ee.current=!1)}},[xe]);const ot=(n||d.length>0)&&Object.values(h).some(o=>o===""||o===null||o===void 0?!1:typeof o=="object"&&("min"in o||"max"in o)?o.min!==""&&o.min!==null&&o.min!==void 0||o.max!==""&&o.max!==null&&o.max!==void 0:!0),lt=o=>{if(!o.sortable||!S)return;const y=o.sortField||o.key,k=S.sortBy===y?S.sortDirection:null;let U="asc";if(k==="asc")U="desc";else if(k==="desc"){S.onSort("created_at","desc");return}S.onSort(y,U)},Je=o=>{if(!o.sortable||!S)return null;const y=o.sortField||o.key;return S.sortBy!==y?e.jsx("span",{className:"ml-1 cursor-pointer text-gray-400 hover:text-gray-600 dark:hover:text-gray-300",children:"⇅"}):S.sortDirection==="asc"?e.jsx("span",{className:"ml-1 cursor-pointer text-brand-500",children:"↑"}):e.jsx("span",{className:"ml-1 cursor-pointer text-brand-500",children:"↓"})},v=o=>{if(o){const y=c.filter(k=>!k.isAdded).map(k=>{var U;return((U=k.id)==null?void 0:U.toString())||""}).filter(k=>k!=="");te(y),i==null||i.onSelectionChange(y)}else te([]),i==null||i.onSelectionChange([])},B=(o,y)=>{const k=c.find(de=>String(de.id)===o);if(k&&k.isAdded)return;const U=y?[...ee,o]:ee.filter(de=>de!==o);te(U),i==null||i.onSelectionChange(U)};return e.jsxs("div",{className:X,children:[e.jsxs("div",{className:"flex justify-between items-center mb-6 overflow-visible",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("h2",{className:"text-xl font-semibold text-gray-800 dark:text-white/90 flex items-center gap-2",children:[s&&e.jsx("div",{className:"flex items-center justify-center w-10 h-10 bg-blue-50 rounded-xl dark:bg-blue-500/10",children:s}),t]}),a&&e.jsx("p",{className:"mt-1 text-sm text-gray-500 dark:text-gray-400",children:a})]}),e.jsx("div",{className:"flex-shrink-0 overflow-visible",children:e.jsx(Ds,{})})]}),(n||d.length>0)&&e.jsx("div",{className:"flex justify-center mb-4",children:e.jsx("div",{className:"w-[75%] igny8-filter-bar p-3 rounded-lg bg-transparent",style:{boxShadow:"0 2px 6px 3px rgba(0, 0, 0, 0.08)"},children:e.jsxs("div",{className:"flex flex-nowrap gap-3 items-center justify-between w-full",children:[e.jsx("div",{className:"flex flex-nowrap gap-3 items-center flex-1 min-w-0 w-full",children:n?e.jsx("div",{className:"flex flex-nowrap gap-3 items-center flex-1 min-w-0 w-full",children:n}):e.jsx(e.Fragment,{children:d.map(o=>{if(o.type==="custom"&&o.customRender)return e.jsx(je.Fragment,{children:o.customRender()},o.key);if(o.type==="text")return e.jsx(Zt,{type:"text",placeholder:o.placeholder||`Search ${o.label.toLowerCase()}...`,value:h[o.key]||"",onChange:y=>{u==null||u(o.key,y.target.value)},className:"flex-1 min-w-[200px] h-9"},o.key);if(o.type==="select"){const y=h[o.key]||"";return e.jsx(rt,{options:o.options||[],placeholder:o.label,value:y,onChange:k=>{const U=k==null?"":String(k);u==null||u(o.key,U)},className:o.className||"flex-1 min-w-[140px]"},o.key)}return null})})}),ot&&g&&e.jsx(ye,{variant:"secondary",size:"sm",onClick:g,className:"flex-shrink-0",children:"Clear Filters"})]})})}),e.jsxs("div",{className:"flex justify-between items-center mb-4",children:[H.length>0&&e.jsx("div",{className:"inline-block",children:H.length===1?e.jsxs(ye,{size:"md",onClick:()=>{ee.length>0&&Ge(H[0].key,ee)},disabled:ee.length===0,variant:H[0].variant==="success"?"success":(H[0].variant==="danger","primary"),startIcon:H[0].icon,className:ee.length===0?"opacity-50 cursor-not-allowed":"",children:[H[0].label,ee.length>0&&e.jsx("span",{className:"ml-2 inline-flex items-center justify-center px-2 py-0.5 text-xs font-medium rounded-full bg-white/20 text-white",children:ee.length})]}):e.jsxs(e.Fragment,{children:[e.jsxs(ye,{ref:N,size:"md",onClick:()=>ee.length>0&&oe(!ie),disabled:ee.length===0,className:`dropdown-toggle ${ee.length===0?"opacity-50 cursor-not-allowed":""}`,endIcon:e.jsx(xt,{className:"w-4 h-4"}),children:["Bulk Actions",ee.length>0&&e.jsx("span",{className:"ml-2 inline-flex items-center justify-center px-2 py-0.5 text-xs font-medium rounded-full bg-blue-100 text-blue-800 dark:bg-blue-500/20 dark:text-blue-300",children:ee.length})]}),e.jsx(ht,{isOpen:ie&&ee.length>0,onClose:()=>oe(!1),anchorRef:N,placement:"bottom-left",className:"w-48 p-2",children:H.map((o,y)=>{const k=o.key==="delete",U=k&&y>0;return e.jsxs(je.Fragment,{children:[U&&e.jsx("div",{className:"my-2 border-t border-gray-200 dark:border-gray-800"}),e.jsxs(st,{onItemClick:()=>{Ge(o.key,ee)},className:`flex items-center gap-3 px-3 py-2 font-medium rounded-lg text-sm text-left ${k?"text-error-500 hover:bg-error-50 hover:text-error-600 dark:text-error-400 dark:hover:bg-error-500/15 dark:hover:text-error-300":"text-gray-700 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-400 dark:hover:bg-white/5 dark:hover:text-gray-300"}`,children:[o.icon&&e.jsx("span",{className:"flex-shrink-0 w-5 h-5",children:o.icon}),e.jsx("span",{className:"text-left",children:o.label})]})]},o.key)})})]})}),e.jsxs("div",{className:"flex gap-2",children:[ne&&e.jsx(ye,{variant:"secondary",size:"md",endIcon:b,onClick:ne,children:"Export CSV"}),q&&e.jsx(ye,{variant:"secondary",size:"md",endIcon:D,onClick:q,children:"Import"}),O&&e.jsx(ye,{variant:"primary",size:"md",endIcon:F,onClick:O,children:P})]})]}),e.jsx("div",{className:`rounded-xl border border-gray-200 bg-white dark:border-white/[0.05] dark:bg-white/[0.03] igny8-table-container ${m?"loaded":"loading"}`,style:{overflowX:"auto",overflowY:"visible"},children:e.jsx("div",{className:"igny8-table-wrapper",style:{overflow:"visible"},children:e.jsxs(Ls,{className:"igny8-table-compact igny8-table-smooth",children:[e.jsx(Os,{className:"border-b border-gray-100 dark:border-white/[0.05]",children:e.jsxs(mt,{children:[i&&e.jsx(Te,{isHeader:!0,className:"px-5 py-3 font-medium text-gray-500 text-start text-theme-xs dark:text-gray-400 w-12",children:m&&e.jsx(At,{checked:(()=>{const o=c.filter(y=>!y.isAdded);return o.length>0&&ee.length===o.length})(),onChange:v,id:"select-all"})}),l.map((o,y)=>{const k=y===l.length-1;return e.jsx(Te,{isHeader:!0,className:`px-5 py-3 font-medium text-gray-500 text-${o.align||"start"} text-theme-xs dark:text-gray-400 ${o.sortable?"cursor-pointer hover:text-gray-700 dark:hover:text-gray-300":""} ${k&&W.length>0?"pr-16":""}`,children:o.sortable?e.jsxs("div",{onClick:()=>lt(o),className:"flex items-center",children:[o.label,Je(o)]}):e.jsxs(e.Fragment,{children:[o.label,Je(o)]})},o.key)})]})}),e.jsx(Fs,{className:"divide-y divide-gray-100 dark:divide-white/[0.05] igny8-table-body",children:m?c.length===0?null:c.map((o,y)=>{var Mt;const k=o.id||y,U=G.has(k),de=l.find(ve=>ve.toggleable),Pe=(de==null?void 0:de.toggleContentKey)||(de==null?void 0:de.key),Dt=(de==null?void 0:de.toggleContentLabel)||"Content",$e=Pe?o[Pe]:null,Qe=$e&&(typeof $e=="string"?$e.trim().length>0:typeof $e=="object"&&$e!==null&&Object.keys($e).length>0),Bt=(i?1:0)+l.length,It=(ve,Ce)=>{fe(ze=>{const ke=new Set(ze),De=Ce??k;return ve?ke.add(De):ke.delete(De),ke})},Et=!!o.isAdded;return e.jsxs(je.Fragment,{children:[e.jsxs(mt,{className:`igny8-data-row ${Et?"bg-blue-50 dark:bg-blue-500/10":""}`,children:[i&&e.jsx(Te,{className:"px-5 py-4 text-start",children:e.jsx(At,{checked:ee.includes(((Mt=o.id)==null?void 0:Mt.toString())||""),onChange:ve=>{var Ce;return B(((Ce=o.id)==null?void 0:Ce.toString())||"",ve)},id:`checkbox-${o.id}`,disabled:Et})}),l.map((ve,Ce)=>{var De;const ze=Ce===l.length-1,ke=o.id||y;if(ze&&W.length>0&&!ge.current.has(ke)){const Be=je.createRef();ge.current.set(ke,Be)}return e.jsxs(Te,{className:`px-5 py-4 text-${ve.align||"start"} text-gray-800 dark:text-white/90 ${ze&&W.length>0?"relative pr-16":""}`,children:[e.jsxs("div",{className:`flex items-center ${ve.toggleable&&Qe?"justify-between w-full":""} gap-2`,children:[e.jsx("div",{className:"flex-1",children:ve.render?ve.render(o[ve.key],o):e.jsx("span",{children:((De=o[ve.key])==null?void 0:De.toString())||"-"})}),ve.toggleable&&Qe&&e.jsx("div",{onClick:Be=>Be.stopPropagation(),children:e.jsx(Hs,{isExpanded:U,onClick:()=>{It(!U,k)},hasContent:Qe})})]}),ze&&W.length>0&&(()=>{const Be=!!o.isAdded;if(W.length===1){const pe=W[0];return Be?e.jsx("div",{className:"absolute right-2 top-1/2 -translate-y-1/2 z-10",children:e.jsx("span",{className:"text-sm font-medium text-blue-light-500 dark:text-blue-light-400",children:"Added"})}):e.jsx("div",{className:"absolute right-2 top-1/2 -translate-y-1/2 z-10",children:e.jsxs("button",{type:"button",onClick:Se=>{Se.stopPropagation(),We(pe.key,o)},className:"flex items-center gap-1 text-sm font-medium text-success-500 hover:text-success-600 dark:text-success-400 dark:hover:text-success-300 transition-colors cursor-pointer",children:[pe.label,e.jsx("span",{className:"inline-flex items-center",children:e.jsx(Ve,{className:"w-4 h-4 fill-current"})})]})})}const it=ge.current.get(ke);if(!it)return null;const Kt=be.get(ke)||!1;return e.jsxs(e.Fragment,{children:[e.jsx("button",{ref:it,type:"button",onClick:pe=>{pe.stopPropagation(),we(Se=>{const _e=new Map(Se);return _e.forEach((ct,Ye)=>{Ye!==ke&&_e.set(Ye,!1)}),_e.set(ke,!_e.get(ke)),_e})},className:"absolute right-2 top-1/2 -translate-y-1/2 inline-flex items-center justify-center w-8 h-8 rounded-lg transition-colors text-gray-500 hover:text-gray-700 hover:bg-gray-100 dark:text-gray-400 dark:hover:text-gray-300 dark:hover:bg-gray-800 dropdown-toggle z-10",title:"Actions",children:e.jsx(es,{className:"w-5 h-5"})}),e.jsx(ht,{isOpen:Kt,onClose:()=>{we(pe=>{const Se=new Map(pe);return Se.set(ke,!1),Se})},anchorRef:it,placement:"right",className:"w-48 p-2",children:W.map(pe=>{const Se=pe.key==="edit",_e=pe.key==="delete",ct=pe.key==="export",Ye=()=>{var $t;if(!pe.icon)return null;const Xe=pe.icon,Ze=(($t=Xe.props)==null?void 0:$t.className)||"",dt=Ze.includes("w-")?"":"w-5 h-5 ";return Se?je.cloneElement(Xe,{className:`${dt}text-blue-light-500 ${Ze}`.trim()}):_e?je.cloneElement(Xe,{className:`${dt}text-error-500 ${Ze}`.trim()}):ct?je.cloneElement(Xe,{className:`${dt}text-gray-600 dark:text-gray-400 ${Ze}`.trim()}):pe.icon};return e.jsxs(je.Fragment,{children:[e.jsxs(st,{onItemClick:()=>We(pe.key,o),className:`flex items-center gap-3 px-3 py-2 font-medium rounded-lg text-sm text-left ${Se?"text-blue-light-500 hover:bg-blue-light-50 hover:text-blue-light-600 dark:text-blue-light-400 dark:hover:bg-blue-light-500/15 dark:hover:text-blue-light-300":_e?"text-error-500 hover:bg-error-50 hover:text-error-600 dark:text-error-400 dark:hover:bg-error-500/15 dark:hover:text-error-300":"text-gray-700 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-400 dark:hover:bg-white/5 dark:hover:text-gray-300"}`,children:[e.jsx("span",{className:"flex-shrink-0 w-5 h-5",children:Ye()}),e.jsx("span",{className:"text-left",children:pe.label})]}),ct&&e.jsx("div",{className:"my-2 border-t border-gray-200 dark:border-gray-800"})]},pe.key)})})]})})()]},ve.key)})]}),de&&Qe&&e.jsx(Us,{row:o,contentKey:Pe||"",contentLabel:Dt,colSpan:Bt,isExpanded:U,onToggle:It})]},o.id||y)}):Array.from({length:10}).map((o,y)=>e.jsxs(mt,{className:"igny8-skeleton-row",children:[i&&e.jsx(Te,{children:e.jsx("div",{className:"h-4 bg-gray-200 dark:bg-gray-700 rounded animate-pulse"})}),l.map((k,U)=>e.jsx(Te,{children:e.jsx("div",{className:"h-4 bg-gray-200 dark:bg-gray-700 rounded animate-pulse"})},U))]},`skeleton-${y}`))})]})})}),w&&e.jsx(Ns,{isOpen:le.isOpen,onClose:()=>J({isOpen:!1,items:[],isBulk:!1,isLoading:!1}),onConfirm:Ie,title:w.title,message:le.isBulk?w.multipleItemsMessage(le.items.length):w.singleItemMessage,variant:"danger",isConfirmation:!0,confirmText:"Delete",cancelText:"Cancel",isLoading:le.isLoading,itemsList:le.items.map(o=>R(o))}),x&&e.jsx(Rs,{isOpen:p.isOpen,onClose:()=>_({isOpen:!1,itemCount:0,isLoading:!1}),onConfirm:nt,title:x.export.title,message:x.export.message(p.itemCount),confirmText:x.export.confirmText,isLoading:p.isLoading}),x&&e.jsx(Ps,{isOpen:I.isOpen,onClose:()=>me({isOpen:!1,itemCount:0,isLoading:!1}),onConfirm:Fe,title:x.updateStatus.title,message:x.updateStatus.message(I.itemCount),confirmText:x.updateStatus.confirmText,statusOptions:x.updateStatus.statusOptions,isLoading:I.isLoading}),A&&e.jsx("div",{className:"mt-6 border-t border-gray-200 dark:border-gray-800 pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:["Showing ",c.length," of ",A.totalCount," ",E||"items"]}),e.jsx(zs,{currentPage:A.currentPage,totalPages:A.totalPages,pageSize:$,onPageChange:o=>{A.onPageChange(o)},onPageSizeChange:o=>{z(o),A.onPageChange(1)}})]})})]})}function Nt({isOpen:t,onClose:s,onSubmit:a,title:l,fields:c=[],submitLabel:f="Create",cancelLabel:m="Cancel",isLoading:d=!1,className:h="max-w-2xl",customFooter:u,customBody:g}){return e.jsx(He,{isOpen:t,onClose:s,className:h,children:e.jsxs("div",{className:"p-6",children:[e.jsx("h3",{className:"text-lg font-semibold mb-6 text-gray-800 dark:text-white",children:l}),e.jsxs("form",{onSubmit:n=>{n.preventDefault(),a()},className:"space-y-4",children:[g||e.jsxs(e.Fragment,{children:[c.find(n=>n.key==="keyword")&&e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:[c.find(n=>n.key==="keyword").label,c.find(n=>n.key==="keyword").required&&e.jsx("span",{className:"text-error-500 ml-1",children:"*"})]}),e.jsx("input",{type:"text",className:"h-9 w-full rounded-lg border border-gray-300 bg-transparent px-3 py-2 text-sm shadow-theme-xs text-gray-800 placeholder:text-gray-400 focus:border-brand-300 focus:outline-hidden focus:ring-3 focus:ring-brand-500/10 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90 dark:placeholder:text-white/30 dark:focus:border-brand-800",value:c.find(n=>n.key==="keyword").value||"",onChange:n=>c.find(j=>j.key==="keyword").onChange(n.target.value),placeholder:c.find(n=>n.key==="keyword").placeholder,required:c.find(n=>n.key==="keyword").required})]}),(c.find(n=>n.key==="volume")||c.find(n=>n.key==="difficulty"))&&e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[c.find(n=>n.key==="volume")&&e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:[c.find(n=>n.key==="volume").label,c.find(n=>n.key==="volume").required&&e.jsx("span",{className:"text-error-500 ml-1",children:"*"})]}),e.jsx("input",{type:"number",className:"h-9 w-full rounded-lg border border-gray-300 bg-transparent px-3 py-2 text-sm shadow-theme-xs text-gray-800 placeholder:text-gray-400 focus:border-brand-300 focus:outline-hidden focus:ring-3 focus:ring-brand-500/10 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90 dark:placeholder:text-white/30 dark:focus:border-brand-800",value:c.find(n=>n.key==="volume").value||"",onChange:n=>{const j=n.target.value===""?"":parseInt(n.target.value)||0;c.find(O=>O.key==="volume").onChange(j)},placeholder:c.find(n=>n.key==="volume").placeholder,required:c.find(n=>n.key==="volume").required})]}),c.find(n=>n.key==="difficulty")&&(()=>{const n=c.find(j=>j.key==="difficulty");return e.jsxs("div",{children:[e.jsxs(et,{className:"mb-2",children:[n.label,n.required&&e.jsx("span",{className:"text-error-500 ml-1",children:"*"})]}),n.type==="select"?e.jsx(rt,{options:n.options||[],placeholder:n.placeholder||n.label,value:n.value||"",onChange:j=>n.onChange(j),className:"w-full"}):e.jsx("input",{type:"number",className:"h-9 w-full rounded-lg border border-gray-300 bg-transparent px-3 py-2 text-sm shadow-theme-xs text-gray-800 placeholder:text-gray-400 focus:border-brand-300 focus:outline-hidden focus:ring-3 focus:ring-brand-500/10 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90 dark:placeholder:text-white/30 dark:focus:border-brand-800",value:n.value||"",onChange:j=>{const O=j.target.value===""?"":parseInt(j.target.value)||0;n.onChange(O)},placeholder:n.placeholder,required:n.required,min:n.min,max:n.max})]})})()]}),c.filter(n=>n.key!=="keyword"&&n.key!=="volume"&&n.key!=="difficulty").map(n=>n.type==="select"?e.jsxs("div",{children:[e.jsxs(et,{className:"mb-2",children:[n.label,n.required&&e.jsx("span",{className:"text-error-500 ml-1",children:"*"})]}),e.jsx(rt,{options:n.options||[],placeholder:n.placeholder||n.label,value:n.value||"",onChange:j=>n.onChange(j),className:"w-full"})]},n.key):n.type==="textarea"?e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:[n.label,n.required&&e.jsx("span",{className:"text-error-500 ml-1",children:"*"})]}),e.jsx("textarea",{rows:n.rows||4,className:"w-full rounded-lg border border-gray-300 bg-transparent px-3 py-2 text-sm shadow-theme-xs text-gray-800 placeholder:text-gray-400 focus:border-brand-300 focus:outline-hidden focus:ring-3 focus:ring-brand-500/10 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90 dark:placeholder:text-white/30 dark:focus:border-brand-800",value:n.value||"",onChange:j=>n.onChange(j.target.value),placeholder:n.placeholder,required:n.required})]},n.key):e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:[n.label,n.required&&e.jsx("span",{className:"text-error-500 ml-1",children:"*"})]}),e.jsx("input",{type:n.type,className:"h-9 w-full rounded-lg border border-gray-300 bg-transparent px-3 py-2 text-sm shadow-theme-xs text-gray-800 placeholder:text-gray-400 focus:border-brand-300 focus:outline-hidden focus:ring-3 focus:ring-brand-500/10 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90 dark:placeholder:text-white/30 dark:focus:border-brand-800",value:n.value||"",onChange:j=>n.onChange(j.target.value),placeholder:n.placeholder,required:n.required,min:n.min,max:n.max})]},n.key))]}),u||e.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[e.jsx(ye,{type:"button",variant:"outline",onClick:s,disabled:d,children:m}),e.jsx(ye,{type:"submit",variant:"primary",disabled:d,children:d?"Processing...":f})]})]})]})})}function Ct({isOpen:t,title:s,percentage:a,status:l,message:c,details:f,onClose:m,onCancel:d,taskId:h}){r.useEffect(()=>{if(l==="completed"&&m){const n=setTimeout(()=>{m()},2e3);return()=>clearTimeout(n)}},[l,m]);const u=()=>l==="error"?"error":l==="completed"?"success":"primary",g=()=>l==="completed"?e.jsx("svg",{className:"w-6 h-6 text-success-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}):l==="error"?e.jsx("svg",{className:"w-6 h-6 text-error-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}):e.jsxs("svg",{className:"w-6 h-6 text-brand-500 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"})]});return e.jsx(He,{isOpen:t,onClose:m||(()=>{}),className:"max-w-lg",showCloseButton:l==="completed"||l==="error",children:e.jsxs("div",{className:"p-6",children:[e.jsxs("div",{className:"flex items-start gap-4 mb-6",children:[e.jsx("div",{className:"flex-shrink-0 mt-1",children:g()}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white mb-1",children:s}),e.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:c})]})]}),e.jsx("div",{className:"mb-6",children:e.jsx(Le,{value:a,color:u(),size:"lg",showLabel:!0,label:`${Math.round(a)}%`})}),f&&e.jsxs("div",{className:"mb-6 space-y-2",children:[f.currentItem&&e.jsxs("div",{className:"text-sm text-gray-700 dark:text-gray-300",children:[e.jsx("span",{className:"font-medium",children:"Current:"})," ",e.jsx("span",{className:"text-gray-600 dark:text-gray-400",children:f.currentItem})]}),f.total>0&&e.jsxs("div",{className:"text-sm text-gray-700 dark:text-gray-300",children:[e.jsx("span",{className:"font-medium",children:"Progress:"})," ",e.jsxs("span",{className:"text-gray-600 dark:text-gray-400",children:[f.current," of ",f.total," completed"]})]}),f.phase&&e.jsxs("div",{className:"text-xs text-gray-500 dark:text-gray-500",children:["Phase: ",f.phase]})]}),h&&!1,e.jsxs("div",{className:"flex justify-end gap-3",children:[d&&l!=="completed"&&l!=="error"&&e.jsx(ye,{variant:"secondary",size:"sm",onClick:d,disabled:l==="processing",children:"Cancel"}),(l==="completed"||l==="error")&&m&&e.jsx(ye,{variant:"primary",size:"sm",onClick:m,children:l==="completed"?"Close":"Dismiss"})]})]})})}function _t(){const[t,s]=r.useState(!1),[a,l]=r.useState(null),[c,f]=r.useState(""),[m,d]=r.useState({percentage:0,message:"Initializing...",status:"pending"}),h=r.useRef(0),u=r.useRef(null),g=r.useRef(null),n=(b,q="",D=[])=>{const C=(b==null?void 0:b.toUpperCase())||"",E=(Z,M)=>{const K=M.match(Z);return K&&K[1]?K[1]:""};let A=E(/(\d+)\s+keyword/i,q),i=E(/(\d+)\s+cluster/i,q);if(!A){const Z=E(/loaded\s+(\d+)\s+items?/i,q);Z&&(A=Z)}if(!i){const Z=E(/created\s+(\d+)\s+clusters?/i,q);Z&&(i=Z)}if(!A||!i)for(const Z of D){const M=Z.message||"";if(A||(A=E(/(\d+)\s+keyword/i,M)||E(/loaded\s+(\d+)\s+items?/i,M)),i||(i=E(/(\d+)\s+cluster/i,M)||E(/created\s+(\d+)\s+clusters?/i,M)),A&&i)break}const S=A,T=i;return C.includes("INIT")||C.includes("INITIALIZ")?{percentage:0,friendlyMessage:"Getting started..."}:C.includes("PREP")||C.includes("PREPAR")?{percentage:16,friendlyMessage:S?`Preparing ${S} keyword${S!=="1"?"s":""}...`:"Preparing your keywords..."}:C.includes("AI_CALL")||C.includes("CALLING")?{percentage:50,friendlyMessage:"Finding related keywords..."}:C.includes("PARSE")||C.includes("PARSING")?{percentage:70,friendlyMessage:"Organizing results..."}:C.includes("SAVE")||C.includes("SAVING")||C.includes("CREAT")?{percentage:85,friendlyMessage:T?`Saving ${T} cluster${T!=="1"?"s":""}...`:"Saving clusters..."}:C.includes("DONE")||C.includes("COMPLETE")?{percentage:100,friendlyMessage:S&&T?`Done! Created ${T} cluster${T!=="1"?"s":""} from ${S} keyword${S!=="1"?"s":""}`:S?`Done! Processed ${S} keyword${S!=="1"?"s":""}`:T?`Done! Created ${T} cluster${T!=="1"?"s":""}`:"Done! Clustering complete"}:{percentage:h.current,friendlyMessage:q||"Processing..."}};r.useEffect(()=>{if(!a||!t||a.startsWith("temp-"))return;let b=null,q=0,D=!1;const C=300,E=async()=>{if(!D)try{if(q++,q>C){d({percentage:0,message:"Task is taking longer than expected. Please check manually.",status:"error"}),D=!0,b&&(clearInterval(b),b=null);return}const A=await rs(`/v1/system/settings/task_progress/${a}/`);if(A.state==="PROGRESS"){const i=A.meta||{};let S=null;const T=[...i.request_steps||[],...i.response_steps||[]];if(T.length>0){const R=[...T].sort((X,re)=>(re.stepNumber||0)-(X.stepNumber||0))[0];if(R&&R.stepName){const X=R.stepName.toUpperCase();X.includes("INIT")?S="INIT":X.includes("PREP")?S="PREP":X.includes("AI_CALL")||X.includes("CALL")?S="AI_CALL":X.includes("PARSE")?S="PARSE":X.includes("SAVE")||X.includes("CREAT")?S="SAVE":X.includes("DONE")||X.includes("COMPLETE")?S="DONE":S=X}}if(!S){const L=(i.phase||"").toLowerCase(),R=(i.message||"").toLowerCase();L.includes("initializ")||R.includes("initializ")||R.includes("getting started")?S="INIT":L.includes("prepar")||L.includes("prep")||R.includes("prepar")||R.includes("loading")?S="PREP":L.includes("analyzing")||L.includes("ai_call")||R.includes("analyzing")||R.includes("finding related")?S="AI_CALL":L.includes("pars")||R.includes("pars")||R.includes("organizing")?S="PARSE":L.includes("sav")||L.includes("creat")||R.includes("sav")||R.includes("creat")||R.includes("cluster")?S="SAVE":(L.includes("done")||L.includes("complet")||R.includes("done")||R.includes("complet"))&&(S="DONE")}const Z=i.message||"",M=n(S||"",Z,T),K=M.percentage,Q=M.friendlyMessage,Y=u.current!==S;if(g.current&&(clearTimeout(g.current),g.current=null),Y&&u.current!==null?g.current=setTimeout(()=>{u.current=S,h.current=K,d({percentage:K,message:Q,status:"processing",details:{current:i.current||0,total:i.total||0,completed:i.completed||0,currentItem:i.current_item,phase:i.phase}})},500):(u.current=S,h.current=K,d({percentage:K,message:Q,status:"processing",details:{current:i.current||0,total:i.total||0,completed:i.completed||0,currentItem:i.current_item,phase:i.phase}})),i.request_steps||i.response_steps){const{useAIRequestLogsStore:L}=await Me(async()=>{const{useAIRequestLogsStore:re}=await import("./page-dashboard-DxYTR5eF.js").then(ie=>ie.a6);return{useAIRequestLogsStore:re}},__vite__mapDeps([0,1,2,3,4,5,6])).catch(()=>({useAIRequestLogsStore:null})),X=((L==null?void 0:L.getState().logs)||[]).find(re=>{var ie,oe;return((oe=(ie=re.response)==null?void 0:ie.data)==null?void 0:oe.task_id)===a});if(X){const re=L==null?void 0:L.getState().addRequestStep,ie=L==null?void 0:L.getState().addResponseStep;i.request_steps&&Array.isArray(i.request_steps)&&i.request_steps.forEach(oe=>{X.requestSteps.find(be=>be.stepNumber===oe.stepNumber)||re==null||re(X.id,oe)}),i.response_steps&&Array.isArray(i.response_steps)&&i.response_steps.forEach(oe=>{X.responseSteps.find(be=>be.stepNumber===oe.stepNumber)||ie==null||ie(X.id,oe)})}}}else if(A.state==="SUCCESS"){const i=A.meta||{};g.current&&(clearTimeout(g.current),g.current=null);const S=i.message||"",T=[...i.request_steps||[],...i.response_steps||[]],Z=n("DONE",S,T);if(u.current="DONE",h.current=100,d({percentage:100,message:Z.friendlyMessage,status:"completed",details:i.details}),i.request_steps||i.response_steps){const{useAIRequestLogsStore:M}=await Me(async()=>{const{useAIRequestLogsStore:Y}=await import("./page-dashboard-DxYTR5eF.js").then(L=>L.a6);return{useAIRequestLogsStore:Y}},__vite__mapDeps([0,1,2,3,4,5,6])).catch(()=>({useAIRequestLogsStore:null})),K=(M==null?void 0:M.getState().logs)||[],Q=K.find(Y=>{var L,R;return((R=(L=Y.response)==null?void 0:L.data)==null?void 0:R.task_id)===a})||K[0];if(Q){const Y=M==null?void 0:M.getState().addRequestStep,L=M==null?void 0:M.getState().addResponseStep;i.request_steps&&Array.isArray(i.request_steps)&&i.request_steps.forEach(R=>{Q.requestSteps.find(X=>X.stepNumber===R.stepNumber)||Y==null||Y(Q.id,R)}),i.response_steps&&Array.isArray(i.response_steps)&&i.response_steps.forEach(R=>{Q.responseSteps.find(X=>X.stepNumber===R.stepNumber)||L==null||L(Q.id,R)})}}D=!0,b&&(clearInterval(b),b=null)}else if(A.state==="FAILURE"){const i=A.meta||{},S=i.error||"Task failed";if(d({percentage:0,message:`Error: ${S}`,status:"error"}),i.request_steps||i.response_steps){const{useAIRequestLogsStore:T}=await Me(async()=>{const{useAIRequestLogsStore:K}=await import("./page-dashboard-DxYTR5eF.js").then(Q=>Q.a6);return{useAIRequestLogsStore:K}},__vite__mapDeps([0,1,2,3,4,5,6])).catch(()=>({useAIRequestLogsStore:null})),M=((T==null?void 0:T.getState().logs)||[]).find(K=>{var Q,Y;return((Y=(Q=K.response)==null?void 0:Q.data)==null?void 0:Y.task_id)===a});if(M){const K=T==null?void 0:T.getState().addRequestStep,Q=T==null?void 0:T.getState().addResponseStep;i.request_steps&&Array.isArray(i.request_steps)&&i.request_steps.forEach(Y=>{M.requestSteps.find(L=>L.stepNumber===Y.stepNumber)||K==null||K(M.id,Y)}),i.response_steps&&Array.isArray(i.response_steps)&&i.response_steps.forEach(Y=>{M.responseSteps.find(L=>L.stepNumber===Y.stepNumber)||Q==null||Q(M.id,Y)})}}D=!0,b&&(clearInterval(b),b=null)}else d({percentage:0,message:"Task is starting...",status:"pending"})}catch(A){if(console.error("Error polling task status:",A),q>5){let i=A.message||"Unknown error";i.includes("HTTP_ERROR")&&(i=i.replace(/^API Error \(\d+\): HTTP_ERROR - /,"").trim()||"Server error"),d({percentage:0,message:`Error checking task status: ${i}`,status:"error"}),D=!0,b&&(clearInterval(b),b=null)}}};return E(),b=setInterval(()=>{D||E()},2e3),()=>{D=!0,b&&(clearInterval(b),b=null),g.current&&(clearTimeout(g.current),g.current=null)}},[a,t]);const j=r.useCallback((b,q)=>{g.current&&(clearTimeout(g.current),g.current=null),h.current=0,u.current=null,l(b),f(q),s(!0),d({percentage:0,message:"Getting started...",status:"pending"})},[]),O=r.useCallback(b=>{l(b),d({percentage:0,message:"Initializing...",status:"pending"})},[]),P=r.useCallback(()=>{g.current&&(clearTimeout(g.current),g.current=null),h.current=0,u.current=null,s(!1),l(null),f("")},[]),F=r.useCallback(b=>{d({percentage:0,message:b,status:"error"})},[]),ne=r.useCallback(()=>{g.current&&(clearTimeout(g.current),g.current=null),h.current=0,u.current=null,d({percentage:0,message:"Getting started...",status:"pending"}),l(null),f(""),s(!1)},[]);return{progress:m,isOpen:t,openModal:j,updateTaskId:O,closeModal:P,setError:F,reset:ne,title:c,taskId:a}}const qs=t=>{const s=new URLSearchParams;t.filters&&Object.entries(t.filters).forEach(([f,m])=>{m!==""&&m!==null&&m!==void 0&&s.append(f,String(m))});const a=s.toString(),l=t.endpoint.endsWith("/")?t.endpoint:`${t.endpoint}/`;return`${bt}${l}${a?`?${a}`:""}`},Ws=async(t,s,a)=>{const l=t.format||"csv",c=qs(t);s==null||s(`Exporting ${l.toUpperCase()}...`);try{const f=await fetch(c,{method:"GET",credentials:"include"});if(!f.ok){const u=await f.text();throw new Error(`Export failed: ${f.statusText} - ${u}`)}const m=await f.blob(),d=window.URL.createObjectURL(m),h=document.createElement("a");h.href=d,h.download=`${t.filename}.${l}`,document.body.appendChild(h),h.click(),document.body.removeChild(h),window.URL.revokeObjectURL(d),s==null||s(`Export successful: ${t.filename}.${l}`)}catch(f){const m=f instanceof Error?f:new Error("Export failed");throw a==null||a(m),m}},Gs=async(t,s,a,l)=>{var h,u;const c=s.acceptedFormats||[".csv"],f="."+((h=t.name.split(".").pop())==null?void 0:h.toLowerCase());if(!c.includes(f)){const g=new Error(`Invalid file format. Accepted formats: ${c.join(", ")}`);throw l==null||l(g),g}const m=s.maxFileSize||5*1024*1024;if(t.size>m){const g=new Error(`File size exceeds ${m/1024/1024}MB limit`);throw l==null||l(g),g}a==null||a(`Importing ${t.name}...`);const d=new FormData;d.append("file",t);try{const g=s.endpoint.endsWith("/")?s.endpoint:`${s.endpoint}/`,n=new URLSearchParams;s.queryParams&&Object.entries(s.queryParams).forEach(([ne,b])=>{b!==""&&b!==null&&b!==void 0&&n.append(ne,String(b))});const j=n.toString(),O=`${bt}${g}${j?`?${j}`:""}`,P=await fetch(O,{method:"POST",body:d,credentials:"include"});if(!P.ok){const ne=await P.text();throw new Error(`Import failed: ${P.statusText} - ${ne}`)}const F=await P.json();return a==null||a(`Import successful: ${F.imported||0} rows imported`),(u=s.onSuccess)==null||u.call(s,F),F}catch(g){const n=g instanceof Error?g:new Error("Import failed");throw l==null||l(n),n}},Js=({className:t,onChange:s,accept:a,disabled:l=!1})=>e.jsx("input",{type:"file",accept:a,disabled:l,className:`focus:border-ring-brand-300 h-11 w-full overflow-hidden rounded-lg border border-gray-300 bg-transparent text-sm text-gray-500 shadow-theme-xs transition-colors file:mr-5 file:border-collapse file:cursor-pointer file:rounded-l-lg file:border-0 file:border-r file:border-solid file:border-gray-200 file:bg-gray-50 file:py-3 file:pl-3.5 file:pr-3 file:text-sm file:text-gray-700 placeholder:text-gray-400 hover:file:bg-gray-100 focus:outline-hidden focus:file:ring-brand-300 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-400 dark:text-white/90 dark:file:border-gray-800 dark:file:bg-white/[0.03] dark:file:text-gray-400 dark:placeholder:text-gray-400 disabled:opacity-50 disabled:cursor-not-allowed ${t}`,onChange:s});function Qs(t){const{exportEndpoint:s,importEndpoint:a,filename:l,acceptedFormats:c=[".csv"],maxFileSize:f=5*1024*1024,onImportSuccess:m,onExportSuccess:d,onError:h}=t,[u,g]=r.useState(!1),[n,j]=r.useState(!1),O=r.useCallback(async(b="csv",q={})=>{j(!0);try{await Ws({endpoint:s,filename:l,format:b,filters:q},C=>console.log(C),C=>{throw h==null||h(C),C}),d==null||d()}catch(D){const C=D instanceof Error?D:new Error("Export failed");throw h==null||h(C),C}finally{j(!1)}},[s,l,h,d]),P=r.useCallback(async b=>{j(!0);try{const q={endpoint:a,acceptedFormats:c,maxFileSize:f,queryParams:t.importQueryParams,onSuccess:C=>{m==null||m(C)}},D=await Gs(b,q,C=>console.log(C),C=>{throw h==null||h(C),C});return g(!1),D}catch(q){const D=q instanceof Error?q:new Error("Import failed");throw h==null||h(D),D}finally{j(!1)}},[a,c,f,m,h]),F=r.useCallback(async b=>{var D;const q=(D=b.target.files)==null?void 0:D[0];q&&(await P(q),b.target.value="")},[P]);return{handleExport:O,handleImportClick:()=>g(!0),ImportModal:()=>e.jsx(He,{isOpen:u,onClose:()=>g(!1),className:"max-w-md",children:e.jsxs("div",{className:"p-6",children:[e.jsxs("h2",{className:"text-xl font-bold mb-6 text-gray-800 dark:text-white",children:["Import ",l.charAt(0).toUpperCase()+l.slice(1)]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(et,{children:"CSV File"}),e.jsx(Js,{onChange:F,accept:c.join(","),disabled:n}),e.jsxs("p",{className:"text-sm text-gray-500 dark:text-gray-400 mt-2",children:["Upload a CSV file (max ",f/1024/1024,"MB)"]})]}),e.jsx("div",{className:"flex justify-end gap-4 pt-4",children:e.jsx(ye,{variant:"outline",onClick:()=>g(!1),disabled:n,children:"Close"})})]})]})})}}const Ys=(t,s,a)=>Qs({exportEndpoint:"/v1/planner/keywords/export/",importEndpoint:"/v1/planner/keywords/import_keywords/",filename:"keywords",acceptedFormats:[".csv"],maxFileSize:5*1024*1024,importQueryParams:a,onImportSuccess:t,onError:s});function Xs(){const t=Ue(),{activeSite:s}=St(),{activeSector:a,loadSectorsForSite:l}=Oe(),{pageSize:c}=qe(),[f,m]=r.useState([]),[d,h]=r.useState([]),[u,g]=r.useState([]),[n,j]=r.useState(!0),[O,P]=r.useState(!1),[F,ne]=r.useState(""),[b,q]=r.useState(""),[D,C]=r.useState(""),[E,A]=r.useState(""),[i,S]=r.useState(""),[T,Z]=r.useState(""),[M,K]=r.useState(""),[Q,Y]=r.useState(!1),[L,R]=r.useState(""),[X,re]=r.useState(""),ie=r.useRef(null),oe=r.useRef(null),[be,we]=r.useState([]),[ge,N]=r.useState(1),[w,x]=r.useState(1),[V,W]=r.useState(0),[H,ee]=r.useState("created_at"),[te,G]=r.useState("desc"),[fe,le]=r.useState(!1),[J,p]=r.useState(!1),[_,I]=r.useState(!1),[me,he]=r.useState(null),[ue,$]=r.useState({seed_keyword_id:0,volume_override:null,difficulty_override:null,cluster_id:null,status:"pending"}),z=_t(),se=r.useRef(!1);r.useEffect(()=>{s&&l(s.id)},[s,l]),r.useEffect(()=>{(async()=>{if(!s||!a||!s.industry){g([]);return}try{P(!0);const B=await ft({industry:s.industry,sector:a.industry_sector||void 0}),o=new Set(f.map(k=>k.seed_keyword_id)),y=(B.results||[]).filter(k=>!o.has(k.id));g(y)}catch(B){console.error("Failed to load available seed keywords:",B),g([])}finally{P(!1)}})()},[s,a,f]),r.useEffect(()=>{(async()=>{try{const B=await tt({ordering:"name"});h(B.results||[])}catch(B){console.error("Error fetching clusters:",B)}})()},[]);const ae=r.useCallback(async()=>{j(!0),le(!1);try{const v=H?`${te==="desc"?"-":""}${H}`:"-created_at",B={...F&&{search:F},...b&&{status:b},...D&&{cluster_id:D},...E&&{intent:E},...(a==null?void 0:a.id)&&{sector_id:a.id},page:ge,page_size:c||10,ordering:v};if(i){const y=parseInt(i),k=wt(y);if(k!==null){const U=vt(k);U&&(B.difficulty_min=U.min,B.difficulty_max=U.max)}}T!==""&&T!==null&&T!==void 0&&(B.volume_min=Number(T)),M!==""&&M!==null&&M!==void 0&&(B.volume_max=Number(M));const o=await as(B);m(o.results||[]),W(o.count||0),x(Math.ceil((o.count||0)/c)),setTimeout(()=>{le(!0),j(!1)},100)}catch(v){console.error("Error loading keywords:",v),t.error(`Failed to load keywords: ${v.message}`),le(!0),j(!1)}},[ge,b,D,E,i,T,M,H,te,F,s,a,c]);r.useEffect(()=>{const v=()=>{ae(),(async()=>{try{const y=await tt({ordering:"name"});h(y.results||[])}catch(y){console.error("Error fetching clusters:",y)}})()},B=()=>{ae()};return window.addEventListener("siteChanged",v),window.addEventListener("sectorChanged",B),()=>{window.removeEventListener("siteChanged",v),window.removeEventListener("sectorChanged",B)}},[ae]),r.useEffect(()=>{const v=B=>{ie.current&&!ie.current.contains(B.target)&&oe.current&&!oe.current.contains(B.target)&&(Y(!1),R(T),re(M))};if(Q)return document.addEventListener("mousedown",v),()=>{document.removeEventListener("mousedown",v)}},[Q,T,M]),r.useEffect(()=>{ae()},[ae]),r.useEffect(()=>{const v=setTimeout(()=>{N(1)},500);return()=>clearTimeout(v)},[F]),r.useEffect(()=>{const v=ge===1;N(1),v&&setTimeout(()=>{ae()},0)},[c]);const Ne=(v,B)=>{ee(v||"created_at"),G(B),N(1)},{handleExport:Ie,handleImportClick:We,ImportModal:Ge}=Ys(()=>{t.success("Import successful","Keywords imported successfully."),ae()},v=>{t.error("Import failed",v.message)},s&&a?{site_id:s.id,sector_id:a.id}:void 0),nt=r.useCallback(async(v,B)=>{if(v==="auto_cluster"){if(B.length===0){t.error("Please select at least one keyword to cluster");return}if(B.length>20){t.error("Maximum 20 keywords allowed for clustering");return}try{const o=B.map(U=>parseInt(U)),y=a==null?void 0:a.id,k=await ns(o,y);if(k&&k.success===!1){const U=k.error||"Failed to cluster keywords";t.error(U);return}if(k&&k.success)k.task_id?(se.current=!1,z.openModal(k.task_id,"Auto-Clustering Keywords")):(t.success(`Clustering complete: ${k.clusters_created||0} clusters created, ${k.keywords_updated||0} keywords updated`),se.current||(se.current=!0,ae()));else{const U=(k==null?void 0:k.error)||"Unexpected response format";t.error(U)}}catch(o){let y="Failed to cluster keywords";o.message&&(y=o.message.replace(/^API Error \(\d+\): [^-]+ - /,"").trim(),(!y||y===o.message)&&(y=o.message)),t.error(y)}}else t.info(`Bulk action "${v}" for ${B.length} items`)},[t,a,ae,z]),Fe=r.useCallback(()=>{$({seed_keyword_id:0,volume_override:null,difficulty_override:null,cluster_id:null,status:"pending"}),I(!1),he(null)},[]),Re=r.useCallback(async v=>{try{if(!v||v.length===0)throw new Error("No records selected for export");const B=v.join(","),o=`${bt}/v1/planner/keywords/export/?ids=${encodeURIComponent(B)}`,y=await fetch(o,{method:"GET",credentials:"include"});if(!y.ok){const Pe=await y.text();throw new Error(`Export failed: ${y.statusText} - ${Pe}`)}const k=await y.blob(),U=window.URL.createObjectURL(k),de=document.createElement("a");de.href=U,de.download="keywords.csv",document.body.appendChild(de),de.click(),document.body.removeChild(de),window.URL.revokeObjectURL(U)}catch(B){throw B}},[]),Ee=r.useCallback(async(v,B)=>{try{const o=v.map(y=>parseInt(y));await os(o,B),await ae()}catch(o){throw o}},[ae]),xe=r.useMemo(()=>Cs({clusters:d,activeSector:a,availableSeedKeywords:u,formData:ue,setFormData:$,searchTerm:F,setSearchTerm:ne,statusFilter:b,setStatusFilter:q,intentFilter:E,setIntentFilter:A,difficultyFilter:i,setDifficultyFilter:S,clusterFilter:D,setClusterFilter:C,volumeMin:T,volumeMax:M,setVolumeMin:Z,setVolumeMax:K,isVolumeDropdownOpen:Q,setIsVolumeDropdownOpen:Y,tempVolumeMin:L,tempVolumeMax:X,setTempVolumeMin:R,setTempVolumeMax:re,volumeButtonRef:oe,volumeDropdownRef:ie,setCurrentPage:N,loadKeywords:ae}),[d,a,u,ue,F,b,E,i,D,T,M,Q,L,X,ae,s]),ot=r.useMemo(()=>xe!=null&&xe.headerMetrics?xe.headerMetrics.map(v=>({label:v.label,value:v.calculate({keywords:f,totalCount:V,clusters:d}),accentColor:v.accentColor})):[],[xe==null?void 0:xe.headerMetrics,f,V,d]),lt=async()=>{try{if(!s){t.error("Please select an active site first");return}if(_&&me)await cs(me.id,ue),t.success("Keyword updated successfully");else{if(!a){t.error("Please select a sector for this site first");return}if(!ue.seed_keyword_id){t.error("Please select a seed keyword");return}const v=a.id,B={...ue,site_id:s.id,sector_id:v};await ds(B),t.success("Keyword attached successfully")}p(!1),Fe(),ae()}catch(v){t.error(`Failed to save: ${v.message}`)}},Je=r.useCallback(v=>{he(v),I(!0),$({seed_keyword_id:v.seed_keyword_id,volume_override:v.volume_override||null,difficulty_override:v.difficulty_override||null,cluster_id:v.cluster_id,status:v.status}),p(!0)},[]);return e.jsxs(e.Fragment,{children:[e.jsx(at,{title:"Keywords",titleIcon:e.jsx(Ft,{className:"text-brand-500 size-5"}),subtitle:"Manage and organize SEO keywords for content planning",columns:xe.columns,data:f,loading:n,showContent:fe,filters:xe.filters,filterValues:{search:F,status:b,intent:E,difficulty:i,cluster_id:D,volumeMin:T,volumeMax:M},onFilterChange:(v,B)=>{const o=B==null?"":String(B);v==="search"?ne(o):v==="status"?(q(o),N(1)):v==="intent"?(A(o),N(1)):v==="difficulty"?(S(o),N(1)):v==="cluster_id"&&(C(o),N(1))},onEdit:Je,onCreate:()=>{Fe(),p(!0)},createLabel:"Add Keyword",onCreateIcon:e.jsx(Ve,{}),onDelete:async v=>{await is(v),ae()},onBulkDelete:async v=>{const B=await ls(v);return ae(),B},onBulkExport:Re,onBulkUpdateStatus:Ee,onBulkAction:nt,getItemDisplayName:v=>v.keyword,onExport:async()=>{try{await Ie("csv",{search:F,status:b,cluster_id:D,intent:E,difficulty:i}),t.success("Export successful","Keywords exported successfully.")}catch(v){t.error("Export failed",v.message)}},onExportIcon:e.jsx(yt,{}),onImport:We,onImportIcon:e.jsx(ts,{}),selectionLabel:"keyword",pagination:{currentPage:ge,totalPages:w,totalCount:V,onPageChange:v=>{N(v)}},selection:{selectedIds:be,onSelectionChange:we},sorting:{sortBy:H,sortDirection:te,onSort:Ne},headerMetrics:ot,onFilterReset:()=>{ne(""),q(""),C(""),A(""),S(""),Z(""),K(""),R(""),re(""),Y(!1),N(1)}}),e.jsx(Nt,{isOpen:J,onClose:()=>{p(!1),Fe()},onSubmit:lt,title:_?"Edit Keyword":"Add Keyword",submitLabel:_?"Update":"Create",fields:xe.formFields(d)}),e.jsx(Ge,{}),e.jsx(Ct,{isOpen:z.isOpen,title:z.title,percentage:z.progress.percentage,status:z.progress.status,message:z.progress.message,details:z.progress.details,taskId:z.taskId||void 0,onClose:()=>{z.closeModal(),z.progress.status==="completed"&&!se.current&&(se.current=!0,ae())}})]})}const yr=Object.freeze(Object.defineProperty({__proto__:null,default:Xs},Symbol.toStringTag,{value:"Module"}));function Zs(){const t=Ue(),{activeSector:s}=Oe(),{pageSize:a}=qe(),[l,c]=r.useState([]),[f,m]=r.useState(!0),[d,h]=r.useState(""),[u,g]=r.useState(""),[n,j]=r.useState(""),[O,P]=r.useState(""),[F,ne]=r.useState(""),[b,q]=r.useState(!1),[D,C]=r.useState(""),[E,A]=r.useState(""),i=r.useRef(null),S=r.useRef(null),[T,Z]=r.useState([]),[M,K]=r.useState(1),[Q,Y]=r.useState(1),[L,R]=r.useState(0),[X,re]=r.useState("name"),[ie,oe]=r.useState("asc"),[be,we]=r.useState(!1),[ge,N]=r.useState(!1),[w,x]=r.useState(!1),[V,W]=r.useState(null),[H,ee]=r.useState({name:"",description:"",status:"active"}),te=_t(),G=r.useCallback(async()=>{m(!0),we(!1);try{const $=X?`${ie==="desc"?"-":""}${X}`:"name",z={...d&&{search:d},...u&&{status:u},...(s==null?void 0:s.id)&&{sector_id:s.id},page:M,page_size:a,ordering:$};if(n){const ae=parseInt(n),Ne=wt(ae);if(Ne!==null){const Ie=vt(Ne);Ie&&(z.difficulty_min=Ie.min,z.difficulty_max=Ie.max)}}O!==""&&O!==null&&O!==void 0&&(z.volume_min=Number(O)),F!==""&&F!==null&&F!==void 0&&(z.volume_max=Number(F));const se=await tt(z);c(se.results||[]),R(se.count||0),Y(Math.ceil((se.count||0)/a)),setTimeout(()=>{we(!0),m(!1)},100)}catch($){console.error("Error loading clusters:",$),t.error(`Failed to load clusters: ${$.message}`),we(!0),m(!1)}},[M,u,X,ie,d,n,O,F,s,a]);r.useEffect(()=>{G()},[G]),r.useEffect(()=>{const $=()=>{G()},z=()=>{G()};return window.addEventListener("siteChanged",$),window.addEventListener("sectorChanged",z),()=>{window.removeEventListener("siteChanged",$),window.removeEventListener("sectorChanged",z)}},[G]),r.useEffect(()=>{const $=setTimeout(()=>{M===1?G():K(1)},500);return()=>clearTimeout($)},[d,M,G]),r.useEffect(()=>{K(1)},[a]);const fe=($,z)=>{re($||"name"),oe(z),K(1)},le=r.useCallback(async($,z)=>{try{const se=$.map(ae=>parseInt(ae));await us(se,z),await G()}catch(se){throw se}},[G]),J=r.useCallback(async $=>{try{if(!$||$.length===0)throw new Error("No records selected for export");t.info("Export functionality coming soon")}catch(z){throw z}},[]),p=r.useCallback(async($,z)=>{if($==="generate_ideas")try{const se=await Lt([z.id]);se.success&&se.task_id?te.openModal(se.task_id,"Generating Ideas"):se.success&&se.ideas_created?(t.success(se.message||"Ideas generated successfully"),await G()):t.error(se.error||"Failed to generate ideas")}catch(se){t.error(`Failed to generate ideas: ${se.message}`)}},[t,te,G]),_=r.useCallback(async($,z)=>{if($==="auto_generate_ideas"){if(z.length===0){t.error("Please select at least one cluster to generate ideas");return}if(z.length>5){t.error("Maximum 5 clusters allowed for idea generation");return}try{const se=z.map(Ne=>parseInt(Ne)),ae=await Lt(se);ae.success?ae.task_id?te.openModal(ae.task_id,"Generating Content Ideas"):(t.success(`Ideas generation complete: ${ae.ideas_created||0} ideas created`),await G()):t.error(ae.error||"Failed to generate ideas")}catch(se){t.error(`Failed to generate ideas: ${se.message}`)}}else t.info(`Bulk action "${$}" for ${z.length} items`)},[t,G,te]);r.useEffect(()=>{const $=z=>{i.current&&!i.current.contains(z.target)&&S.current&&!S.current.contains(z.target)&&q(!1)};return b&&document.addEventListener("mousedown",$),()=>{document.removeEventListener("mousedown",$)}},[b]);const I=r.useMemo(()=>js({activeSector:s,formData:H,setFormData:ee,searchTerm:d,setSearchTerm:h,statusFilter:u,setStatusFilter:g,difficultyFilter:n,setDifficultyFilter:j,volumeMin:O,volumeMax:F,setVolumeMin:P,setVolumeMax:ne,isVolumeDropdownOpen:b,setIsVolumeDropdownOpen:q,tempVolumeMin:D,tempVolumeMax:E,setTempVolumeMin:C,setTempVolumeMax:A,volumeButtonRef:S,volumeDropdownRef:i,setCurrentPage:K,loadClusters:G}),[s,H,d,u,n,O,F,b,D,E,G]),me=r.useMemo(()=>I!=null&&I.headerMetrics?I.headerMetrics.map($=>({label:$.label,value:$.calculate({clusters:l,totalCount:L}),accentColor:$.accentColor})):[],[I==null?void 0:I.headerMetrics,l,L]),he=r.useCallback(()=>{ee({name:"",description:"",status:"active"}),x(!1),W(null)},[]),ue=async()=>{try{w&&V?(await fs(V.id,H),t.success("Cluster updated successfully")):(await hs(H),t.success("Cluster created successfully")),N(!1),he(),G()}catch($){t.error(`Failed to save: ${$.message}`)}};return e.jsxs(e.Fragment,{children:[e.jsx(at,{title:"Keyword Clusters",titleIcon:e.jsx(Rt,{className:"text-success-500 size-5"}),subtitle:"Organize keywords into content clusters for better SEO strategy",columns:I.columns,data:l,loading:f,showContent:be,filters:I.filters,filterValues:{search:d,status:u,difficulty:n,volumeMin:O,volumeMax:F},onFilterChange:($,z)=>{const se=z==null?"":String(z);$==="search"?h(se):$==="status"?g(se):$==="difficulty"&&j(se),K(1)},onEdit:$=>{W($),ee({name:$.name||"",description:$.description||"",status:$.status||"active"}),x(!0),N(!0)},onCreate:()=>{he(),N(!0)},createLabel:"Create Cluster",onCreateIcon:e.jsx(Ve,{}),onDelete:async $=>{await gs($),G()},onBulkDelete:async $=>{const z=await ms($);return G(),z},onBulkExport:J,onBulkUpdateStatus:le,onBulkAction:_,onRowAction:p,getItemDisplayName:$=>$.name,onExport:async()=>{t.info("Export functionality coming soon")},onExportIcon:e.jsx(yt,{}),selectionLabel:"cluster",pagination:{currentPage:M,totalPages:Q,totalCount:L,onPageChange:K},selection:{selectedIds:T,onSelectionChange:Z},sorting:{sortBy:X,sortDirection:ie,onSort:fe},headerMetrics:me,onFilterReset:()=>{h(""),g(""),j(""),P(""),ne(""),K(1)}}),e.jsx(Ct,{isOpen:te.isOpen,title:te.title,percentage:te.progress.percentage,status:te.progress.status,message:te.progress.message,details:te.progress.details,taskId:te.taskId||void 0,onClose:()=>{const $=te.progress.status==="completed";te.closeModal(),$&&G()}}),e.jsx(Nt,{isOpen:ge,onClose:()=>{N(!1),he()},onSubmit:ue,title:w?"Edit Cluster":"Add Cluster",submitLabel:w?"Update":"Create",fields:I.formFields()})]})}const br=Object.freeze(Object.defineProperty({__proto__:null,default:Zs},Symbol.toStringTag,{value:"Module"}));function er(){const t=Ue(),{activeSector:s}=Oe(),{pageSize:a}=qe(),[l,c]=r.useState([]),[f,m]=r.useState([]),[d,h]=r.useState(!0),[u,g]=r.useState(""),[n,j]=r.useState(""),[O,P]=r.useState(""),[F,ne]=r.useState(""),[b,q]=r.useState(""),[D,C]=r.useState([]),[E,A]=r.useState(1),[i,S]=r.useState(1),[T,Z]=r.useState(0),[M,K]=r.useState("created_at"),[Q,Y]=r.useState("desc"),[L,R]=r.useState(!1),[X,re]=r.useState(!1),[ie,oe]=r.useState(!1),[be,we]=r.useState(null),[ge,N]=r.useState({idea_title:"",description:"",content_structure:"blog_post",content_type:"blog_post",target_keywords:"",keyword_cluster_id:null,status:"new",estimated_word_count:1e3}),w=_t();r.useEffect(()=>{(async()=>{try{const _=await tt({ordering:"name"});m(_.results||[])}catch(_){console.error("Error fetching clusters:",_)}})()},[]);const x=r.useCallback(async()=>{h(!0),R(!1);try{const p=M?`${Q==="desc"?"-":""}${M}`:"-created_at",_={...u&&{search:u},...n&&{status:n},...O&&{keyword_cluster_id:O},...F&&{content_structure:F},...b&&{content_type:b},page:E,page_size:a,ordering:p},I=await ps(_);c(I.results||[]),Z(I.count||0),S(Math.ceil((I.count||0)/a)),setTimeout(()=>{R(!0),h(!1)},100)}catch(p){console.error("Error loading ideas:",p),t.error(`Failed to load ideas: ${p.message}`),R(!0),h(!1)}},[E,n,O,F,b,M,Q,u,s,a]);r.useEffect(()=>{x()},[x]),r.useEffect(()=>{const p=()=>{x()},_=()=>{x()};return window.addEventListener("siteChanged",p),window.addEventListener("sectorChanged",_),()=>{window.removeEventListener("siteChanged",p),window.removeEventListener("sectorChanged",_)}},[x]),r.useEffect(()=>{A(1)},[a]),r.useEffect(()=>{const p=setTimeout(()=>{E===1?x():A(1)},500);return()=>clearTimeout(p)},[u,E,x]);const V=(p,_)=>{K(p||"created_at"),Y(_),A(1)},W=r.useCallback(async(p,_)=>{try{const I=p.map(me=>parseInt(me));await xs(I,_),await x()}catch(I){throw I}},[x]),H=r.useCallback(async p=>{try{if(!p||p.length===0)throw new Error("No records selected for export");t.info("Export functionality coming soon")}catch(_){throw _}},[]),ee=r.useCallback(async(p,_)=>{if(p==="queue_to_writer"){if(_.status!=="new"){t.error(`Only ideas with status "new" can be queued. Current status: ${_.status}`);return}try{const I=await Ot([_.id]);t.success(`Queue complete: ${I.created_count||0} task created`),await x()}catch(I){t.error(`Failed to queue idea: ${I.message}`)}}},[t,x]),te=r.useCallback(async(p,_)=>{if(p==="queue_to_writer"){if(_.length===0){t.error("Please select at least one idea to queue");return}try{const I=_.map(he=>parseInt(he)),me=await Ot(I);t.success(`Queue complete: ${me.created_count||0} tasks created from ${_.length} ideas`),await x()}catch(I){t.error(`Failed to queue ideas: ${I.message}`)}}else t.info(`Bulk action "${p}" for ${_.length} items`)},[t,x]),G=r.useMemo(()=>_s({clusters:f,activeSector:s,formData:ge,setFormData:N,searchTerm:u,setSearchTerm:g,statusFilter:n,setStatusFilter:j,clusterFilter:O,setClusterFilter:P,structureFilter:F,setStructureFilter:ne,typeFilter:b,setTypeFilter:q,setCurrentPage:A}),[f,s,ge,u,n,O,F,b]),fe=r.useMemo(()=>G!=null&&G.headerMetrics?G.headerMetrics.map(p=>({label:p.label,value:p.calculate({ideas:l,totalCount:T}),accentColor:p.accentColor})):[],[G==null?void 0:G.headerMetrics,l,T]),le=r.useCallback(()=>{N({idea_title:"",description:"",content_structure:"blog_post",content_type:"blog_post",target_keywords:"",keyword_cluster_id:null,status:"new",estimated_word_count:1e3}),oe(!1),we(null)},[]),J=async()=>{try{ie&&be?(await ws(be.id,ge),t.success("Idea updated successfully")):(await vs(ge),t.success("Idea created successfully")),re(!1),le(),x()}catch(p){t.error(`Failed to save: ${p.message}`)}};return e.jsxs(e.Fragment,{children:[e.jsx(at,{title:"Content Ideas",titleIcon:e.jsx(pt,{className:"text-warning-500 size-5"}),subtitle:"Generate and organize content ideas based on keyword research",columns:G.columns,data:l,loading:d,showContent:L,filters:G.filters,filterValues:{search:u,status:n,keyword_cluster_id:O,content_structure:F,content_type:b},onFilterChange:(p,_)=>{const I=_==null?"":String(_);p==="search"?g(I):p==="status"?j(I):p==="keyword_cluster_id"?P(I):p==="content_structure"?ne(I):p==="content_type"&&q(I),A(1)},onEdit:p=>{we(p),N({idea_title:p.idea_title||"",description:p.description||"",content_structure:p.content_structure||"blog_post",content_type:p.content_type||"blog_post",target_keywords:p.target_keywords||"",keyword_cluster_id:p.keyword_cluster_id||null,status:p.status||"new",estimated_word_count:p.estimated_word_count||1e3}),oe(!0),re(!0)},onCreate:()=>{le(),re(!0)},createLabel:"Add Idea",onCreateIcon:e.jsx(Ve,{}),onDelete:async p=>{await bs(p),x()},onBulkDelete:async p=>{const _=await ys(p);return x(),_},onBulkExport:H,onBulkUpdateStatus:W,onBulkAction:te,onRowAction:ee,getItemDisplayName:p=>p.idea_title,onExport:async()=>{t.info("Export functionality coming soon")},onExportIcon:e.jsx(yt,{}),selectionLabel:"idea",pagination:{currentPage:E,totalPages:i,totalCount:T,onPageChange:A},selection:{selectedIds:D,onSelectionChange:C},sorting:{sortBy:M,sortDirection:Q,onSort:V},headerMetrics:fe,onFilterReset:()=>{g(""),j(""),P(""),ne(""),q(""),A(1)}}),e.jsx(Ct,{isOpen:w.isOpen,title:w.title,percentage:w.progress.percentage,status:w.progress.status,message:w.progress.message,details:w.progress.details,taskId:w.taskId||void 0,onClose:()=>{const p=w.progress.status==="completed";w.closeModal(),p&&x()}}),e.jsx(Nt,{isOpen:X,onClose:()=>{re(!1),le()},onSubmit:J,title:ie?"Edit Idea":"Add Idea",submitLabel:ie?"Update":"Create",fields:G.formFields(f)})]})}const wr=Object.freeze(Object.defineProperty({__proto__:null,default:er},Symbol.toStringTag,{value:"Module"}));function tr(){const t=Ue(),{activeSite:s}=St(),{activeSector:a,loadSectorsForSite:l}=Oe(),{pageSize:c}=qe(),[f,m]=r.useState([]),[d,h]=r.useState(!0),[u,g]=r.useState(!1),[n,j]=r.useState([]),O=r.useRef(new Set),[P,F]=r.useState(1),[ne,b]=r.useState(1),[q,D]=r.useState(0),[C,E]=r.useState("keyword"),[A,i]=r.useState("asc"),[S,T]=r.useState(""),[Z,M]=r.useState(""),[K,Q]=r.useState(""),[Y,L]=r.useState(""),[R,X]=r.useState("");r.useEffect(()=>{s!=null&&s.id&&l(s.id)},[s==null?void 0:s.id]);const re=r.useCallback(async()=>{if(!s||!s.industry){m([]),D(0),b(1),h(!1);return}h(!0),g(!1);try{let N=new Set;try{const{fetchKeywords:J,fetchSiteSectors:p}=await Me(async()=>{const{fetchKeywords:I,fetchSiteSectors:me}=await import("./page-dashboard-DxYTR5eF.js").then(he=>he.a7);return{fetchKeywords:I,fetchSiteSectors:me}},__vite__mapDeps([0,1,2,3,4,5,6])),_=await p(s.id);for(const I of _)try{((await J({site_id:s.id,sector_id:I.id,page_size:1e3})).results||[]).forEach(he=>{const ue=he.seed_keyword_id||he.seed_keyword&&he.seed_keyword.id;ue&&N.add(Number(ue))})}catch(me){console.warn(`Could not fetch attached keywords for sector ${I.id}:`,me)}}catch(J){console.warn("Could not fetch sectors or attached keywords:",J)}const w={industry:s.industry,page_size:1e3};a&&a.industry_sector&&(w.sector=a.industry_sector),S&&(w.search=S),Z&&(w.intent=Z);let x=[],V=1,W=!0;for(;W;){const J={...w,page:V},p=await ft(J);if(p.results&&p.results.length>0&&(x=[...x,...p.results]),W=p.next!==null&&p.next!==void 0,V++,V>100){console.warn("Reached maximum page limit (100) while fetching seed keywords");break}}let H=x.map(J=>{const p=N.has(Number(J.id))||O.current.has(Number(J.id));return{...J,isAdded:!!p}});if(K){const J=parseInt(K),p=wt(J);if(p!==null){const _=vt(p);_&&(H=H.filter(I=>I.difficulty>=_.min&&I.difficulty<=_.max))}}Y!==""&&Y!==null&&Y!==void 0&&(H=H.filter(J=>J.volume>=Number(Y))),R!==""&&R!==null&&R!==void 0&&(H=H.filter(J=>J.volume<=Number(R))),C&&H.sort((J,p)=>{let _,I;if(C==="keyword")_=J.keyword.toLowerCase(),I=p.keyword.toLowerCase();else if(C==="volume")_=J.volume,I=p.volume;else if(C==="difficulty")_=J.difficulty,I=p.difficulty;else if(C==="intent")_=J.intent.toLowerCase(),I=p.intent.toLowerCase();else return 0;return _<I?A==="asc"?-1:1:_>I?A==="asc"?1:-1:0});const ee=H.length,te=c||10,G=(P-1)*te,fe=G+te,le=H.slice(G,fe);m(le),D(ee),b(Math.ceil(ee/te)),g(!0)}catch(N){console.error("Error loading seed keywords:",N),t.error(`Failed to load keyword opportunities: ${N.message}`),m([]),D(0),b(1)}finally{h(!1)}},[s,a,P,c,S,Z,K,Y,R,C,A]);r.useEffect(()=>{re()},[re]),r.useEffect(()=>{const N=setTimeout(()=>{F(1)},500);return()=>clearTimeout(N)},[S]),r.useEffect(()=>{F(1)},[c]);const ie=(N,w)=>{E(N||"keyword"),i(w),F(1)},oe=r.useCallback(async N=>{var x;if(!s){t.error("Please select an active site first");return}let w=a;if(!w)try{const{fetchSiteSectors:V}=await Me(async()=>{const{fetchSiteSectors:H}=await import("./page-dashboard-DxYTR5eF.js").then(ee=>ee.a7);return{fetchSiteSectors:H}},__vite__mapDeps([0,1,2,3,4,5,6])),W=await V(s.id);if(W.length===0){t.error("No sectors available for this site. Please create a sector first.");return}w={id:W[0].id,name:W[0].name,slug:W[0].slug,site_id:s.id,is_active:W[0].is_active!==!1,industry_sector:W[0].industry_sector||null}}catch(V){t.error(`Failed to get sectors: ${V.message}`);return}try{const V=await ks(N,s.id,w.id);V.success?(t.success(`Successfully added ${V.created} keyword(s) to workflow`),N.forEach(W=>{O.current.add(W)}),j([]),m(W=>W.map(H=>N.includes(H.id)?{...H,isAdded:!0}:H))):t.error(`Failed to add keywords: ${((x=V.errors)==null?void 0:x.join(", "))||"Unknown error"}`)}catch(V){t.error(`Failed to add keywords: ${V.message}`)}},[s,a,t]),be=r.useCallback(async N=>{if(N.length===0){t.error("Please select at least one keyword");return}const w=N.filter(V=>{const W=f.find(H=>String(H.id)===V);return W&&!W.isAdded});if(w.length===0){t.error("All selected keywords are already added to workflow");return}w.length<N.length&&t.info(`${N.length-w.length} keyword(s) were already added and were skipped`);const x=w.map(V=>parseInt(V));await oe(x)},[oe,t,f]),we=r.useCallback(async()=>{if(!s||!s.industry){t.error("Please select an active site first");return}try{const N={industry:s.industry,page_size:1e3};a!=null&&a.industry_sector&&(N.sector=a.industry_sector);const x=(await ft(N)).results||[];if(x.length===0){t.error("No keywords available to add");return}const{fetchKeywords:V,fetchSiteSectors:W}=await Me(async()=>{const{fetchKeywords:fe,fetchSiteSectors:le}=await import("./page-dashboard-DxYTR5eF.js").then(J=>J.a7);return{fetchKeywords:fe,fetchSiteSectors:le}},__vite__mapDeps([0,1,2,3,4,5,6])),H=await W(s.id);let ee=new Set;for(const fe of H)try{((await V({site_id:s.id,sector_id:fe.id,page_size:1e3})).results||[]).forEach(J=>{const p=J.seed_keyword_id||J.seed_keyword&&J.seed_keyword.id;p&&ee.add(Number(p))})}catch(le){console.warn(`Could not fetch attached keywords for sector ${fe.id}:`,le)}const te=x.filter(fe=>!ee.has(fe.id));if(te.length===0){t.error("All keywords are already added to workflow");return}te.length<x.length&&t.info(`${x.length-te.length} keyword(s) were already added and were skipped`);const G=te.map(fe=>fe.id);await oe(G)}catch(N){t.error(`Failed to load all keywords: ${N.message}`)}},[s,a,oe,t]),ge=r.useMemo(()=>({columns:[{key:"keyword",label:"Keyword",sortable:!0,sortField:"keyword"},...!a?[{key:"sector_name",label:"Sector",sortable:!1,render:(w,x)=>e.jsx(ut,{color:"info",size:"sm",variant:"light",children:x.sector_name||"-"})}]:[],{key:"volume",label:"Volume",sortable:!0,sortField:"volume",render:w=>w.toLocaleString()},{key:"difficulty",label:"Difficulty",sortable:!0,sortField:"difficulty",align:"center",render:w=>{const x=Ss(w),V=typeof x=="number"&&x===5?"solid":typeof x=="number"&&(x===2||x===3||x===4)?"light":typeof x=="number"&&x===1?"solid":"light",W=typeof x=="number"&&x===1||typeof x=="number"&&x===2?"success":typeof x=="number"&&x===3?"warning":typeof x=="number"&&x===4||typeof x=="number"&&x===5?"error":"light";return typeof x=="number"?e.jsx(ut,{color:W,variant:V,size:"sm",children:x}):x}},{key:"intent",label:"Intent",sortable:!0,sortField:"intent",render:w=>{const x=V=>{const W=(V==null?void 0:V.toLowerCase())||"";return W==="transactional"||W==="commercial"?"success":W==="navigational"?"warning":"info"};return e.jsx(ut,{color:x(w),size:"sm",variant:(w==null?void 0:w.toLowerCase())==="informational"?"light":void 0,children:w})}}],filters:[{key:"search",label:"Search",type:"text",placeholder:"Search keywords..."},{key:"intent",label:"Intent",type:"select",options:[{value:"",label:"All Intent"},{value:"informational",label:"Informational"},{value:"navigational",label:"Navigational"},{value:"transactional",label:"Transactional"},{value:"commercial",label:"Commercial"}]},{key:"difficulty",label:"Difficulty",type:"select",options:[{value:"",label:"All Difficulty"},{value:"1",label:"1 - Very Easy"},{value:"2",label:"2 - Easy"},{value:"3",label:"3 - Medium"},{value:"4",label:"4 - Hard"},{value:"5",label:"5 - Very Hard"}]}]}),[a]);return e.jsx(e.Fragment,{children:e.jsx(at,{title:"Keyword Opportunities",titleIcon:e.jsx(pt,{className:"text-brand-500 size-5"}),subtitle:"Discover and add keywords to your workflow",columns:ge.columns,data:f,loading:d,showContent:u,filters:ge.filters,filterValues:{search:S,intent:Z,difficulty:K},onFilterChange:(N,w)=>{const x=w==null?"":String(w);N==="search"?T(x):N==="intent"?(M(x),F(1)):N==="difficulty"&&(Q(x),F(1))},onRowAction:async(N,w)=>{if(N==="add_to_workflow"){if(w.isAdded){t.info("This keyword is already added to workflow");return}await oe([w.id])}},onBulkAction:async(N,w)=>{N==="add_selected_to_workflow"&&await be(w)},onCreate:we,createLabel:"Add All to Workflow",onCreateIcon:e.jsx(Ve,{}),pagination:{currentPage:P,totalPages:ne,totalCount:q,onPageChange:F},sorting:{sortBy:C,sortDirection:A,onSort:ie},selection:{selectedIds:n,onSelectionChange:j}})})}const vr=Object.freeze(Object.defineProperty({__proto__:null,default:tr},Symbol.toStringTag,{value:"Module"}));export{br as C,xr as D,Nt as F,pr as H,wr as I,yr as K,Le as P,rt as S,at as T,qe as a,_t as b,Ct as c,$s as d,St as e,vr as f,Oe as u};
|