1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-Dq2zLArw.js","assets/query-_koPiPsI.js","assets/react-vendor-h1rQ_Bae.js","assets/ui-radix-CKwvnS8F.js","assets/supabase-DL6nu9mS.js","assets/charts-Xu79y1bN.js","assets/motion-nVmI7L5T.js","assets/index-DKBqfRLs.css"])))=>i.map(i=>d[i]); 2import{d as ss}from"./supabase-DL6nu9mS.js";import{b as ts,j as e,u as pe}from"./query-_koPiPsI.js";import{f as ie,r as o,h as as}from"./react-vendor-h1rQ_Bae.js";import{c as ke,g as b,f as he,s as S,C as q,n as G,al as rs,O as ns,e as se,B as N,S as te,L as ee,y as Se,V as is,k as R,ah as Fe,a1 as de,X as fe,Z as ls,J as ze,a0 as os,v as ge,E as cs,D as ds,h as ms,i as us,j as hs,I as je,t as xs,T as Oe,a as Re,b as me,o as ye,p as ve,N as ps,K as fs,q as gs,ao as js,ai as Ve,H as ys,G as vs}from"./index-Dq2zLArw.js";import{S as ws}from"./switch-CyEfQhNS.js";import{u as bs,C as Ns}from"./useUsageLimits-CvkMyGTN.js";import{n as ce,C as _s}from"./notifyError-B5A7t736.js";import{P as Be}from"./plus-BKP-C_hU.js";import{D as Cs,a as ks,b as Ss,c as ne,C as Is,L as Ds}from"./dropdown-menu-BvquEsnV.js";import{D as qe}from"./dollar-sign-BHebF1F9.js";import{G as $s}from"./grip-vertical-s3_ZjWHt.js";import{T as Ge}from"./trash-2-DwNrObEE.js";import{C as Ps}from"./chevron-right-N8QrdNsP.js";import{L as We}from"./layout-grid-CCNctG8l.js";import{L as As}from"./lightbulb-DmQhwTLA.js";import{C as Ts}from"./circle-check-big-BlhODvES.js";import{F as Es}from"./file-pen-C1-gMAg1.js";import{S as we,a as be,b as Ne,c as _e,d as Q}from"./select-S0HS5dUY.js";import{T as Ce}from"./target-BFvLTc1H.js";import{B as Ls}from"./book-open-C0MfautB.js";import{A as Ms}from"./activity-cfZN1jba.js";import{M as Fs}from"./message-square-C6C943k8.js";import"./ui-radix-CKwvnS8F.js";import"./charts-Xu79y1bN.js";import"./motion-nVmI7L5T.js";import"./circle-CflMNCk5.js";import"./chevron-up-Dbq7Df3-.js";/** 3 * @license lucide-react v0.462.0 - ISC 4 * 5 * This source code is licensed under the ISC license. 6 * See the LICENSE file in the root directory of this source tree. 7 */const ue=ke("CalendarDays",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M16 14h.01",key:"1gbofw"}],["path",{d:"M8 18h.01",key:"lrp35t"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M16 18h.01",key:"kzsmim"}]]);/** 8 * @license lucide-react v0.462.0 - ISC 9 * 10 * This source code is licensed under the ISC license. 11 * See the LICENSE file in the root directory of this source tree. 12 */const zs=ke("EllipsisVertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]);/** 13 * @license lucide-react v0.462.0 - ISC 14 * 15 * This source code is licensed under the ISC license. 16 * See the LICENSE file in the root directory of this source tree. 17 */const Os=ke("ShoppingCart",[["circle",{cx:"8",cy:"21",r:"1",key:"jimo8o"}],["circle",{cx:"19",cy:"21",r:"1",key:"13723u"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12",key:"9zh506"}]]);function Ie(){const{isSubscriber:a}=bs(),f=ie();return o.useCallback((p="this AI feature")=>a?!0:(b.error("Subscription required",{description:`Upgrade to keep using ${p}. Your work is saved.`,duration:8e3,action:{label:"Upgrade",onClick:()=>f("/pricing")}}),!1),[a,f])}function Rs({pillars:a,planDuration:f,onPlanGenerated:p}){const{user:c}=he(),g=ts(),E=Ie(),[j,x]=o.useState([]),[w,P]=o.useState(""),[v,D]=o.useState(!1),[y,A]=o.useState([]),[_,T]=o.useState(a),[m,V]=o.useState(!1),[i,s]=o.useState([]),[t,d]=o.useState(!1),u=o.useRef(null),C=o.useRef(null);o.useEffect(()=>{T(a)},[a]),o.useEffect(()=>{if(!c)return;let r=!1;return(async()=>{const{data:h}=await S.from("content_plan_chats").select("messages, pending_suggestions, viral_posts, last_research_mode").eq("user_id",c.id).maybeSingle();r||(h&&(Array.isArray(h.messages)&&x(h.messages),Array.isArray(h.pending_suggestions)&&A(h.pending_suggestions),Array.isArray(h.viral_posts)&&s(h.viral_posts),typeof h.last_research_mode=="boolean"&&V(h.last_research_mode)),d(!0))})(),()=>{r=!0}},[c?.id]),o.useEffect(()=>{if(!(!c||!t))return C.current&&window.clearTimeout(C.current),C.current=window.setTimeout(()=>{S.from("content_plan_chats").upsert({user_id:c.id,messages:j,pending_suggestions:y,viral_posts:i,last_research_mode:m,updated_at:new Date().toISOString()},{onConflict:"user_id"}).then(()=>{})},1200),()=>{C.current&&window.clearTimeout(C.current)}},[c?.id,t,j,y,i,m]);const l=async()=>{x([]),A([]),s([]),c&&await S.from("content_plan_chats").upsert({user_id:c.id,messages:[],pending_suggestions:[],viral_posts:[],last_research_mode:m,updated_at:new Date().toISOString()},{onConflict:"user_id"})},$=()=>{u.current?.scrollIntoView({behavior:"smooth"})};o.useEffect(()=>{$()},[j]),o.useEffect(()=>{const r=h=>{const k=h.detail;typeof k=="string"&&k.length>0&&P(k)};return window.addEventListener("tf:content-plan-seed",r),()=>window.removeEventListener("tf:content-plan-seed",r)},[]);const L=async r=>{if(c&&E(m?"viral research":"AI planning")){D(!0);try{const h=await S.auth.getSession();if(!h.data.session){b.error("Please log in to generate content plans");return}const k=r?[...j,{role:"user",content:r}]:j;r&&(x(k),P(""));const{data:z,error:B}=await S.functions.invoke("generate-content-plan",{body:{messages:k.map(K=>({role:K.role,content:K.content})),pillars:_.map(K=>({id:K.id,name:K.name})),planDuration:f,researchMode:m},headers:{Authorization:`Bearer ${h.data.session.access_token}`}});if(B)throw B;const Y={role:"assistant",content:z.message,suggestions:z.suggestions,viralResearch:z.viralResearch};x([...k,Y]),z.suggestions?.length>0&&A(z.suggestions),z.viralResearch?.viral_posts?.length>0&&s(z.viralResearch.viral_posts),z.newPillar&&(T(K=>[...K,z.newPillar]),g.invalidateQueries({queryKey:["content-pillars"]}),b.success(`Created new pillar: ${z.newPillar.name}`))}catch(h){console.error("Generate plan error:",h),ce(h,m?"viral-research":"content-plan")}finally{D(!1)}}},U=r=>{r.preventDefault(),!(!w.trim()||v)&&L(w.trim())},X=async r=>{if(c)try{let h=r.pillar_id;if(!h&&r.pillar_name){const B=_.find(Y=>Y.name.toLowerCase()===r.pillar_name?.toLowerCase());B&&(h=B.id)}const{data:k,error:z}=await S.rpc("approve_plan_topic",{p_topic:{title:r.title,outline:r.outline??null,pillar_id:h??null,status:"approved",target_date:r.target_date??null,plan_duration:f,notes:r.inspired_by?`${r.why_relevant} 18 19Inspired by: ${r.inspired_by}`:r.why_relevant}});if(z)throw z;k&&S.functions.invoke("enrich-plan-item",{body:{plan_item_id:k,keyword:r.title}}
19).then(({error:B})=>{B&&(console.warn("enrich-plan-item failed:",B.message),b.warning(`"${r.title}" added, but SEO evidence enrichment failed. It will retry when the item is opened.`))}).catch(B=>console.warn("enrich-plan-item threw:",B?.message)),A(B=>B.filter(Y=>Y.title!==r.title)),b.success(`Added "${r.title}" to your plan! Switch to Board view to see it.`),p()}catch(h){b.error(`Failed to add topic: ${h.message}`)}},le=r=>{A(h=>h.filter(k=>k.title!==r.title))},ae=async()=>{for(const r of y)await X(r)};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsx(q,{className:"glass-effect",children:e.jsxs(G,{className:"p-4 h-[600px] flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs text-muted-foreground mb-3 pb-3 border-b border-border/50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rs,{className:"w-3 h-3"}),e.jsxs("span",{children:[_.length," pillar",_.length!==1?"s":"",_.length>0&&e.jsxs("span",{className:"ml-1 hidden sm:inline",children:["(",_.map(r=>r.name).join(", "),")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ws,{id:"research-mode",checked:m,onCheckedChange:V,className:"scale-75"}),e.jsxs(ns,{htmlFor:"research-mode",className:"text-xs cursor-pointer flex items-center gap-1",children:[e.jsx(se,{className:"w-3 h-3"}),"Research Mode"]})]}),j.length>0&&e.jsx(N,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs text-muted-foreground hover:text-destructive",onClick:l,children:"Clear"})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto space-y-4 mb-4",children:[j.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center p-8",children:[e.jsx(te,{className:"w-12 h-12 text-primary mb-4"}),e.jsx("h3",{className:"text-xl font-semibold mb-2",children:m?"Viral Content Research":"Your Content Strategy Partner"}),e.jsx("p",{className:"text-muted-foreground mb-6 max-w-md",children:m?"I'll find viral posts on LinkedIn and X, analyze what makes them successful, and help you create your own spin.":`Chat with AI about your content goals. I'll help you brainstorm ideas, create pillars, and build your ${f}-day plan.`}),e.jsxs("div",{className:"flex flex-col gap-2",children:[m?e.jsxs(e.Fragment,{children:[e.jsxs(N,{variant:"default",onClick:()=>L("Find viral content about AI and startups"),disabled:v,className:"gap-2",children:[v?e.jsx(ee,{className:"w-4 h-4 animate-spin"}):e.jsx(se,{className:"w-4 h-4"}),"Find Viral AI & Startup Content"]}),e.jsx(N,{variant:"outline",onClick:()=>L("Find viral content about productivity and remote work"),disabled:v,children:"Find Viral Productivity Content"})]}):e.jsxs(N,{variant:"outline",onClick:()=>L("Hi! I'd like to plan my content strategy."),disabled:v,children:[v?e.jsx(ee,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(te,{className:"w-4 h-4 mr-2"}),"Start a Conversation"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"or type your own message below"})]})]}):j.map((r,h)=>e.jsx("div",{className:`flex ${r.role==="user"?"justify-end":"justify-start"}`,children:e.jsx("div",{className:`max-w-[85%] rounded-lg px-4 py-3 ${r.role==="user"?"bg-primary text-primary-foreground":"bg-muted"}`,children:e.jsx("p",{className:"whitespace-pre-wrap",children:r.content})})},h)),v&&e.jsx("div",{className:"flex justify-start",children:e.jsxs("div",{className:"bg-muted rounded-lg px-4 py-3 flex items-center gap-2",children:[e.jsx(ee,{className:"w-4 h-4 animate-spin"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:m?"Researching viral content...":"Thinking..."})]})}),e.jsx("div",{ref:u})]}),e.jsxs("form",{onSubmit:U,className:"flex gap-2",children:[e.jsx(Se,{value:w,onChange:r=>P(r.target.value),placeholder:m?"e.g., Find viral content about AI tools for founders...":"Chat about your content strategy...",className:"min-h-[60
19px] resize-none",onKeyDown:r=>{r.key==="Enter"&&!r.shiftKey&&(r.preventDefault(),U(r))}}),e.jsx(N,{type:"submit",size:"icon",disabled:!w.trim()||v,children:e.jsx(is,{className:"w-4 h-4"})})]})]})}),e.jsx(q,{className:"glass-effect",children:e.jsxs(G,{className:"p-4 h-[600px] overflow-y-auto",children:[m&&i.length>0&&y.length===0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2",children:[e.jsx(se,{className:"w-4 h-4 text-orange-500"}),"Trending Themes"]}),e.jsxs(R,{variant:"outline",className:"text-xs",children:[i.length," theme",i.length!==1?"s":""]})]}),e.jsx("div",{className:"space-y-3",children:i.slice(0,5).map((r,h)=>e.jsx(q,{className:"border-border/50",children:e.jsxs(G,{className:"p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(R,{variant:"secondary",className:`text-xs ${r.platform==="linkedin"?"bg-blue-500/10 text-blue-600":r.platform==="twitter"?"bg-sky-500/10 text-sky-600":"bg-purple-500/10 text-purple-600"}`,children:r.platform==="linkedin"?"LinkedIn":r.platform==="twitter"?"X":"General"}),r.engagement_signals&&e.jsx("span",{className:"text-xs text-muted-foreground line-clamp-1",children:r.engagement_signals})]}),e.jsx("p",{className:"text-sm mb-2",children:r.content}),r.key_patterns?.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1",children:r.key_patterns.slice(0,3).map((k,z)=>e.jsx(R,{variant:"outline",className:"text-xs",children:k},z))})]})},h))}),e.jsx("div",{className:"mt-4 text-center",children:e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"Ask me to generate topics inspired by these trends"})})]}),y.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2",children:[e.jsx(Fe,{className:"w-4 h-4"}),"Topic Suggestions"]}),e.jsxs(N,{size:"sm",variant:"outline",onClick:ae,children:[e.jsx(de,{className:"w-4 h-4 mr-1"}),"Approve All"]})]}),e.jsx("div",{className:"space-y-3",children:y.map((r,h)=>{const k=_.find(z=>z.id===r.pillar_id);return e.jsx(q,{className:"border-border/50",children:e.jsxs(G,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 mb-2",children:[e.jsx("h4",{className:"font-medium leading-tight",children:r.title}),e.jsxs("div",{className:"flex gap-1 flex-shrink-0",children:[e.jsx(N,{size:"icon",variant:"ghost",className:"h-7 w-7 text-green-500 hover:text-green-600 hover:bg-green-500/10",onClick:()=>X(r),children:e.jsx(de,{className:"w-4 h-4"})}),e.jsx(N,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive hover:bg-destructive/10",onClick:()=>le(r),children:e.jsx(fe,{className:"w-4 h-4"})})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-1 mb-2",children:[k&&e.jsxs(R,{variant:"outline",style:{borderColor:k.color,color:k.color},children:[k.icon," ",k.name]}),r.inspired_by&&e.jsxs(R,{variant:"secondary",className:"text-xs gap-1",children:[e.jsx(ls,{className:"w-3 h-3"}),"Viral-inspired"]})]}),e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:r.why_relevant}),r.outline&&e.jsxs("details",{className:"text-sm",children:[e.jsx("summary",{className:"cursor-pointer text-primary hover:underline",children:"View Outline"}),e.jsx("p",{className:"mt-2 text-muted-foreground whitespace-pre-wrap",children:r.outline})]})]})},h)})})]}),y.length===0&&i.length===0&&e.jsxs("div",{className:"flex flex-col items-center justify-center h-[500px] text-center text-muted-foreground",children:[e.jsx(Be,{className:"w-8 h-8 mb-2 opacity-50"}),e.jsx("p",{children:m?"Viral posts and suggestions will appear here":"Topic suggestions will appear here"}),e.jsx("p",{className:"text-sm mt-1",children:m?"Ask me to find viral content on any topic":"Chat with AI about your goals, then ask for topic ideas when you're ready"})]})]})})]})}function Vs(a){return a==null?"â":a>=1e3?`${(a/1e3).toFixed(a>=1e4?0:1)}K`:a.toString()}function Bs(a){return a==null?"text-muted-foreground":a<30?"text-green-600 dark:text-green-400":a<60?"text-yellow-600 dark:text-yellow-400":"text-orange-600 dar
19k:text-orange-400"}function qs({planItemId:a,autoEnrich:f=!0,keyword:p}){const[c,g]=o.useState(null),[E,j]=o.useState(!0),[x,w]=o.useState(null);return o.useEffect(()=>{let P=!1;return(async()=>{j(!0);const{data:v}=await S.from("content_plan_evidence").select("volume, difficulty, cpc, top_competitor").eq("plan_item_id",a).maybeSingle();if(P)return;if(v){g(v),j(!1);return}if(!f||!p){j(!1);return}const{data:D,error:y}=await S.functions.invoke("enrich-plan-item",{body:{plan_item_id:a,keyword:p}});P||(y?w("unavailable"):D?.success&&D.evidence?g(D.evidence):w(D?.errorCode||"unavailable"),j(!1))})(),()=>{P=!0}},[a,p,f]),E?e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-muted-foreground",children:[e.jsx(ee,{className:"w-3 h-3 animate-spin"}),e.jsx("span",{children:"Looking up SEO dataâ¦"})]}):!c||c.volume==null&&c.difficulty==null?e.jsx("div",{className:"text-[11px] text-muted-foreground italic",children:x==="SEMRUSH_UNAVAILABLE"?"No SEO data found":"SEO data unavailable"}):e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",title:"Monthly search volume",children:[e.jsx(ze,{className:"w-3 h-3"}),e.jsx("span",{className:"font-medium text-foreground",children:Vs(c.volume)}),e.jsx("span",{children:"/mo"})]}),e.jsxs("span",{className:"flex items-center gap-1",title:"Keyword difficulty (0â100)",children:[e.jsx(se,{className:"w-3 h-3"}),e.jsxs("span",{className:`font-medium ${Bs(c.difficulty)}`,children:["KD ",c.difficulty!=null?Math.round(c.difficulty):"â"]})]}),c.cpc!=null&&c.cpc>0&&e.jsxs("span",{className:"flex items-center gap-1",title:"Avg cost per click (commercial value)",children:[e.jsx(qe,{className:"w-3 h-3"}),e.jsx("span",{className:"font-medium text-foreground",children:c.cpc.toFixed(2)})]}),c.top_competitor&&e.jsxs("span",{className:"flex items-center gap-1",title:"Currently ranking #1",children:[e.jsx(os,{className:"w-3 h-3"}),e.jsx("span",{className:"truncate max-w-[140px]",children:c.top_competitor})]})]})}function Gs({item:a,pillar:f,onDragStart:p,onCreateArticle:c,onDraftFirstVersion:g,isDrafting:E=!1,onDelete:j,onUpdate:x,isDraggable:w}){const[P,v]=o.useState(!1),[D,y]=o.useState(a.title),[A,_]=o.useState(a.outline||""),T=()=>{x({title:D,outline:A||null}),v(!1)};return e.jsxs(e.Fragment,{children:[e.jsx(q,{className:`border-border/50 hover:border-border transition-colors ${w?"cursor-grab active:cursor-grabbing":""}`,draggable:w,onDragStart:m=>w&&p(m,a.id),children:e.jsx(G,{className:"p-3",children:e.jsxs("div",{className:"flex items-start gap-2",children:[w&&e.jsx($s,{className:"w-4 h-4 text-muted-foreground flex-shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm leading-tight line-clamp-2 mb-2",children:a.title}),f&&e.jsxs(R,{variant:"outline",className:"text-xs mb-2",style:{borderColor:f.color,color:f.color},children:[f.icon," ",f.name]}),a.target_date&&e.jsxs("p",{className:"text-xs text-muted-foreground mb-2",children:["Target: ",new Date(a.target_date).toLocaleDateString()]}),e.jsx(qs,{planItemId:a.id,keyword:a.title,autoEnrich:!0})]}),e.jsxs(Cs,{children:[e.jsx(ks,{asChild:!0,children:e.jsx(N,{variant:"ghost",size:"icon",className:"h-7 w-7",children:e.jsx(zs,{className:"w-4 h-4"})})}),e.jsxs(Ss,{align:"end",children:[e.jsxs(ne,{onClick:()=>v(!0),children:[e.jsx(ge,{className:"w-4 h-4 mr-2"}),"Edit"]}),["idea","approved"].includes(a.status)&&e.jsxs(e.Fragment,{children:[e.jsxs(ne,{onClick:g,disabled:E,children:[E?e.jsx(ee,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(te,{className:"w-4 h-4 mr-2"}),"Draft first version (AI)"]}),e.jsxs(ne,{onClick:c,children:[e.jsx(ge,{className:"w-4 h-4 mr-2"}),"Create Article (blank)"]})]}),a.article_id&&e.jsxs(ne,{onClick:()=>window.open(`/editor/${a.article_id}`,"_blank"),children:[e.jsx(cs,{className:"w-4 h-4 mr-2"}),"View Article"]}),e.jsxs(ne,{onClick:j,className:"text-destructive",children:[e.jsx(Ge,{className:"w-4 h-4 mr-2"}),"Delete"]})]})]})]})})}),e.jsx(ds,{open:P,onOpenChange:v,children:e.jsxs(ms,{children:[e.jsx(us,{children:e.jsx(hs,{children:"Edit Plan Item"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Title"}),e.jsx(je,{value:D,onChange:m=>y(m.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Outline"}),e.jsx(Se,{value:A,onChange:m=>_(m.target.value),rows:6,placeholder:"Add an outline for this topic..."})]})]}),e.jsxs(xs,{children:[e.jsx(N,{variant:"outline",onClick:()=>v(!1),children:"Cancel"}),e.jsx(N,{onClick:T,children:"Save"})]})]})})]})}const Ee={idea:"bg-yellow-500",approved:"bg-blue-500",draft:"bg-orange-500",scheduled:"bg-purple-500",published:"bg-green-500"};function Le(a){return a.toISOString().slice(0,10)}function Me(a){const f=a.getDay(),p=new Date(a);return p.setDate(a.getDate()-(f+6)%7),p.setHours(0,0,0,0),p}function Ws({planItems:a,onUpdate:f,onAddOnDate:p}){const c=ie(),[g,E]=o.useState(()=>
19Me(new Date)),[j,x]=o.useState(null),[w,P]=o.useState(null),v=4,D=o.useMemo(()=>{const i=[];for(let s=0;s<v*7;s++){const t=new Date(g);t.setDate(g.getDate()+s),i.push(t)}return i},[g]),y=o.useMemo(()=>{const i=new Map;for(const s of a){if(!s.target_date)continue;const t=s.target_date.slice(0,10);i.has(t)||i.set(t,[]),i.get(t).push(s)}return i},[a]),A=o.useMemo(()=>{let i=0;return y.forEach(s=>{s.length>i&&(i=s.length)}),i||1},[y]),_=a.filter(i=>!i.target_date&&["idea","approved"].includes(i.status)),T=async i=>{if(j){x(null),P(null);try{const{error:s}=await S.from("content_plan_items").update({target_date:i}).eq("id",j);if(s)throw s;b.success("Rescheduled"),f()}catch(s){b.error(`Failed: ${s.message}`)}}},m=i=>{if(i===0)return"bg-transparent";const s=Math.min(1,i/A);return s>.66?"bg-primary/20":s>.33?"bg-primary/10":"bg-primary/5"},V=Le(new Date);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(N,{variant:"outline",size:"icon",onClick:()=>{const i=new Date(g);i.setDate(i.getDate()-7),E(i)},children:e.jsx(_s,{className:"w-4 h-4"})}),e.jsx(N,{variant:"outline",size:"sm",onClick:()=>E(Me(new Date)),children:"This week"}),e.jsx(N,{variant:"outline",size:"icon",onClick:()=>{const i=new Date(g);i.setDate(i.getDate()+7),E(i)},children:e.jsx(Ps,{className:"w-4 h-4"})}),e.jsxs("span",{className:"ml-2 text-sm text-muted-foreground",children:[g.toLocaleDateString(void 0,{month:"short",day:"numeric"})," â"," ",D[D.length-1].toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),e.jsx("div",{className:"text-xs text-muted-foreground hidden sm:block",children:"Drag cards onto a day to schedule"})]}),e.jsx("div",{className:"grid grid-cols-7 gap-2 text-xs font-medium text-muted-foreground",children:["Mon","Tue","Wed","Thu","Fri","Sat","Sun"].map(i=>e.jsx("div",{className:"px-2",children:i},i))}),e.jsx("div",{className:"grid grid-cols-7 gap-2",children:D.map(i=>{const s=Le(i),t=y.get(s)||[],d=s===V,u=w===s;return e.jsxs("div",{onDragOver:C=>{C.preventDefault(),P(s)},onDragLeave:()=>P(null),onDrop:()=>T(s),className:`min-h-[110px] rounded-lg border p-2 transition-colors ${m(t.length)} ${u?"ring-2 ring-primary":""} ${d?"border-primary":"border-border/60"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:`text-xs ${d?"font-bold text-primary":"text-muted-foreground"}`,children:i.getDate()}),t.length===0&&p&&e.jsx("button",{type:"button",onClick:()=>p(s),className:"opacity-0 hover:opacity-100 group-hover:opacity-100 text-muted-foreground hover:text-foreground",title:"Plan content for this day",children:e.jsx(Be,{className:"w-3 h-3"})})]}),e.jsxs("div",{className:"space-y-1",children:[t.slice(0,3).map(C=>e.jsxs("div",{draggable:!0,onDragStart:()=>x(C.id),onClick:()=>C.article_id&&c(`/editor/${C.article_id}`),className:"text-[11px] leading-tight rounded px-1.5 py-1 bg-card border border-border/60 hover:border-border cursor-grab active:cursor-grabbing flex items-center gap-1",title:C.title,children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full flex-shrink-0 ${Ee[C.status]||"bg-muted"}`}),e.jsx("span",{className:"truncate",children:C.title})]},C.id)),t.length>3&&e.jsxs("div",{className:"text-[10px] text-muted-foreground",children:["+",t.length-3," more"]})]})]},s)})}),_.length>0&&e.jsx(q,{className:"border-dashed",children:e.jsxs(G,{className:"p-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Unscheduled ideas"}),e.jsx(R,{variant:"secondary",children:_.length})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:_.slice(0,20).map(i=>e.jsxs("div",{draggable:!0,onDragStart:()=>x(i.id),className:"text-xs rounded-md border px-2 py-1 bg-card cursor-grab active:cursor-grabbing max-w-[260px] truncate",title:i.title,children:[e.jsx("span",{className:`inline-block w-1.5 h-1.5 rounded-full mr-1.5 align-middle ${Ee[i.status]||"bg-muted"}`}),i.title]},i.id))}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-2",children:"Drag any of these onto a day above to schedule it."})]})})]})}const Us=[{id:"idea",label:"Ideas",icon:As,color:"text-yellow-500"},{id:"approved",label:"Approved",icon:Ts,color:"text-blue-500"},{id:"draft",label:"In Draft",icon:Es,color:"text-orange-500"},{id:"scheduled",label:"Scheduled",icon:ps,color:"text-purple-500"},{id:"published",label:"Published",icon:Ns,color:"text-green-500"}];function Hs({planItems:a,pillars:f,onUpdate:p}){const c=ie(),g=Ie(),[E,j]=o.useState(null),[x,w]=o.useState("kanban"),P=s=>a.filter(t=>t.status===s),v=(s,t)=>{j(t),s.dataTransfer.effectAllowed="move"},D=s=>{s.preventDefault(),s.dataTransfer.dropEffect="move"},y=async(s,t)=>{if(s.preventDefault(),!!E){if(["draft","scheduled","published"].includes(t)){b.info("This column is auto-updated when you create/publish articles"),j(null);return}try{const{error:d}=await S.from("content_plan_items").update({status:t}).eq("id",E);if(d)throw d;p()}catch(d){b.error(`Failed to update: ${d.message}`)}finally{j(null)}}},A=async s=>{const t=new URLSearchParams;t.set("planItemId",s.id),t.set("title",s.title),s.outline&&t.set("outline",s.outline),s.pillar_id&&t.set("pillar",s.pillar_id),c(`/editor/new?${t.toString()}`)},[_,T]=o.useState(null),m=async s=>{if(s.article_id){c(`/editor/${s.article_id}`);return}if(!g("AI drafting"))return;T(s.id);const t=b.loading("Drafting your first version with AI...");try{const{data:d,error:u}=await S.functions.invoke("draft-article-from-plan",{body:{planItemId:s.id}});if(u){b.dismiss(t),ce(u,"draft-from-plan",{planItemId:s.id});return}if(!d?.success){b.dismiss(t),ce(d??{error:"Failed to draft article"},"draft-from-plan",{planItemId:s.id});return}b.success("Rough draft ready â opening editor",{id:t}),p(),c(`/editor/${d.postId}`)}catch(d){b.dismiss(t),ce(d,"draft-from-plan",{planItemId:s.id})}finally{T(null)}},V=async s=>{try{const{error:t}=await S.from("content_plan_items").delete().eq("id",s);if(t)throw t;b.success("Item removed from plan"),p()}catch(t){b.error(`Failed to delete: ${t.message}`)}},i=async(s,t)=>{try{const{error:d}=await S.from("content_plan_items").update(t).eq("id",s);if(d)throw d;p()}catch(d){b.error(`Failed to update: ${d.message}`)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsx(Oe,{value:x,onValueChange:s=>w(s),children:e.jsxs(Re,{children:[e.jsxs(me,{value:"kanban",className:"gap-2",children:[e.jsx(We,{className:"w-4 h-4"}),e.jsx("span",{children:"Kanban"})]}),e.jsxs(me,{value:"calendar",className:"gap-2",children:[e.jsx(ue,{className:"w-4 h-4"}),e.jsx("span",{children:"Calendar"})]})]})})}),x==="calendar"?e.jsx(Ws,{planItems:a,onUpdate:p}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 lg:grid-cols-5 ga
19p-4",children:Us.map(s=>{const t=P(s.id),d=s.icon;return e.jsxs(q,{className:"glass-effect min-h-[400px]",onDragOver:D,onDrop:u=>y(u,s.id),children:[e.jsx(ye,{className:"pb-3",children:e.jsxs(ve,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(d,{className:`w-4 h-4 ${s.color}`}),s.label,e.jsx(R,{variant:"secondary",className:"ml-auto",children:t.length})]})}),e.jsx(G,{className:"space-y-3",children:t.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground text-sm",children:[s.id==="idea"&&"Add ideas from chat",s.id==="approved"&&"Approve topics to see them here",s.id==="draft"&&"Create articles from approved topics",s.id==="scheduled"&&"Schedule posts to see them here",s.id==="published"&&"Published content appears here"]}):t.map(u=>e.jsx(Gs,{item:u,pillar:u.content_pillars||void 0,onDragStart:v,onCreateArticle:()=>A(u),onDraftFirstVersion:()=>m(u),isDrafting:_===u.id,onDelete:()=>V(u.id),onUpdate:C=>i(u.id,C),isDraggable:["idea","approved"].includes(u.status)},u.id))})]},s.id)})})]})}function Ks({onClose:a,onComplete:f,initialTopic:p}){const{user:c}=he(),g=ie(),E=Ie(),[j,x]=o.useState(1),[w,P]=o.useState(!1),[v,D]=o.useState(!1),[y,A]=o.useState(0),[_,T]=o.useState(""),[m,V]=o.useState([]),[i,s]=o.useState(0),[t,d]=o.useState(!1),[u,C]=o.useState(!1),[l,$]=o.useState(""),[L,U]=o.useState(""),[X,le]=o.useState(p||""),[ae,r]=o.useState("aeo_geo"),[h,k]=o.useState([]),[z,B]=o.useState(!1),[Y,K]=o.useState(0),[De,$e]=o.useState(!1);o.useEffect(()=>{He(),Ue()},[]);const Ue=async()=>{if(!c)return;const{data:n}=await S.from("writer_profiles").select("business_description, ideal_customer, topics, primary_goal").eq("user_id",c.id).maybeSingle();n&&(n.business_description&&$(n.business_description),n.ideal_customer&&U(n.ideal_customer),!p&&Array.isArray(n.topics)&&n.topics.length>0&&le(n.topics.join(", ")),n.primary_goal&&r(n.primary_goal)),C(!0)},He=async()=>{P(!0);try{const n=await S.auth.getSession();if(!n.data.session)return;const{data:M,error:O}=await S.functions.invoke("analyze-site-content",{body:{mode:"detect"},headers:{Authorization:`Bearer ${n.data.session.access_token}`}});if(O)throw O;V(M.connectedCMS||[]),s(M.existingContentCount||0),d(M.needsQualifying)}catch(n){console.error("Detection error:",n)}finally{P(!1)}},Pe=!!(l&&L),Ae=t&&!Pe,Ke=async()=>{if(E("calendar planning")){D(!0),x(2),A(10),T("Analyzing your site content...");try{const n=await S.auth.getSession();if(!n.data.session)return;const M=[{pct:25,label:"Scanning existing articles..."},{pct:45,label:"Researching SEO keywords with Perplexity..."},{pct:65,label:"Identifying content gaps..."},{pct:80,label:"Building your 30-day plan..."},{pct:90,label:"Optimizing titles and outlines..."}],O=setInterval(()=>{A(I=>{const H=M.find(re=>re.pct>I);return H?(T(H.label),H.pct):I})},3e3),W={mode:"generate",planDuration:30};if((l||L||X)&&(W.businessContext={businessDescription:l,idealCustomer:L,topics:X,primaryGoal:ae},c)){const I=X?X.split(",").map(H=>H.trim()).filter(Boolean):void 0;await S.from("writer_profiles").upsert({user_id:c.id,business_description:l||null,ideal_customer:L||null,primary_goal:ae||null,...I?{topics:I}:{}},{onConflict:"user_id"}).then(({error:H})=>{H&&console.warn("writer_profiles upsert failed:",H.message)})}const{data:F,error:Z}=await S.functions.invoke("analyze-site-content",{body:W,headers:{Authorization:`Bearer ${n.data.session.access_token}`}});if(clearInterval(O),Z)throw Z;if(F&&F.success===!1){if(F.errorCode==="NO_SOURCE_CONTENT"){x(1),b.info(F.message||"Write your first article first.",{action:{label:"Write article",onClick:()=>g("/editor/new")},duration:1e4});return}if(F.errorCode==="INSUFFICIENT_CONTEXT"){d(!0),x(1),b.info(F.message||"Add a bit more context so we can build a useful plan.");return}if(F.errorCode==="AI_TEMPORARILY_UNAVAILABLE"){x(1),b.warning(F.message||"Planning engine is briefly busy. Try again in a minute.");return}x(1),b.error(F.message||"Couldn't build your plan. Try again in a moment.");return}A(100),T("Plan ready!"),B(F.seoResearchUsed),K(F.pillarsCreated||0);const J=(F.items||[]).map(I=>({...I,selected:!0}));k(J),setTimeout(()=>x(3),500)}catch(n){console.error("Generation error:",n),b.error("Couldn't build your plan right now. Try again in a moment."),x(1)}finally{D(!1)}}},Qe=async()=>
19{if(c){$e(!0);try{const n=h.filter(I=>I.selected);if(n.length===0){b.error("Select at least one topic to add");return}const M=n.map(I=>({title:I.title,outline:I.outline||null,notes:`Keyword: ${I.target_keyword} | Volume: ${I.search_volume}/mo | ${I.search_intent} | ${I.difficulty} difficulty${I.notes?` 20${I.notes}`:""}`,target_date:I.target_date,status:"idea",plan_duration:30,trending_source:"seo_analysis",pillar_id:I.pillar_id||null})),{data:O,error:W}=await S.rpc("save_plan_items_batch",{p_items:M});if(W)throw W;const F=O??{},Z=F.inserted_count??0,J=F.failed_count??0;if(Z>0&&J===0)b.success(`Added ${Z} articles to your calendar`,{description:"View them on the Schedule page"}),f();else if(Z>0&&J>0){const I=F.failures?.[0];b.warning(`Added ${Z} of ${Z+J} articles`,{description:I?`${J} failed. First error: ${I.error}`:`${J} rows failed â keep the wizard open and retry the failed items.`});const H=new Set((F.failures??[]).map(re=>re.title));k(re=>re.map(Te=>({...Te,selected:H.has(Te.title)})))}else{const I=F.failures?.[0];throw new Error(I?.error||"Failed to save plan")}}catch(n){b.error(n.message||"Failed to save plan")}finally{$e(!1)}}},Xe=n=>{k(M=>M.map((O,W)=>W===n?{...O,selected:!O.selected}:O))},Ye=n=>{k(M=>M.filter((O,W)=>W!==n))},Ze=(n,M)=>{k(O=>O.map((W,F)=>F===n?{...W,title:M}:W))},xe=h.filter(n=>n.selected).length,Je=n=>n==="low"?"text-green-600 bg-green-500/10":n==="medium"?"text-yellow-600 bg-yellow-500/10":"text-red-600 bg-red-500/10",es=n=>n==="commercial"?qe:n==="transactional"?Os:Ls;return j===1?e.jsxs("div",{className:"max-w-2xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(te,{className:"w-6 h-6 text-primary"}),"Plan your next 30 days of articles"]}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"We'll generate article ideas tied to your pillars. Once you publish each one, atomize to LinkedIn, X, and Threads in one click."})]}),e.jsx(N,{variant:"ghost",size:"icon",onClick:a,children:e.jsx(fe,{className:"w-5 h-5"})})]}),w||!u?e.jsx(q,{children:e.jsxs(G,{className:"py-12 text-center",children:[e.jsx(ee,{className:"w-8 h-8 animate-spin mx-auto mb-4 text-primary"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading your context..."})]})}):e.jsxs(e.Fragment,{children:[m.length>0?e.jsxs(q,{children:[e.jsx(ye,{children:e.jsxs(ve,{className:"text-sm flex items-center gap-2 text-muted-foreground font-normal",children:[e.jsx(fs,{className:"w-4 h-4"}),"Also publishing to"]})}),e.jsx(G,{children:e.jsxs("div",{className:"space-y-2",children:[m.map((n,M)=>e.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[e.jsx(de,{className:"w-4 h-4 text-green-500"}),e.jsx("span",{className:"font-medium capitalize",children:n.platform}),e.jsx("span",{className:"text-muted-foreground",children:n.siteUrl})]},M)),i>0&&e.jsxs("p",{className:"text-xs text-muted-foreground pt-1",children:["Found ",i," existing articles â we'll avoid duplicating topics."]})]})})]}):e.jsx(q,{className:"border-dashed",children:e.jsxs(G,{className:"py-3 flex items-center justify-between gap-3 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Optional â also publish to WordPress or Shopify when ready."}),e.jsx(N,{variant:"ghost",size:"sm",onClick:()=>g("/profile"),children:"Connect"})]})}),Ae&&e.jsxs(q,{children:[e.jsxs(ye,{children:[e.jsxs(ve,{className:"text-lg flex items-center gap-2",children:[e.jsx(Ce,{className:"w-5 h-5"}),"Two quick questions"]}),e.jsx(gs,{children:"We'll save these to your profile so we never ask again."})]}),e.jsxs(G,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-1.5 block",children:"What does your business do?"}),e.jsx(Se,{placeholder:"e.g., We sell project management software for remote teams...",value:l,onChange:n=>$(n.target.value),rows:2})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-1.5 block",children:"Who is your ideal customer?"}
20),e.jsx(je,{placeholder:"e.g., SaaS founders, ecommerce store owners, freelance designers",value:L,onChange:n=>U(n.target.value)})]}),e.jsxs("details",{className:"text-sm",children:[e.jsx("summary",{className:"cursor-pointer text-muted-foreground hover:text-foreground select-none",children:"Optional: topics & primary goal"}),e.jsxs("div",{className:"space-y-4 pt-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-1.5 block",children:"Topics you want to be known for"}),e.jsx(je,{placeholder:"e.g., productivity, remote work, team collaboration",value:X,onChange:n=>le(n.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-1.5 block",children:"Primary goal"}),e.jsxs(we,{value:ae,onValueChange:r,children:[e.jsx(be,{children:e.jsx(Ne,{})}),e.jsxs(_e,{children:[e.jsx(Q,{value:"aeo_geo",children:"Get cited by AI (AEO + GEO)"}),e.jsx(Q,{value:"traffic",children:"Rank on Google (organic traffic)"}),e.jsx(Q,{value:"authority",children:"Build authority on LinkedIn"}),e.jsx(Q,{value:"all",children:"All of the above"})]})]})]})]})]})]})]}),i===0&&!Pe?e.jsx(q,{className:"border-dashed",children:e.jsxs(G,{className:"py-6 space-y-3 text-center",children:[e.jsx("p",{className:"text-sm font-medium",children:"Write one article first"}),e.jsx("p",{className:"text-xs text-muted-foreground max-w-md mx-auto",children:"A 30-day plan only works when we can scan your real content. Publish one article and we'll build a plan around your topic and gaps â not generic ideas."}),e.jsxs("div",{className:"flex gap-2 justify-center pt-1",children:[e.jsxs(N,{variant:"hero",size:"sm",onClick:()=>g("/editor/new"),children:[e.jsx(ge,{className:"w-4 h-4 mr-2"}),"Write your first article"]}),e.jsx(N,{variant:"outline",size:"sm",onClick:()=>g("/profile"),children:"Connect WordPress / Shopify"})]})]})}):e.jsxs(e.Fragment,{children:[e.jsxs(N,{variant:"hero",size:"xl",className:"w-full",onClick:Ke,disabled:Ae&&(!l||!L),children:[e.jsx(ze,{className:"w-5 h-5 mr-2"}),"Plan my next 30 days"]}),e.jsx("p",{className:"text-xs text-center text-muted-foreground",children:i>0?`Scanning ${i} existing article${i===1?"":"s"} to avoid duplicates and find gaps.`:"Each plan item = one article. Social posts atomize from each published article."})]})]})]}):j===2?e.jsxs("div",{className:"max-w-lg mx-auto space-y-8 py-12",children:[e.jsxs("div",{className:"text-center",children:[e.jsx(te,{className:"w-12 h-12 text-primary mx-auto mb-4 animate-pulse"}),e.jsx("h2",{className:"text-2xl font-bold mb-2",children:"Building Your Content Plan"}),e.jsx("p",{className:"text-muted-foreground",children:"This usually takes 30-60 seconds"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(js,{value:y,className:"h-3"}),e.jsx("p",{className:"text-sm text-center text-muted-foreground",children:_})]})]}):e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(Fe,{className:"w-6 h-6 text-primary"}),"Your 30-Day Content Plan"]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[e.jsxs("p",{className:"text-muted-foreground",children:[h.length," articles ⢠",xe," selected"]}),z&&e.jsxs(R,{variant:"secondary",className:"gap-1",children:[e.jsx(se,{className:"w-3 h-3"}),"SEO Research Powered"]}),Y>0&&e.jsxs(R,{variant:"secondary",children:[Y," new pillars created"]})]})]}),e.jsx(N,{variant:"ghost",size:"icon",onClick:a,children:e.jsx(fe,{className:"w-5 h-5"})})]}),e.jsx("div",{className:"space-y-3",children:h.map((n,M)=>e.jsx(q,{className:`transition-all ${n.selected?"":"opacity-50"}`,children:e.jsx(G,{className:"py-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Is,{checked:n.selected,onCheckedChange:()=>Xe(M),className:"mt-1"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("input",{className:"font-medium text-base w-full bg-transparent border-none outline-none focus:ring-0 p-0",value:n.title,onChange:O=>Ze(M,O.target.value)}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mt-2",children:[e.jsxs(R,{variant:"outline",className:"text-xs gap-1",children:[e.jsx(Ce,{className:"w-3 h-3"})," ",n.target_keyword]}),n.search_volume&&e.jsxs(R,{variant:"outline",className:"text-xs gap-1",children:[e.jsx(se,{className:"w-3 h-3"})," ",n.search_volume,"/mo"]}),(()=>{const O=es(n.search_intent);return e.jsxs(R,{variant:"outline",className:"text-xs gap-1",children:[e.jsx(O,{className:"w-3 h-3"})," ",n.search_intent]}
20)})(),e.jsx(R,{className:`text-xs ${Je(n.difficulty)}`,children:n.difficulty}),n.pillar_name&&e.jsx(R,{variant:"secondary",className:"text-xs",children:n.pillar_name}),e.jsxs("span",{className:"text-xs text-muted-foreground ml-auto flex items-center gap-1",children:[e.jsx(ue,{className:"w-3 h-3"})," ",new Date(n.target_date).toLocaleDateString("en-US",{month:"short",day:"numeric"})]})]}),n.outline&&e.jsx("p",{className:"text-xs text-muted-foreground mt-2 line-clamp-2",children:n.outline})]}),e.jsx(N,{variant:"ghost",size:"icon",onClick:()=>Ye(M),className:"shrink-0",children:e.jsx(Ge,{className:"w-4 h-4 text-muted-foreground"})})]})})},M))}),e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs(N,{variant:"outline",onClick:()=>x(1),children:[e.jsx(Ve,{className:"w-4 h-4 mr-2"}),"Back"]}),e.jsxs(N,{variant:"hero",size:"lg",onClick:Qe,disabled:De||xe===0,children:[De?e.jsx(ee,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(de,{className:"w-4 h-4 mr-2"}),"Add ",xe," Articles to Calendar"]})]})]})}function Qs(a){return a?Math.floor((Date.now()-new Date(a).getTime())/(24*60*60*1e3)):1/0}function Xs({planItems:a,pillars:f,onPrompt:p}){const{user:c}=he(),g=o.useMemo(()=>{const l=Date.now(),$=l+30*24*60*60*1e3;return a.filter(L=>{if(!L.target_date)return!1;const U=new Date(L.target_date).getTime();return U>=l-24*60*60*1e3&&U<=$})},[a]),{data:E}=pe({queryKey:["plan-evidence",c?.id,g.map(l=>l.id).join(",")],queryFn:async()=>{if(!c||g.length===0)return[];const l=g.map(L=>L.id),{data:$}=await S.from("content_plan_evidence").select("plan_item_id, difficulty").in("plan_item_id",l);return $||[]},enabled:!!c&&g.length>0}),x=2*4,w=g.length,P=Math.min(100,Math.round(w/x*100)),v=new Map;g.forEach(l=>{const $=l.pillar_id||"unassigned";v.set($,(v.get($)||0)+1)});const D=g.length||1,y=f.map(l=>({pillar:l,count:v.get(l.id)||0,pct:Math.round((v.get(l.id)||0)/D*100)})),A=y.find(l=>l.pct>60),_=y.filter(l=>l.count===0&&f.length>1),T=new Map;(E||[]).forEach(l=>T.set(l.plan_item_id,l.difficulty));let m=0,V=0,i=0;g.forEach(l=>{const $=T.get(l.id);$==null||($<30?m++:$<60?V++:i++)});const s=m+V+i,t=s>=3&&m===0,d=a.filter(l=>l.status==="idea"&&Qs(l.created_at)>14).length,u=[];w<x&&u.push({label:`Only ${w} of ${x} target items scheduled in the next 30 days.`,cta:"Suggest more topics",prompt:`My plan has only ${w} items in the next 30 days. Suggest ${x-w} more topics that fit my pillars and don't overlap with what I already have.`}),A&&u.push({label:`Over-indexed on "${A.pillar.name}" (${A.pct}% of upcoming).`,cta:"Balance pillars",prompt:`My upcoming content is too heavy on "${A.pillar.name}". Suggest topics for my other pillars instead.`}),_.length>0&&u.push({label:`No upcoming content for: ${_.map(l=>l.pillar.name).join(", ")}.`,cta:"Fill empty pillars",prompt:`Suggest topics for these pillars that currently have no upcoming content: ${_.map(l=>l.pillar.name).join(", ")}.`}),t&&u.push({label:"All upcoming topics are medium-to-hard difficulty. Add some easy wins.",cta:"Add 2 easy wins",prompt:"Suggest 2 low-competition, low-difficulty topic ideas I can rank for quickly, that fit my pillars."}),d>0&&u.push({label:`${d} idea${d===1?"":"s"} sitting unread for >14 days.`,cta:"Review old ideas",prompt:`I have ${d} old ideas that haven't been touched. Help me decide which to keep, refine, or drop.`});const C=u.length===0;return e.jsx(q,{className:"glass-effect",children:e.jsxs(G,{className:"p-4 sm:p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 mb-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ms,{className:"w-4 h-4 text-primary"}),e.jsx("h3",{className:"font-semibold",children:"Plan Health"})]}),C?e.jsxs(R,{variant:"outline",className:"text-green-600 border-green-600/40 gap-1",children:[e.jsx(ys,{className:"w-3 h-3"})," Healthy"]}):e.jsxs(R,{variant:"outline",className:"text-orange-600 border-orange-600/40 gap-1",children:[e.jsx(vs,{className:"w-3 h-3"})," ",u.length," to fix"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 mb-4",children:[e.jsx(oe,{icon:e.jsx(Ce,{className:"w-3.5 h-3.5"}),label:"Next 30d",value:`${w} / ${x}`,sub:`${P}% of target`}),e.jsx(oe,{icon:e.jsx(Ds,{className:"w-3.5 h-3.5"}),label:"Pillars covered",value:`${y.filter(l=>l.count>0).length} / ${f.length||0}`,sub:f.length?`${_.length} empty`:"no pillars yet"}),e.jsx(oe,{label:"Easy wins",value:`${m}`,sub:s>0?`${Math.round(m/s*100)}% of scored`:"no SEO data yet"}),e.jsx(oe,{label:"Stale ideas",value:`${d}`,sub:d===0?"all fresh":"older than 14d"})]}),f.length>0&&D>0&&e.jsxs("div",{className:"mb-4",children:[e.jsx("div",{className:"text-xs text-muted-foreground mb-1.5",children:"Upcoming by pillar"}),e.jsx("div",{className:"flex h-2 rounded-full overflow-hidden bg-muted",children:y.filter(l=>l.count>
200).map(l=>e.jsx("div",{style:{width:`${l.pct}%`,backgroundColor:l.pillar.color},title:`${l.pillar.name}: ${l.count} (${l.pct}%)`},l.pillar.id))})]}),u.length>0?e.jsx("div",{className:"space-y-2",children:u.map((l,$)=>e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-md border border-border/60 px-3 py-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:l.label}),e.jsx(N,{size:"sm",variant:"outline",onClick:()=>p(l.prompt),children:l.cta})]},$))}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your plan looks balanced. Keep publishing on cadence."})]})})}function oe({icon:a,label:f,value:p,sub:c}){return e.jsxs("div",{className:"rounded-md border border-border/60 p-2.5",children:[e.jsxs("div",{className:"flex items-center gap-1 text-[11px] text-muted-foreground",children:[a,e.jsx("span",{children:f})]}),e.jsx("div",{className:"text-lg font-semibold leading-tight mt-0.5",children:p}),c&&e.jsx("div",{className:"text-[11px] text-muted-foreground mt-0.5",children:c})]})}function _t(){const{user:a,loading:f}=he(),p=ie(),[c,g]=as(),[E,j]=o.useState("chat"),[x,w]=o.useState(null),[P,v]=o.useState(30),[D,y]=o.useState(!1),[A,_]=o.useState(void 0);o.useEffect(()=>{const t=c.get("seedTopic");t&&_(t),c.get("mode")==="generate"&&(y(!0),c.delete("mode"),c.delete("seedTopic"),g(c,{replace:!0}))},[]);const{data:T}=pe({queryKey:["content-pillars",a?.id],queryFn:async()=>{if(!a)return[];const{data:t,error:d}=await S.from("content_pillars").select("*").eq("user_id",a.id).order("name");if(d)throw d;return t||[]},enabled:!!a}),{data:m,refetch:V}=pe({queryKey:["content-plan-items",a?.id,x],queryFn:async()=>{if(!a)return[];let t=S.from("content_plan_items").select("*, content_pillars(id, name, color, icon)").eq("user_id",a.id).order("created_at",{ascending:!1});x&&(t=t.eq("pillar_id",x));const{data:d,error:u}=await t;if(u)throw u;return d||[]},enabled:!!a}),[i,s]=o.useState(!1);return o.useEffect(()=>{if(!a||!m||i)return;const t=m.filter(d=>!d.article_id);if(t.length===0){s(!0);return}s(!0),(async()=>{const{data:d}=await S.from("posts").select("id, title, status").eq("user_id",a.id);if(!d?.length)return;const u=new Map;d.forEach(l=>u.set((l.title||"").trim().toLowerCase(),{id:l.id,status:l.status}));let C=0;for(const l of t){const $=u.get((l.title||"").trim().toLowerCase());if(!$)continue;const L=["draft","scheduled","published"].includes($.status)?$.status:l.status,{error:U}=await S.from("content_plan_items").update({article_id:$.id,status:L}).eq("id",l.id);U||C++}if(C>0){const{toast:l}=await ss(async()=>{const{toast:$}=await import("./index-Dq2zLArw.js").then(L=>L.bk);return{toast:$}},__vite__mapDeps([0,1,2,3,4,5,6,7]));l.success(`Linked ${C} plan item${C===1?"":"s"} to existing articles`),V()}})()},[a,m,i]),f||!a?e.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent"})}):e.jsx("div",{className:"min-h-screen bg-background",children:e.jsxs("main",{className:"container mx-auto px-4 sm:px-6 py-8",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-8",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(N,{variant:"ghost",size:"icon",onClick:()=>p("/dashboard"),children:e.jsx(Ve,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsxs("h1",{className:"text-3xl sm:text-4xl font-bold flex items-center gap-2",children:[e.jsx(te,{className:"w-8 h-8 text-primary"}),"Discoverability Plan"]}),e.jsx("p",{className:"text-muted-foreground",children:"Articles built to rank on Google, get cited by AI, and atomize into social posts"})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-3 w-full md:w-auto",children:[e.jsxs(N,{variant:"default",size:"sm",onClick:()=>y(!0),className:"gap-2",children:[e.jsx(ue,{className:"w-4 h-4"}),"Fill Calendar"]}),e.jsxs(N,{variant:"outline",size:"sm",onClick:()=>p("/schedule"),className:"gap-2",children:[e.jsx(ue,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"View on Calendar"})]}),e.jsxs(we,{value:x||"all",onValueChange:t=>w(t==="all"?null:t),children:[e.jsx(be,{className:"w-full sm:w-[180px]",children:e.jsx(Ne,{placeholder:"All Pillars"})}),e.jsxs(_e,{children:[e.jsx(Q,{value:"all",children:"All Pillars"}),T?.map(t=>e.jsx(Q,{value:t.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{children:t.icon}),t.name]})},t.id))]})]}),e.jsxs(we,{value:P.toString(),onValueChange:t=>v(Number(t)),children:[e.jsx(be,{className:"w-full sm:w-[140px]",children:e.jsx(Ne,{})}),e.jsxs(_e,{children:[e.jsx(Q,{value:"30",children:"30 Days"}),e.jsx(Q,{value:"60",children:"60 Days"}),e.jsx(Q,{value:"90",children:"90 Days"})]})]}),e.jsx(Oe,{value:E,onValueChange:t=>j(t),children:e.jsxs(Re,{children:[e.jsxs(me,{value:"chat",className:"gap-2",children:[e.jsx(Fs,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Chat"})]}),e.jsxs(me,{value:"board",className:"gap-2",children:[e.jsx(We,{className:"w-4 h-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Board"})]})]})})]})]}),D?e.jsx(Ks,{initialTopic:A,onClose:()=>{y(!1),_(void 0)},onComplete:()=>{y(!1),_(void 0),j("board"),V()}}):e.jsxs("div",{className:"space-y-6",children:[e.jsx(Xs,{planItems:m||[],pillars:T||[],onPrompt:t=>{j("chat"),window.dispatchEvent(new CustomEvent("tf:content-plan-seed",{detail:t}))}}),E==="chat"?e.jsx(Rs,{pillars:T||[],planDuration:P,onPlanGenerated:V}):e.jsx(Hs,{planItems:m||[],pillars:T||[],onUpdate:V}),e.jsxs("p",{className:"text-center text-xs text-muted-foreground pt-2",children:["Scheduled social posts (LinkedIn, X, Threads) appear on your"," ",e.jsx("button",{type:"button",onClick:()=>p("/schedule"),className:"underline underline-offset-2 hover:text-foreground",children:"Master Calendar"}),"."]})]})]})})}export{_t as default};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.