1import{u as P,j as e,b as se,c as Y}from"./query-_koPiPsI.js";import{r as _,f as X,h as xt,L as Z}from"./react-vendor-h1rQ_Bae.js";import{c as fe,u as ht,S as M,B as b,R as ie,X as Oe,T as $s,a as Fs,b as le,d as gs,C as q,s as f,e as ge,f as V,g as N,D as Ie,h as $e,i as Fe,j as De,k as F,L as Q,E as Ke,F as be,l as Le,m as je,n as D,o as O,p as K,q as J,r as pt,I as he,t as Ye,v as ne,w as ns,A as W,x as gt,y as re,z as oe,M as ft,G as ye,H as is,J as ls,K as xe,N as os,O as Je,P as fs,Q as pe,Z as Te,U as Ne,V as cs,W as Ee,Y as Ds,_ as Ls,$ as Es,a0 as zs,a1 as ze,a2 as Xe,a3 as jt,a4 as Rs,a5 as bt,a6 as yt,a7 as wt,a8 as Nt,a9 as vt,aa as kt,ab as _t,ac as Ct,ad as St,ae as qt,af as At}from"./index-Dq2zLArw.js";import{B as Ve,F as Ms,U as Pt,a as Tt,R as It,u as $t,S as Ft,G as Dt,b as js}from"./GeoUpgradeDiffDialog-Cj3UMIzE.js";import{T as Ge}from"./trash-2-DwNrObEE.js";import{A as Os,a as Ks,b as Gs,c as Ws,d as Bs,e as Us,f as Vs,g as Qs}from"./alert-dialog-DEwTsyDm.js";import{S as Lt}from"./switch-CyEfQhNS.js";import{C as Hs,a as Ys,b as Js}from"./collapsible-BqfEIKWx.js";import{S as bs}from"./scroll-area-Bj9Lyf-c.js";import{P as we}from"./plus-BKP-C_hU.js";import{W as ds}from"./wand-sparkles-DjjB0AGR.js";import{L as Ze}from"./lock-CB21B3PI.js";import{M as Xs}from"./message-square-C6C943k8.js";import{T as Zs}from"./thumbs-up-DIXQLZcT.js";import{L as Re}from"./lightbulb-DmQhwTLA.js";import{S as Et}from"./shield-alert-BIB5GtN7.js";import{C as zt}from"./chevron-up-Dbq7Df3-.js";import{A as Rt}from"./AdminAlertsDashboard-BtWasCOj.js";import{W as Mt}from"./wrench-LyUHElFj.js";import{T as Ot,a as Kt,b as ys,c as ke,d as Gt,e as _e}from"./table-BzZXAQMZ.js";import{S as es,a as ss,b as ts,c as as,d as ee}from"./select-S0HS5dUY.js";import{E as We}from"./eye-DeaWVGHm.js";import{U as Wt}from"./users-B5SvTFTu.js";import{T as et}from"./trending-down-DhyNl6tg.js";import{S as Bt,T as Ut,M as Vt}from"./tablet-CTHy_2cF.js";import{T as ms}from"./target-BFvLTc1H.js";import{u as Qt,g as Ht,P as ws,a as Yt,A as Ns}from"./recommender-289MKoHe.js";import{M as Jt}from"./mouse-pointer-click-B3fjeOvo.js";import{u as Xt}from"./usePublishedPosts-COsWyTJL.js";import{c as Zt,g as ea}from"./geoScore-CmpoRK6f.js";import{A as st}from"./arrow-up-1-Rt-S8S.js";import{A as tt}from"./arrow-down-BgB6QDVU.js";import{M as at}from"./minus-PALHGxhy.js";import{A as rs}from"./arrow-up-right-DgLfBzug.js";import{S as sa}from"./save-bi9ogCha.js";import{C as Me}from"./copy-BJMOZJfL.js";import{f as vs}from"./format-Bq4KMpNp.js";import{S as ta}from"./ShareLinkPopover-CU3zzJEv.js";import{P as aa,a as ra,b as na}from"./popover-CimjViyr.js";import"./ui-radix-CKwvnS8F.js";import"./supabase-DL6nu9mS.js";import"./charts-Xu79y1bN.js";import"./motion-nVmI7L5T.js";import"./purify.es-BlZidd4c.js";import"./info-DI8_flyN.js";/** 2 * @license lucide-react v0.462.0 - ISC 3 * 4 * This source code is licensed under the ISC license. 5 * See the LICENSE file in the root directory of this source tree. 6 */const ia=fe("Bell",[["path",{d:"M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9",key:"1qo2s2"}],["path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0",key:"qgo35s"}]]);/** 7 * @license lucide-react v0.462.0 - ISC 8 * 9 * This source code is licensed under the ISC license. 10 * See the LICENSE file in the root directory of this source tree. 11 */const la=fe("EyeOff",[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** 12 * @license lucide-react v0.462.0 - ISC 13 * 14 * This source code is licensed under the ISC license. 15 * See the LICENSE file in the root directory of this source tree. 16 */const ks=fe("FileInput",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M2 15h10",key:"jfw4w8"}],["path",{d:"m9 18 3-3-3-3",key:"112psh"}]]);/** 17 * @license lucide-react v0.462.0 - ISC 18 * 19 * This source code is licensed under the ISC license. 20 * See the LICENSE file in the root directory of this source tree. 21 */const oa=fe("ListTodo",[["rect",{x:"3",y:"5",width:"6",height:"6",rx:"1",key:"1defrl"}],["path",{d:"m3 17 2 2 4-4",key:"1jhpwq"}],["path",{d:"M13 6h8",key:"15sg57"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 18h8",key:"oe0vm4"}]]);/** 22 * @license lucide-react v0.462.0 - ISC 23 * 24 * This source code is licensed under the ISC license. 25 * See the LICENSE file in the root directory of this source tree. 26 */const ca=fe("Mic",[["path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z",key:"131961"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]);/** 27 * @license lucide-react v0.462.0 - ISC 28 * 29 * This source code is licensed under the ISC license. 30 * See the LICENSE file in the root directory of this source tree. 31 */const da=fe("NotebookPen",[["path",{d:"M13.4 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-7.4",key:"re6nr2"}],["path",{d:"M2 6h4",key:"aawbzj"}],["path",{d:"M2 10h4",key:"l0bgd4"}
31],["path",{d:"M2 14h4",key:"1gsvsf"}],["path",{d:"M2 18h4",key:"1bu2t1"}],["path",{d:"M21.378 5.626a1 1 0 1 0-3.004-3.004l-5.01 5.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"pqwjuv"}]]);/** 32 * @license lucide-react v0.462.0 - ISC 33 * 34 * This source code is licensed under the ISC license. 35 * See the LICENSE file in the root directory of this source tree. 36 */const ma=fe("ShieldOff",[["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M5 5a1 1 0 0 0-1 1v7c0 5 3.5 7.5 7.67 8.94a1 1 0 0 0 .67.01c2.35-.82 4.48-1.97 5.9-3.71",key:"1jlk70"}],["path",{d:"M9.309 3.652A12.252 12.252 0 0 0 11.24 2.28a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1v7a9.784 9.784 0 0 1-.08 1.264",key:"18rp1v"}]]),ua={"how-to":{label:"How-to",tone:"bg-blue-500/15 text-blue-600 dark:text-blue-400 border-blue-500/30"},framework:{label:"Framework",tone:"bg-purple-500/15 text-purple-600 dark:text-purple-400 border-purple-500/30"},contrarian:{label:"Contrarian",tone:"bg-amber-500/15 text-amber-600 dark:text-amber-400 border-amber-500/30"},data:{label:"Data",tone:"bg-emerald-500/15 text-emerald-600 dark:text-emerald-400 border-emerald-500/30"},story:{label:"Story",tone:"bg-pink-500/15 text-pink-600 dark:text-pink-400 border-pink-500/30"},"case-study":{label:"Case study",tone:"bg-cyan-500/15 text-cyan-600 dark:text-cyan-400 border-cyan-500/30"}},xa=()=>{const[s,r]=_.useState(!1),{toast:t}=ht(),d=X(),[n,i]=xt(),o=n.get("pillar"),{data:c}=P({queryKey:["pillar-info",o],enabled:!!o,queryFn:async()=>{const{data:x}=await f.from("content_pillars").select("name, icon, color").eq("id",o).maybeSingle();return x}}),{data:a,refetch:m}=P({queryKey:["topic-suggestions-fresh",o],queryFn:async()=>{let x=f.from("topic_suggestions").select("*").eq("used",!1).eq("saved",!1).order("generated_at",{ascending:!1}).limit(o?25:5);o&&(x=x.eq("pillar_id",o));const{data:v,error:T}=await x;if(T)throw T;return v}}),{data:h,refetch:g}=P({queryKey:["topic-suggestions-saved",o],queryFn:async()=>{let x=f.from("topic_suggestions").select("*").eq("saved",!0).order("generated_at",{ascending:!1});o&&(x=x.eq("pillar_id",o));const{data:v,error:T}=await x;if(T)throw T;return v}}),A=()=>{const x=new URLSearchParams(n);x.delete("pillar"),i(x,{replace:!0})},C=async()=>{r(!0);try{const x=o&&c?{pillarId:o,pillarName:c.name}:void 0,{error:v}=await f.functions.invoke("generate-topic-suggestions",x?{body:x}:{});if(v)throw v;t({title:"Fresh ideas generated!",description:o?"New ideas added for this pillar.":"5 new topic suggestions powered by real-time trends."}),m()}catch(x){console.error("Error generating suggestions:",x),t({title:"Generation failed",description:x.message||"Failed to generate topic suggestions. Please try again.",variant:"destructive"})}finally{r(!1)}},p=async x=>{f.from("topic_suggestions").update({used:!0,used_at:new Date().toISOString()}).eq("id",x.id).then(({error:$})=>{$?console.warn("Failed to mark topic as used:",$):(m(),g())});const v=x.article_h1_draft||x.headline,T=x.thesis||x.hook,G=x.why_only_you||x.why_trending,k=(x.outline&&x.outline.length?x.outline:x.key_points)||[],E=(x.evidence||[]).filter($=>$&&($.claim||$.source_url)),u=(x.sources||[]).filter($=>$&&$.url),S=[];x.target_reader&&S.push(`Target reader: ${x.target_reader}`),x.article_angle&&S.push(`Angle: ${x.article_angle}`);const R=S.length?S.join(` 37`)+` 38 39`:"",I=E.length?` 40 41Evidence: 42${E.map($=>`⢠${$.claim||""}${$.source_url?` (${$.source_url})`:""}`).join(` 43`)}`:"",B=u.length?` 44 45Research sources: 46${u.map($=>`⢠${$.title||$.url}${$.url&&$.title?` â ${$.url}`:""}`).join(` 47`)}`:"",ce=x.promotion_hook?` 48 49Optional bridge / CTA: ${x.promotion_hook}`:"",de=`${R}Thesis: ${T} 50 51Why only you: ${G}${I}${B} 52 53Outline: 54${k.map(($,te)=>`${te+1}. ${$}`).join(` 55`)}${ce} 56 57[Expand each beat with your voice, examples, and proof...]`;d("/editor/new",{state:{title:v,content:de,fromTopicSuggestion:!0}})},w=async x=>{await f.from("topic_suggestions").update({saved:!0}).eq("id",x),t({title:"Topic saved",description:"You can find it in the Saved Topics tab."}),m(),g()},L=async x=>{const{error:v}=await f.from("topic_suggestions").delete().eq("id",x);
57if(v){t({title:"Delete failed",description:v.message,variant:"destructive"});return}t({title:"Topic deleted"}),m(),g()},j=(x,v)=>{const T=x.thesis||x.hook,G=(x.outline&&x.outline.length?x.outline:x.key_points)||[],k=(x.evidence||[]).filter(I=>I&&(I.claim||I.source_url)),E=x.why_only_you||x.why_trending,u=(x.sources||[]).filter(I=>I&&I.url),S=x.article_angle?ua[x.article_angle.toLowerCase()]:null,R=x.article_h1_draft&&x.article_h1_draft!==x.headline?x.article_h1_draft:null;return e.jsx(q,{className:"p-6 glass-effect hover:shadow-glow transition-smooth",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center flex-shrink-0",children:e.jsx(ge,{className:"w-5 h-5 text-primary"})}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("h3",{className:"text-xl font-semibold",children:x.headline}),S&&e.jsx("span",{className:`text-[10px] uppercase tracking-wide font-semibold px-2 py-1 rounded border whitespace-nowrap ${S.tone}`,children:S.label})]}),(R||x.target_reader)&&e.jsxs("div",{className:"rounded-md border bg-card/40 p-2 space-y-1",children:[R&&e.jsxs("p",{className:"text-xs",children:[e.jsx("span",{className:"font-medium text-primary",children:"Article H1 draft:"})," ",R]}),x.target_reader&&e.jsxs("p",{className:"text-xs",children:[e.jsx("span",{className:"font-medium text-primary",children:"Target reader:"})," ",x.target_reader]})]}),T&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium text-primary",children:"Thesis:"}),e.jsx("p",{className:"text-sm",children:T})]}),E&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium text-primary",children:"Why only you:"}),e.jsx("p",{className:"text-sm italic",children:E})]}),k.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium text-primary",children:"Evidence:"}),e.jsx("ul",{className:"space-y-1",children:k.map((I,B)=>e.jsxs("li",{className:"text-sm flex items-start gap-2",children:[e.jsx("span",{className:"text-primary",children:"â¢"}),e.jsxs("span",{children:[I.claim,I.source_url&&e.jsxs(e.Fragment,{children:[" ",e.jsx("a",{href:I.source_url,target:"_blank",rel:"noreferrer noopener",className:"text-primary underline hover:opacity-80",children:"source"}),I.date?e.jsxs("span",{className:"text-muted-foreground",children:[" · ",I.date]}):null]})]})]},B))})]}),G.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium text-primary",children:"Outline:"}),e.jsx("ol",{className:"space-y-1 list-decimal list-inside",children:G.map((I,B)=>e.jsx("li",{className:"text-sm",children:I},B))})]}),u.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium text-primary",children:"Research sources:"}),e.jsx("ul",{className:"space-y-0.5",children:u.slice(0,5).map((I,B)=>e.jsxs("li",{className:"text-xs truncate",children:[e.jsx("a",{href:I.url,target:"_blank",rel:"noreferrer noopener",className:"text-primary underline hover:opacity-80",children:I.title||I.url}),I.source_type&&e.jsxs("span",{className:"text-muted-foreground ml-1",children:["· ",I.source_type]})]},B))})]}),x.promotion_hook&&e.jsxs("div",{className:"rounded-md border border-dashed border-primary/30 bg-primary/5 p-2",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide font-semibold text-primary mb-1",children:"Optional bridge / CTA"}),e.jsx("p",{className:"text-xs italic",children:x.promotion_hook})]}),e.jsxs("div",{className:"flex gap-2 mt-4",children:[e.jsxs(b,{onClick:()=>p(x),size:"sm",className:"gap-2",children:[e.jsx(M,{className:"w-4 h-4"}),"Start article"]}),v&&e.jsxs(b,{onClick:()=>w(x.id),variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(Ve,{className:"w-4 h-4"}),"Save for Later"]}),e.jsx(b,{onClick:()=>L(x.id),variant:"ghost",size:"sm",className:"gap-2",children:e.jsx(Ge,{className:"w-4 h-4"})})]})]})]})},x.id)};return e.jsxs("div",{className:"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(M,{className:"w-6 h-6 text-primary"}),"Content Radar"]}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"AI-curated topic inspiration tailored to YOUR niche"})]}),e.jsxs(b,{onClick:C,disabled:s,className:"gap-2",children:[e.jsx(ie,{className:`w-4 h-4 ${s?"animate-spin":""}`}),s?"Generating...":"Generate New Ideas"]})]}),o&&e.jsxs("div",{className:"flex items-center justify-between gap-3 p-3 rounded-lg border bg-card",style:c?{borderColor:`${c.color}40`,background:`linear-gradient(135deg, ${c.color}10 0%, transparent 100%)`}:void 0,children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[c?.icon&&e.jsx("span",{className:"text-lg",children:c.icon}),e.jsx("span",{className:"text-muted-foreground",children:"Filtering by pillar:"}),e.jsx("span",{className:"font-medium",children:c?.name??"Pillar"})]}),e.jsxs(b,{size:"sm",variant:"ghost",className:"gap-1",onClick:A,children:[e.jsx(Oe,{className:"w-3 h-3"})," Clear"]})]}),e.jsxs($s,{defaultValue:"fresh",className:"w-full",children:[e.jsxs(Fs,{className:"grid w-full max-w-md grid-cols-2",children:[e.jsxs(le,{value:"fresh",className:"gap-2",children:[e.jsx(M,{className:"w-4 h-4"}),"Fresh Ideas"]}),e.jsxs(le,{value:"saved",className:"gap-2",children:[e.jsx(Ve,{className:"w-4 h-4"}),"Saved Topics"]})]}),e.jsx(gs,{value:"fresh",className:"mt-6",children:a&&a.length>0?e.jsx("div",{className:"grid gap-4",children:a.map(x=>j(x,!0))}):e.jsxs(q,{className:"p-12 text-center glass-effect",children:[e.jsx(M,{className:"w-12 h-12 text-muted-foreground mx-auto mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No fresh ideas yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:o?'No ideas for this pillar yet. Click "Generate New Ideas" to create some.':'Click "Generate New Ideas" to get trending topic suggestions based on real-time data'})]})}),e.jsx(gs,{value:"saved",className:"mt-6",children:h&&h.length>0?e.jsx("div",{className:"grid gap-4",children:h.map(x=>j(x,!1))}):e.jsxs(q,{className:"p-12 text-center glass-effect",children:[e.jsx(Ve,{className:"w-12 h-12 text-muted-foreground mx-auto mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No saved topics"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Save topics from Fresh Ideas to revisit them anytime"})]})})]})]})};function ha({pillar:s,open:r,onClose:t}){const{user:d}=V(),n=se(),[i,o]=_.useState(!1),{data:c,isLoading:a}=P({queryKey:["pillar-items",s?.id],queryFn:async()=>
57{if(!s)return[];const{data:p,error:w}=await f.from("content_pillar_items").select(` 58 id, 59 post_id, 60 platform, 61 auto_tagged, 62 confidence_score 63 `).eq("pillar_id",s.id);if(w)throw w;const L=p.map(v=>v.post_id).filter(Boolean);if(L.length===0)return[];const{data:j}=await f.from("posts").select("id, title, slug, status, linkedin_post_url, twitter_post_url").in("id",L),x=new Map(j?.map(v=>[v.id,v])||[]);return p.map(v=>({...v,post:x.get(v.post_id)}))},enabled:!!s&&r}),{data:m}=P({queryKey:["unconnected-posts",s?.id,d?.id],queryFn:async()=>{if(!s||!d)return[];const{data:p}=await f.from("posts").select("id, title, slug, status, linkedin_published_at, twitter_published_at").eq("author_id",d.id).or("status.eq.published,linkedin_published_at.not.is.null,twitter_published_at.not.is.null"),{data:w}=await f.from("content_pillar_items").select("post_id").eq("pillar_id",s.id),L=new Set(w?.map(j=>j.post_id)||[]);return(p||[]).filter(j=>!L.has(j.id))},enabled:!!s&&r&&i}),h=Y({mutationFn:async p=>{if(!s)throw new Error("No pillar selected");const w=await f.auth.getSession(),{data:L,error:j}=await f.functions.invoke("auto-tag-pillar-content",{body:{pillarId:s.id,postId:p,action:"remove"},headers:{Authorization:`Bearer ${w.data.session?.access_token}`}});if(j)throw j;return L},onSuccess:()=>{n.invalidateQueries({queryKey:["pillar-items",s?.id]}),n.invalidateQueries({queryKey:["content-pillars"]}),n.invalidateQueries({queryKey:["unconnected-posts"]}),N.success("Content removed from pillar")},onError:p=>{N.error(`Failed to remove: ${p.message}`)}}),g=Y({mutationFn:async p=>{if(!s)throw new Error("No pillar selected");const w=await f.auth.getSession(),{data:L,error:j}=await f.functions.invoke("auto-tag-pillar-content",{body:{pillarId:s.id,postId:p,action:"add"},headers:{Authorization:`Bearer ${w.data.session?.access_token}`}});if(j)throw j;return L},onSuccess:()=>{n.invalidateQueries({queryKey:["pillar-items",s?.id]}),n.invalidateQueries({queryKey:["content-pillars"]}),n.invalidateQueries({queryKey:["unconnected-posts"]}),N.success("Content added to pillar"),o(!1)},onError:p=>{N.error(`Failed to add: ${p.message}`)}}),A=p=>{switch(p){case"linkedin":return e.jsx(je,{className:"w-4 h-4 text-[#0A66C2]"});case"twitter":return e.jsx(Le,{className:"w-4 h-4 text-foreground"});default:return e.jsx(be,{className:"w-4 h-4 text-primary"})}},C=p=>p.platform==="linkedin"&&p.post?.linkedin_post_url?p.post.linkedin_post_url:p.platform==="twitter"&&p.post?.twitter_post_url?p.post.twitter_post_url:p.post?.slug?`/${p.post.slug}`:null;return s?e.jsx(Ie,{open:r,onOpenChange:p=>!p&&t(),children:e.jsxs($e,{className:"max-w-lg",children:[e.jsxs(Fe,{children:[e.jsxs(De,{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-2xl",children:s.icon}),e.jsx("span",{children:s.name}),e.jsxs(F,{variant:"secondary",className:"ml-2",style:{backgroundColor:`${s.color}20`,color:s.color},children:[c?.length||0," items"]})]}),s.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:s.description})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Connected Content"}),e.jsxs(b,{size:"sm",variant:"outline",onClick:()=>o(!i),className:"gap-1",children:[e.jsx(we,{className:"w-3 h-3"}),"Add"]})]}),a?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Q,{className:"w-5 h-5 animate-spin text-muted-foreground"})}):c&&c.length>0?e.jsx(bs,{className:"h-[250px]",children:e.jsx("div",{className:"space-y-2 pr-4",children:c.map(p=>e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-card hover:bg-accent/50 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[A(p.platform),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:p.post?.title||"Untitled"}),e.jsx("div",{className:"flex items-center gap-2",children:p.auto_tagged&&e.jsxs(F,{variant:"outline",className:"text-xs gap-1 px-1.5 py-0",children:[e.jsx(M,{className:"w-2.5 h-2.5"}),"AI",p.confidence_score&&e.jsxs("span",{className:"ml-0.5",children:[Math.round(p.confidence_score*100),"%"]})]})})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[C(p)&&e.jsx(b,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>{const w=C(p);w&&window.open(w,"_blank")},children:e.jsx(Ke,{className:"w-3 h-3"})}),e.jsx(b,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive hover:text-destructive",onClick:()=>p.post_id&&h.mutate(p.post_id),disabled:h.isPending,children:e.jsx(Oe,{className:"w-3 h-3"})})]})]}
63,p.id))})}):e.jsx("div",{className:"text-center py-8 text-muted-foreground text-sm",children:"No content connected yet. Add some or let AI auto-tag!"})]}),i&&e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("h4",{className:"text-sm font-medium mb-2",children:"Add Content"}),m&&m.length>0?e.jsx(bs,{className:"h-[150px]",children:e.jsx("div",{className:"space-y-2 pr-4",children:m.map(p=>e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg border hover:bg-accent/50 transition-colors cursor-pointer",onClick:()=>g.mutate(p.id),children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[e.jsx(be,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm truncate",children:p.title})]}),e.jsx(we,{className:"w-4 h-4 text-muted-foreground"})]},p.id))})}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"All your content is already connected to this pillar!"})]})]})]})}):null}function pa({pillarId:s,pillarName:r,color:t}){const[d,n]=_.useState(!1),i=X(),{data:o,isLoading:c}=P({queryKey:["pillar-ideas",s],enabled:d,queryFn:async()=>{const{data:a,error:m}=await f.from("topic_suggestions").select("id, headline, hook, thesis, evidence, generated_at").eq("pillar_id",s).eq("used",!1).order("generated_at",{ascending:!1}).limit(5);if(m)throw m;return a||[]}});return e.jsxs(Hs,{open:d,onOpenChange:n,children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ys,{asChild:!0,children:e.jsxs(b,{size:"sm",variant:"ghost",className:"flex-1 gap-1 text-xs text-muted-foreground hover:text-foreground",onClick:a=>a.stopPropagation(),children:[e.jsx(ns,{className:`w-3 h-3 transition-transform ${d?"rotate-180":""}`}),"Latest ideas"]})}),e.jsxs(b,{size:"sm",variant:"ghost",className:"gap-1 text-xs",style:{color:t},onClick:a=>{a.stopPropagation(),i(`/?pillar=${s}#content-radar`),setTimeout(()=>{document.getElementById("content-radar")?.scrollIntoView({behavior:"smooth",block:"start"})},50)},title:`View all ideas for ${r} in Content Radar`,children:["View in Radar",e.jsx(W,{className:"w-3 h-3"})]})]}),e.jsx(Js,{children:e.jsx("div",{className:"mt-2 space-y-1.5 rounded-md border bg-card/50 p-2",onClick:a=>a.stopPropagation(),children:c?e.jsx("div",{className:"flex items-center justify-center py-3",children:e.jsx(Q,{className:"w-3 h-3 animate-spin text-muted-foreground"})}):o&&o.length>0?o.map(a=>{const m=Array.isArray(a.evidence)&&a.evidence.length?a.evidence.find(g=>g?.source_url)?.source_url:null,h=a.thesis||a.hook;return e.jsxs("button",{type:"button",className:"w-full text-left text-xs p-2 rounded hover:bg-accent transition-colors",onClick:g=>{g.stopPropagation(),i(`/?pillar=${s}#content-radar`),setTimeout(()=>{document.getElementById("content-radar")?.scrollIntoView({behavior:"smooth",block:"start"})},50)},children:[e.jsx("div",{className:"font-medium line-clamp-1",children:a.headline}),h&&e.jsx("div",{className:"text-muted-foreground line-clamp-2 mt-0.5",children:h}),m&&e.jsxs("div",{className:"text-[10px] text-primary/80 truncate mt-0.5",children:["ð ",new URL(m).hostname]})]},a.id)}):e.jsx("p",{className:"text-xs text-muted-foreground text-center py-2",children:'No ideas yet. Click "Generate 3 deep ideas" below.'})})})]})}const ga=[{value:"thought-leadership",label:"Thought leadership / POV essays"},{value:"industry-commentary",label:"Industry commentary on hot topics"},{value:"how-to-framework",label:"How-to / frameworks / playbooks"},{value:"personal-story",label:"Personal stories / behind the scenes"},{value:"case-study",label:"Case studies / data deep-dives"},{value:"contrarian",label:"Contrarian takes / myth-busting"}];function _s(s){return s.split(/[\n,]/).map(r=>r.trim().replace(/^https?:\/\//,"").replace(/\/.*$/,"").toLowerCase()).filter(Boolean)}function fa({pillar:s,open:r,onClose:t}){const{user:d}=V(),n=X(),i=se(),[o,c]=_.useState({audience:"",pov:"",proof:"",never_write:""}),[a,m]=_.useState({pillar_intent:"",competitor_domains:"",domain_allowlist:""}),{data:h,isLoading:g}=P({queryKey:["pillar-brief",s?.id],enabled:!!s&&r,queryFn:async()=>{const{data:k,error:E}=await f.from("pillar_briefs").select("audience, pov, proof, never_write").eq("pillar_id",s.id).maybeSingle();if(E)throw E;return k}}),{data:A}=P({queryKey:["pillar-cfg",s?.id],enabled:!!s&&r,queryFn:async()=>{const{data:k,error:E}=await f.from("content_pillars").select("pillar_intent, competitor_domains, domain_allowlist").eq("id",s.id).maybeSingle();if(E)throw E;return k}}),{data:C}=P({queryKey:["writer-profile-gate",d?.id],enabled:!!d&&r,queryFn:async()=>{const{data:k}=await f.from("writer_profiles").select("business_description, ideal_customer, projects, offers").eq("user_id",d.id).maybeSingle();return k}});_.useEffect(()=>{r&&c({audience:h?.audience||"",pov:h?.pov||"",proof:h?.proof||"",never_write:h?.never_write||""})},[r,h]),_.useEffect(()=>{r&&m({pillar_intent:A?.pillar_intent||"",competitor_domains:(A?.competitor_domains||[]).join(` 64`),domain_allowlist:(A?.domain_allowlist||[]).join(` 65`)})},[r,A]);const p=!!C?.business_description?.trim(),w=!!C?.ideal_customer?.trim(),L=Array.isArray(C?.projects)?C.projects:[],j=Array.isArray(C?.offers)?C.offers:[],x=L.length>0||j.length>0,v=p&&w&&x,T=Y({mutationFn:async()=>
65{if(!d||!s)throw new Error("Not ready");const k=f.from("pillar_briefs").upsert({pillar_id:s.id,user_id:d.id,audience:o.audience.trim()||null,pov:o.pov.trim()||null,proof:o.proof.trim()||null,never_write:o.never_write.trim()||null},{onConflict:"pillar_id"}),E=f.from("content_pillars").update({pillar_intent:a.pillar_intent||null,competitor_domains:_s(a.competitor_domains),domain_allowlist:_s(a.domain_allowlist)}).eq("id",s.id),[u,S]=await Promise.all([k,E]);if(u.error)throw u.error;if(S.error)throw S.error},onSuccess:()=>{i.invalidateQueries({queryKey:["pillar-brief",s?.id]}),i.invalidateQueries({queryKey:["pillar-cfg",s?.id]}),i.invalidateQueries({queryKey:["content-pillars"]}),N.success("Idea brief saved (private)"),t()},onError:k=>N.error(`Save failed: ${k.message}`)});if(!s)return null;const G=({ok:k,label:E})=>e.jsxs("div",{className:`flex items-center gap-2 text-xs ${k?"text-emerald-600 dark:text-emerald-400":"text-amber-600 dark:text-amber-400"}`,children:[e.jsx("span",{className:`w-4 h-4 rounded-full flex items-center justify-center text-[10px] font-bold ${k?"bg-emerald-500/15":"bg-amber-500/15 border border-amber-500/30"}`,children:k?"â":"!"}),e.jsx("span",{children:E})]});return e.jsx(Ie,{open:r,onOpenChange:k=>!k&&t(),children:e.jsxs($e,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(Fe,{children:[e.jsxs(De,{className:"flex items-center gap-2",children:[e.jsx(Ze,{className:"w-4 h-4 text-muted-foreground"}),"Idea brief â ",s.name]}),e.jsx(gt,{children:e.jsxs("span",{className:"flex items-center gap-1 text-xs",children:[e.jsx(Ze,{className:"w-3 h-3"})," Private. Only used to generate sharper ideas. Never shown on your personal site."]})})]}),g?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Q,{className:"w-5 h-5 animate-spin"})}):e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:`rounded-lg border p-3 space-y-2 ${v?"border-emerald-500/30 bg-emerald-500/5":"border-amber-500/40 bg-amber-500/5"}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-sm font-medium",children:v?"⨠Top-shelf mode unlocked":"Unlock top-shelf ideas"}),!v&&e.jsx(b,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>n("/profile"),children:"Open profile"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(G,{ok:p,label:"What your business does (business description)"}),e.jsx(G,{ok:w,label:"Who your ideal customer is"}),e.jsx(G,{ok:x,label:"At least 1 project or offer (proof)"})]}),!v&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Without these, ideas come out generic. We'd rather wait than ship weak ones."})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Who is this for?"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Your audience for this pillar (1-2 lines)."}),e.jsx(re,{rows:2,placeholder:"e.g., Solo SaaS founders doing $5K-$50K MRR who write to grow but hate generic LinkedIn advice.",value:o.audience,onChange:k=>c({...o,audience:k.target.value})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Your POV / hot takes"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"What do you believe most people in this space get wrong?"}),e.jsx(re,{rows:4,placeholder:"e.g., Most 'content strategy' advice ignores distribution. Volume kills voice.",value:o.pov,onChange:k=>c({...o,pov:k.target.value})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Proof you can cite"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Wins, data, stories, client examples â messy notes are fine."}),e.jsx(re,{rows:4,placeholder:"e.g., Grew 0 â 12K followers in 6 months. One client's CAC dropped 40% after switching to long-form.",value:o.proof,onChange:k=>c({...o,proof:k.target.value})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Never write about"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Angles, framings, words to avoid for this pillar."}),e.jsx(re,{rows:2,placeholder:"e.g., No 'X lessons I learned' listicles. Never frame as guru advice.",value:o.never_write,onChange:k=>c({...o,never_write:k.target.value})})]}),e.jsxs("div",{className:"rounded-lg border p-3 space-y-3 bg-card/40",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Research sources"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Tune what the idea engine looks at for this pillar. All optional â smart defaults are used otherwise."})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium",children:"Pillar intent"}),e.jsx("p",{className:"text-[11px] text-muted-foreground mb-1",children:"Shapes how heavily we weight trends vs. your POV."}),e.jsxs("select",{className:"w-full h-9 rounded-md border bg-background px-2 text-sm",value:a.pillar_intent,onChange:k=>m({...a,pillar_intent:k.target.value}),children:[e.jsx("option",{value:"",children:"Auto (let the engine decide)"}),ga.map(k=>e.jsx("option",{value:k.value,children:k.label},k.value))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium",children:"Competitor / reference domains"}),e.jsx("p",{className:"text-[11px] text-muted-foreground mb-1",children:"One per line. We surface what they're writing about and avoid duplicating."}),e.jsx(re,{rows:3,placeholder:`e.g. 66lennysnewsletter.com 67first1000.substack.com`,value:a.competitor_domains,onChange:k=>m({...a,competitor_domains:k.target.value})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs font-medium",children:"Trusted domain allowlist (advanced)"}),e.jsx("p",{className:"text-[11px] text-muted-foreground mb-1",children:"Restrict trend research to these domains. Leave empty for smart defaults (LinkedIn, X, HN, Reddit, industry pubs)."}),e.jsx(re,{rows:2,placeholder:`e.g.
68news.ycombinator.com 69reddit.com 70linkedin.com`,value:a.domain_allowlist,onChange:k=>m({...a,domain_allowlist:k.target.value})})]})]})]}),e.jsxs(Ye,{children:[e.jsx(b,{variant:"ghost",onClick:t,children:"Cancel"}),e.jsx(b,{onClick:()=>T.mutate(),disabled:T.isPending,children:T.isPending?"Saving...":"Save brief"})]})]})})}const Cs=[{name:"Indigo",value:"#6366f1"},{name:"Purple",value:"#a855f7"},{name:"Pink",value:"#ec4899"},{name:"Blue",value:"#3b82f6"},{name:"Cyan",value:"#06b6d4"},{name:"Green",value:"#22c55e"},{name:"Orange",value:"#f97316"},{name:"Red",value:"#ef4444"}],Ss=["ð","ð¡","ð","ð¯","ð¼","ð§ ","â¡","ð¥","ð","ð","ð¨","ð"];function ja(){const{user:s}=V(),r=X(),t=se(),[d,n]=_.useState(!1),[i,o]=_.useState(null),[c,a]=_.useState(null),[m,h]=_.useState(null),[g,A]=_.useState(null),[C,p]=_.useState(!1),[w,L]=_.useState({name:"",description:"",color:"#6366f1",icon:"ð"}),{data:j,isLoading:x}=P({queryKey:["content-pillars",s?.id],queryFn:async()=>{if(!s)return[];const{data:u,error:S}=await f.from("content_pillars").select("*").eq("user_id",s.id).order("created_at",{ascending:!1});if(S)throw S;return await Promise.all((u||[]).map(async I=>{const{data:B}=await f.from("content_pillar_items").select("platform").eq("pillar_id",I.id),ce=B?.filter(te=>te.platform==="article").length||0,de=B?.filter(te=>te.platform==="linkedin").length||0,$=B?.filter(te=>te.platform==="twitter").length||0;return{...I,itemCount:B?.length||0,articleCount:ce,linkedinCount:de,twitterCount:$}}))},enabled:!!s}),v=Y({mutationFn:async u=>{if(!s)throw new Error("Not authenticated");const{data:S,error:R}=await f.from("content_pillars").insert({user_id:s.id,name:u.name,description:u.description||null,color:u.color,icon:u.icon}).select().single();if(R)throw R;return S},onSuccess:async u=>{t.invalidateQueries({queryKey:["content-pillars"]}),n(!1),L({name:"",description:"",color:"#6366f1",icon:"ð"}),N.success("Content pillar created! Scanning for matching content...");try{const S=await f.auth.getSession(),{data:R}=await f.functions.invoke("auto-tag-pillar-content",{body:{pillarId:u.id},headers:{Authorization:`Bearer ${S.data.session?.access_token}`}});R?.tagged>0&&(N.success(`Found ${R.tagged} matching content!`,{description:"AI connected your existing posts to this pillar"}),t.invalidateQueries({queryKey:["content-pillars"]}))}catch(S){console.error("Auto-tag failed:",S)}},onError:u=>{N.error(`Failed to create pillar: ${u.message}`)}}),T=Y({mutationFn:async({id:u,...S})=>{const{error:R}=await f.from("content_pillars").update(S).eq("id",u);if(R)throw R},onSuccess:()=>{t.invalidateQueries({queryKey:["content-pillars"]}),o(null),N.success("Pillar updated!")},onError:u=>{N.error(`Failed to update pillar: ${u.message}`)}}),G=Y({mutationFn:async u=>{const{error:S}=await f.from("content_pillars").delete().eq("id",u);if(S)throw S},onSuccess:()=>{t.invalidateQueries({queryKey:["content-pillars"]}),N.success("Pillar deleted")},onError:u=>{N.error(`Failed to delete pillar: ${u.message}`)}}),k=(u,S)=>{S.stopPropagation(),r(`/editor/new?pillar=${u.id}&pillarName=${encodeURIComponent(u.name)}`)},E=async()=>{if(s){p(!0);try{const u=await f.auth.getSession(),{data:S,error:R}=await f.functions.invoke("auto-tag-pillar-content",{body:{},headers:{Authorization:`Bearer ${u.data.session?.access_token}`}});if(R)throw R;S?.tagged>0?(N.success(`Found ${S.tagged} new connections!`,{description:"AI matched your content to pillars"}),t.invalidateQueries({queryKey:["content-pillars"]})):N.info("No new matches found",{description:"All your content is already organized"})}catch(u){N.error(`Scan failed: ${u.message}`)}finally{p(!1)}}};return x?e.jsx(q,{className:"glass-effect",children:e.jsx(D,{className:"py-8 flex items-center justify-center",children:e.jsx(Q,{className:"w-6 h-6 animate-spin text-muted-foreground"})})}):e.jsxs(q,{className:"glass-effect",children:[e.jsxs(O,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsxs("div",{children:[e.jsxs(K,{className:"flex items-center gap-2",children:[e.jsx(M,{className:"w-5 h-5 text-primary"}),"Content Pillars"]}),e.jsx(J,{children:"Organize your content by themes. Each pillar grows as you publish."})]}),e.jsxs("div",{className:"flex gap-2",children:[j&&j.length>0&&e.jsxs(b,{size:"sm",variant:"ghost",className:"gap-2",onClick:E,disabled:C,children:[C?e.jsx(Q,{className:"w-4 h-4 animate-spin"}):e.jsx(ds,{className:"w-4 h-4"}),C?"Scanning...":"Auto-scan"]}),e.jsxs(Ie,{open:d,onOpenChange:n,children:[e.jsx(pt,{asChild:!0,children:e.jsxs(b,{size:"sm",variant:"outline",className:"gap-2",children:[e.jsx(we,{className:"w-4 h-4"}),"Add Pillar"]})}),e.jsxs($e,{children:[e.jsx(Fe,{children:e.jsx(De,{children:"Create Content Pillar"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Name"}),e.jsx(he,{placeholder:"e.g., AI & Automation",value:w.name,onChange:u=>L({...w,name:u.target.value})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Description (optional)"}),e.jsx(he,{placeholder:"What this pillar covers...",value:w.description,onChange:u=>L({...w,description:u.target.value})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium block mb-2",children:"Icon"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Ss.map(u=>e.jsx("button",{type:"button",onClick:()=>L({...w,icon:u}),className:`w-10 h-10 rounded-lg text-xl flex items-center justify-center border-2 transition-all ${w.icon===u?"border-primary bg-primary/10":"border-border hover:border-primary/50"}`,children:u},u))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium block mb-2",children:"Color"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Cs.map(u=>e.jsx("button",{type:"button",onClick:()=>L({...w,color:u.value}),className:`w-8 h-8 rounded-full transition-all ${w.color===u.value?"ring-2 ring-offset-2 ring-primary":""}`,style:{backgroundColor:u.value},title:u.name},u.value))})]})]}),e.jsx(Ye,{children:e.jsx(b,{onClick:()=>v.mutate(w),disabled:!w.name.trim()||v.isPending,children:v.isPending?"Creating...":"Create Pillar"})})]})]})]})]}),e.jsxs(D,{children:[j&&j.length>0?e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:j.map(u=>e.jsxs("div",{className:"relative group p-4 rounded-lg border bg-card hover:shadow-md transition-all cursor-pointer",style:{borderColor:`${u.color}30`,background:`linear-gradient(135deg, ${u.color}08 0%, transparent 100%)`},onClick:()=>a(u),children:[u.itemCount&&u.itemCount>0&&e.jsx("div",{className:"absolute inset-0 rounded-lg opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none",style:{boxShadow:`0 0 20px ${u.color}30`}}),e.jsxs("div",{className:"flex items-start justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-2xl",children:u.icon}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[e.jsx("h4",{className:"font-medium",children:u.name}),!u.is_public&&e.jsxs(F,{variant:"secondary",className:"gap-1 text-[10px] px-1.5 py-0",children:[e.jsx(la,{className:"w-2.5 h-2.5"}),"Private"]})]}),u.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:u.description})]})]}),e.jsxs("div",{className:"flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx(b,{size:"icon",variant:"ghost",className:"h-7 w-7",t
70itle:"Idea brief (private context for AI)",onClick:S=>{S.stopPropagation(),A(u)},children:e.jsx(da,{className:"w-3 h-3"})}),e.jsx(b,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:S=>{S.stopPropagation(),o(u)},children:e.jsx(ne,{className:"w-3 h-3"})}),e.jsx(b,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive",onClick:S=>{S.stopPropagation(),h(u.id)},children:e.jsx(Ge,{className:"w-3 h-3"})})]})]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground mb-3",children:[u.articleCount?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(be,{className:"w-3 h-3"}),u.articleCount]}):null,u.linkedinCount?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(je,{className:"w-3 h-3"}),u.linkedinCount]}):null,u.twitterCount?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Le,{className:"w-3 h-3"}),u.twitterCount]}):null,!u.itemCount&&e.jsx("span",{className:"text-muted-foreground/60",children:"Click to view & add content"}),u.itemCount&&u.itemCount>0&&e.jsx("span",{className:"text-muted-foreground/60 ml-auto",children:"Click to manage"})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs(b,{size:"sm",variant:"ghost",className:"w-full gap-2 text-xs",onClick:S=>k(u,S),style:{color:u.color},children:[e.jsx(ne,{className:"w-3 h-3"}),"Write about ",u.name]}),e.jsxs(b,{size:"sm",variant:"ghost",className:"w-full gap-2 text-xs text-muted-foreground hover:text-primary",onClick:async S=>{S.stopPropagation();const R=N.loading(`Researching & writing 3 deep ideas for ${u.name}â¦`);try{const{data:I,error:B}=await f.functions.invoke("generate-topic-suggestions",{body:{pillarId:u.id,pillarName:u.name,pillarDescription:u.description,count:3}});if(B)throw B;if(I?.error)throw new Error(I.error);if(I?.gated){const ce={business_description:"what your business does",ideal_customer:"who your ideal customer is",proof:"at least 1 project or offer"},de=I.missing.map($=>ce[$]||$).join(", ");N.warning("Complete your profile to unlock top-shelf ideas",{id:R,description:`Missing: ${de}. Generic ideas hurt your moat â we'd rather wait.`,duration:8e3,action:{label:"Open profile",onClick:()=>r("/profile")}});return}N.success(`${I?.count??3} deeply researched ideas added`,{id:R,description:'Expand "Latest ideas" or open Content Radar.'}),t.invalidateQueries({queryKey:["topic_suggestions"]}),t.invalidateQueries({queryKey:["topic-suggestions-fresh"]}),t.invalidateQueries({queryKey:["pillar-ideas",u.id]})}catch(I){N.error("Could not generate ideas",{id:R,description:I?.message})}},children:[e.jsx(M,{className:"w-3 h-3"}),"Generate 3 deep ideas"]}),e.jsx(pa,{pillarId:u.id,pillarName:u.name,color:u.color})]})]},u.id))}):e.jsxs("div",{className:"text-center py-8",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"Create your first content pillar to organize your writing by themes."}),e.jsxs(b,{variant:"outline",onClick:()=>n(!0),children:[e.jsx(we,{className:"w-4 h-4 mr-2"}),"Create Your First Pillar"]})]}),e.jsx(Ie,{open:!!i,onOpenChange:u=>!u&&o(null),children:e.jsxs($e,{children:[e.jsx(Fe,{children:e.jsx(De,{children:"Edit Pillar"})}),i&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Name"}),e.jsx(he,{value:i.name,onChange:u=>o({...i,name:u.target.value})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Description"}),e.jsx(he,{value:i.description||"",onChange:u=>o({...i,description:u.target.value})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium block mb-2",children:"Icon"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Ss.map(u=>e.jsx("button",{type:"button",onClick:()=>o({...i,icon:u}),className:`w-10 h-10 rounded-lg text-xl flex items-center justify-center border-2 transition-all ${i.icon===u?"border-primary bg-primary/10":"border-border hover:border-primary/50"}`,children:u},u))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium block mb-2",children:"Color"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Cs.map(u=>e.jsx("button",{type:"button",onClick:()=>o({...i,color:u.value}),className:`w-8 h-8 rounded-full transition-all ${i.color===u.value?"ring-2 ring-offset-2 ring-primary":""}`,style:{backgroundColor:u.value},title:u.name},u.value))})]}),e.jsx("div",{className:"rounded-lg border p-3 space-y-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("label",{className:"text-sm font-medium block",children:"Show on personal site"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:i.is_public?`Visible on /u/<your username>. Visitors will see: "${i.name}"`:"Private. Only used internally for your ideas & planning."})]}),e.jsx(Lt,{checked:i.is_public,onCheckedChange:u=>o({...i,is_public:u})})]})})]}),e.jsx(Ye,{children:e.jsx(b,{onClick:()=>{i&&T.mutate({id:i.id,name:i.name,description:i.description,color:i.color,icon:i.icon,is_public:i.is_public})},disabled:T.isPending,children:T.isPending?"Saving...":"Save Changes"})})]})}),e.jsx(fa,{pillar:g,open:!!g,onClose:()=>A(null)}),e.jsx(ha,{pillar:c,open:!!c,onClose:()=>a(null)}),e.jsx(Os,{open:!!m,onOpenChange:u=>!u&&h(null),children:e.jsxs(Ks,{children:[e.jsxs(Gs,{children:[e.jsx(Ws,{children:"Delete this pillar?"}),e.jsx(Bs,{children:"This will permanently remove this content pillar and unlink all associated content. This action cannot be undone."})]}),e.jsxs(Us,{children:[e.jsx(Vs,{children:"Cancel"}),e.jsx(Qs,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:()=>{m&&(G.mutate(m),h(null))},children:"Delete"})]})]})})]})]})}const qs={positive:{icon:Zs,label:"Understands",color:"text-green-500",bg:"bg-green-500/10"},negative:{icon:Ms,label:"Frustrated",color:"text-red-500",bg:"bg-red-500/10"},idea:{icon:Re,label:"Has Ideas",color:"text-yellow-500",bg:"bg-yellow-500/10"},neutral:{icon:Xs,label:"Neutral",color:"text-muted-foreground",bg:"bg-muted"}},ba=()=>{const{data:s,isLoading:r}=P({queryKey:["admin-feedback"],queryFn:async()=>{const{data:d,error:n}=await f.from("user_feedback").select("*").order("created_at",{ascending:!1}).limit(50);if(n)throw n;return d}}),{data:t}=P({queryKey:["admin-feedback-stats"],queryFn:async()=>{const{data:d,error:n}=await f.from("user_feedback").select("sentiment, created_at");if(n)throw n;const i=new Date;i.setHours(0,0,0,0);const o=d.filter(a=>new Date(a.created_at)>=i).length,c=d.reduce((a,m)=>(a[m.sentiment]=(a[m.sentiment]||0)+1,a),{});return{total:d.length,today:o,positive:c.positive||0,negative:c.negative||0,idea:c.idea||0}}});return r?e.jsx(q,{className:"glass-effect",children:e.jsx(D,{className:"py-8 text-center text-muted-foreground",children:"Loading feedback..."})}):e.jsxs(q,{className:"glass-effect",children:[e.jsxs(O,{children:[e.jsxs(K,{className:"flex items-center gap-2",children:[e.jsx(Xs,{className:"w-5 h-5"}),"User Feedback"]}),e.jsx(J,{children:t&&e.jsxs("span",{className:"flex gap-4 mt-2",children:[e.jsxs("span",{children:["Today: ",t.today]}),e.jsxs("span",{className:"text-green-500 flex items-center gap-1",children:[e.jsx(Zs,{className:"w-3 h-3"})," ",t.positive]}),e.jsxs("span",{className:"text-red-500 flex items-center gap-1",children:[e.jsx(Ms,{className:"w-3 h-3"})," ",t.negative]}),e.jsxs("span",{className:"text-yellow-500 flex items-center gap-1",children:[e.jsx(Re,{className:"w-3 h-3"})," ",t.idea]})]})})]}),e.jsx(D,{children:s&&s.length>0?e.jsx("div",{className:"space-y-3 max-h-[400px] overflow-y-auto",children:s.map(d=>{const n=qs[d.sentiment]||qs.neutral,i=n.icon,o=d.context;return e.jsxs("div",{className:`p-3 rounded-lg border ${n.bg}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(i,{className:`w-4 h-4 ${n.color}`}),e.jsx(F,{variant:"outline",className:"text-xs",children:d.feedback_type})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:oe(new Date(d.created_at),{addSuffix:!0})})]}),d.message&&e.jsx("p",{className:"mt-2 text-sm",children:d.message}),o&&Object.keys(o).length>0&&e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["Context: ",JSON.stringify(o)]})]},d.id)})}):e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No feedback yet"})})]})},ya=()=>{const{data:s}=P({queryKey:["admin-subscriber-stats"],queryFn:async()=>{const{count:r}=await f.from("newsletter_subscribers").select("*",{count:"exact",head:!0}).eq("status","active"),{count:t}=await f.from("newsletter_subscribers").select("*",{count:"exact",head:!0}),{count:d}=await f.from("suppressed_emails").select("email",{count:"exact",head:!0});return{active:r||0,total:t||0,suppressed:d||0}}});return e.jsxs(q,{className:"glass-effect",children:[e.jsx(O,{className:"pb-3",children:e.jsxs(K,{className:"flex items-center gap-2 text-base",children:[e.jsx(ft,{className:"w-4 h-4 text-primary"}),"Newsletter Subscribers"]}
70)}),e.jsx(D,{children:e.jsxs("div",{className:"flex items-center gap-6 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-3xl font-bold",children:s?.active??"â"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Active"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-3xl font-bold text-muted-foreground",children:s?.total??"â"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total (all time)"})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-3xl font-bold text-amber-600 flex items-center gap-1.5",children:[e.jsx(Et,{className:"w-5 h-5"}),s?.suppressed??"â"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Suppressed"})]})]})})]})},As=7*24*60*60*1e3;function wa(){const[s,r]=_.useState(null),[t,d]=_.useState(!1),{data:n,isLoading:i,refetch:o,dataUpdatedAt:c}=P({queryKey:["admin-error-logs"],queryFn:async()=>{const{data:p,error:w}=await f.from("client_error_logs").select("*").order("created_at",{ascending:!1}).limit(50);if(w)throw w;return p||[]},refetchInterval:6e4}),a=n||[],m=a.filter(p=>Date.now()-new Date(p.created_at).getTime()>=As).length,h=t?a:a.filter(p=>Date.now()-new Date(p.created_at).getTime()<As),g=h.reduce((p,w)=>(p[w.error_type]=(p[w.error_type]||0)+1,p),{}),A=h.length>0,C=h.filter(p=>Date.now()-new Date(p.created_at).getTime()<24*60*60*1e3).length;return e.jsxs(q,{children:[e.jsxs(O,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[C>0?e.jsx(ye,{className:"h-5 w-5 text-destructive"}):e.jsx(is,{className:"h-5 w-5 text-green-500"}),e.jsx(K,{className:"text-lg",children:"Error Monitor"}),C>0&&e.jsxs(F,{variant:"destructive",className:"text-xs",children:[C," in 24h"]})]}),e.jsx(b,{variant:"ghost",size:"sm",onClick:()=>o(),children:e.jsx(ie,{className:"h-4 w-4"})})]}),e.jsxs(J,{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{children:A?`${h.length} error${h.length===1?"":"s"} in last 7 days`:"No recent errors â all systems healthy"}),m>0&&e.jsx("button",{type:"button",onClick:()=>d(p=>!p),className:"text-xs underline text-muted-foreground hover:text-foreground",children:t?`Hide ${m} older`:`Show ${m} older`})]})]}),A&&e.jsxs(D,{className:"space-y-3",children:[e.jsx("div",{className:"flex flex-wrap gap-2 pb-2 border-b border-border",children:Object.entries(g).sort((p,w)=>w[1]-p[1]).map(([p,w])=>e.jsxs(F,{variant:"outline",className:"text-xs",children:[p,": ",w]},p))}),e.jsx("div",{className:"max-h-[400px] overflow-y-auto space-y-2",children:h.map(p=>e.jsxs("div",{className:"p-3 rounded-lg border border-border bg-muted/30 text-sm",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(F,{variant:"secondary",className:"text-xs shrink-0",children:p.error_type}),e.jsx("span",{className:"text-xs text-muted-foreground",children:oe(new Date(p.created_at),{addSuffix:!0})}),p.page_path&&e.jsx("span",{className:"text-xs text-muted-foreground truncate",children:p.page_path})]}),e.jsx("p",{className:"mt-1 text-foreground/80 truncate",children:p.error_message||"No message"})]}),p.error_context&&Object.keys(p.error_context).length>0&&e.jsx(b,{variant:"ghost",size:"sm",className:"shrink-0 h-6 w-6 p-0",onClick:()=>r(s===p.id?null:p.id),children:s===p.id?e.jsx(zt,{className:"h-3 w-3"}):e.jsx(ns,{className:"h-3 w-3"})})]}),s===p.id&&p.error_context&&e.jsx("pre",{className:"mt-2 p-2 rounded bg-background text-xs overflow-x-auto",children:JSON.stringify(p.error_context,null,2)})]},p.id))})]})]})}const Na={inline_only:"Inline FAQ block, no DB rows (will migrate)",inline_plus_db:"Inline + DB (duplication risk â will strip)",inline_user_edited:"User-edited DB FAQs (skip â safe)",db_only:"DB only (clean â)",none:"No FAQ markers"};function va(){const[s,r]=_.useState(null),[t,d]=_.useState(null),n=async(a,m={})=>{const{data:h,error:g}=await f.functions.invoke("cleanup-inline-faqs",{body:{action:a,dryRun:m.dryRun!==!1}
70});if(g)throw g;if(!h?.success)throw new Error(h?.error||"Operation failed");return h},i=async()=>{r("audit"),d(null);try{const a=await n("audit");d(a),N.success(`Audited ${a.scanned} posts.`)}catch(a){N.error(a?.message||"Audit failed")}finally{r(null)}},o=async a=>{r(a?"apply":"dry"),d(null);try{const m=await n("cleanup",{dryRun:!a});d(m),N.success(a?`Cleaned ${m.affected} of ${m.scanned} scanned posts.`:`Dry run: ${m.affected} of ${m.scanned} posts would be cleaned.`)}catch(m){N.error(m?.message||"Cleanup failed")}finally{r(null)}},c=async a=>{if(confirm("Restore the original article content for this post?")){r(`revert:${a}`);try{const{data:m,error:h}=await f.functions.invoke("cleanup-inline-faqs",{body:{action:"revert",logId:a}});if(h)throw h;if(!m?.success)throw new Error(m?.error||"Revert failed");N.success("Reverted.")}catch(m){N.error(m?.message||"Revert failed")}finally{r(null)}}};return e.jsxs(q,{className:"glass-effect",children:[e.jsx(O,{className:"pb-2",children:e.jsxs(K,{className:"text-lg flex items-center gap-2",children:[e.jsx(Mt,{className:"w-5 h-5"}),"Maintenance · Inline-FAQ Audit & Cleanup"]})}),e.jsxs(D,{className:"space-y-3",children:[e.jsxs("p",{className:"text-xs text-muted-foreground leading-relaxed",children:["Strips the legacy inline ",e.jsx("code",{className:"text-[10px]",children:"<h2>FAQ</h2>"})," block from articles where it was duplicated into the body and migrates unique Q&As into"," ",e.jsx("code",{className:"text-[10px]",children:"article_faqs"}),". User-edited FAQs are always preserved. Every change is logged; revert any row individually."]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(b,{variant:"ghost",size:"sm",onClick:i,disabled:s!==null,children:[s==="audit"?e.jsx(Q,{className:"w-3 h-3 mr-2 animate-spin"}):e.jsx(ls,{className:"w-3 h-3 mr-2"}),"Audit (read-only)"]}),e.jsxs(b,{variant:"outline",size:"sm",onClick:()=>o(!1),disabled:s!==null,children:[s==="dry"?e.jsx(Q,{className:"w-3 h-3 mr-2 animate-spin"}):null,"Dry run cleanup"]}),e.jsxs(b,{variant:"default",size:"sm",onClick:()=>{confirm("This will modify posts.content for all matching articles. Continue?")&&o(!0)},disabled:s!==null,children:[s==="apply"?e.jsx(Q,{className:"w-3 h-3 mr-2 animate-spin"}):null,"Apply cleanup"]})]}),t?.action==="audit"&&t.summary&&e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3 space-y-2",children:[e.jsxs("div",{className:"text-sm font-semibold",children:["Audit · ",t.scanned," posts scanned"]}),e.jsx("div",{className:"grid grid-cols-2 gap-1 text-[11px]",children:Object.entries(t.summary).filter(([a])=>a.startsWith("state_")).map(([a,m])=>e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:Na[a.replace("state_","")]||a}),e.jsx("span",{className:"font-mono",children:m})]},a))}),(t.samples?.length??0)>0&&e.jsx("div",{className:"max-h-64 overflow-auto text-[11px] font-mono space-y-1 border-t pt-2",children:t.samples.map(a=>e.jsxs("div",{className:"flex justify-between gap-2",children:[e.jsx("span",{className:"truncate",children:a.slug||a.post_id}),e.jsxs("span",{className:"text-muted-foreground shrink-0",children:[a.state," · ",a.qas_found,"q · db:",a.db_count,a.user_edited?" · edited":""]})]},a.post_id))})]}),t?.action==="cleanup"&&e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm flex-wrap",children:[(t.affected??0)===0?e.jsx(is,{className:"w-4 h-4 text-emerald-500"}):e.jsx(ye,{className:"w-4 h-4 text-amber-500"}),e.jsxs("span",{className:"font-semibold",children:[t.dryRun?"Dry run":"Applied"," · ",t.affected??0," / ",t.scanned??0]}),(t.skipped??0)>0&&e.jsxs(F,{variant:"secondary",className:"text-[10px]",children:[t.skipped," skipped (user-edited)"]}),t.dryRun&&e.jsx(F,{variant:"outline",className:"text-[10px]",children:"no changes written"})]}),(t.report?.length??0)>0&&e.jsxs("div",{className:"max-h-64 overflow-auto text-[11px] font-mono space-y-1",children:[t.report.slice(0,50).map(a=>e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"truncate flex-1",children:a.slug||a.post_id}),e.jsx("span",{className:"text-muted-foreground shrink-0",children:a.skipped_reason?`skipped: ${a.skipped_reason}
70`:`${a.qas_found} found · ${a.qas_new} new · ${a.bytes_removed}b`}),a.log_id&&e.jsx(b,{variant:"ghost",size:"sm",className:"h-6 px-2 text-[10px]",onClick:()=>c(a.log_id),disabled:s===`revert:${a.log_id}`,title:"Revert this post to its original content",children:s===`revert:${a.log_id}`?e.jsx(Q,{className:"w-3 h-3 animate-spin"}):e.jsx(Pt,{className:"w-3 h-3"})})]},a.post_id)),t.report.length>50&&e.jsxs("div",{className:"text-muted-foreground",children:["â¦and ",t.report.length-50," more"]})]})]})]})]})}const ka=()=>{const[s,r]=_.useState("30"),{data:t,isLoading:d,error:n}=P({queryKey:["admin-analytics",s],queryFn:async()=>{const{data:c}=await f.auth.getSession(),a=c?.session?.access_token;if(!a)throw new Error("Not authenticated");const m=await fetch(`https://auth.thoughtforge.app/functions/v1/admin-analytics?days=${s}`,{headers:{Authorization:`Bearer ${a}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imh6enZkZGlvaXZ2dHdrampxYXZxIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5MjY5NzQsImV4cCI6MjA3NzUwMjk3NH0.w-brR7A0V588XIgtcG9IVslNcqbLX2eAdEKFbGyLb7U"}});if(!m.ok)throw new Error("Failed to fetch analytics");return m.json()},refetchInterval:6e4}),i=c=>{if(c<60)return`${c}s`;const a=Math.floor(c/60),m=c%60;return`${a}m ${m}s`},o=(c,a)=>a>0?`${(c/a*100).toFixed(1)}%`:"0%";return n?e.jsx(q,{className:"glass-effect",children:e.jsx(D,{className:"py-6 text-center text-muted-foreground",children:"Failed to load platform analytics"})}):e.jsxs(q,{className:"glass-effect",children:[e.jsxs(O,{className:"flex flex-row items-center justify-between pb-2",children:[e.jsxs(K,{className:"text-lg flex items-center gap-2",children:[e.jsx(xe,{className:"w-5 h-5"}),"Platform-Wide Analytics"]}),e.jsxs(es,{value:s,onValueChange:r,children:[e.jsx(ss,{className:"w-[120px]",children:e.jsx(ts,{})}),e.jsxs(as,{children:[e.jsx(ee,{value:"7",children:"Last 7 days"}),e.jsx(ee,{value:"30",children:"Last 30 days"}),e.jsx(ee,{value:"90",children:"Last 90 days"})]})]})]}),e.jsx(D,{className:"space-y-6",children:d?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading analytics..."}):t?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(Ce,{icon:e.jsx(We,{className:"w-4 h-4"}),label:"Total Views",value:t.kpis.totalViews.toLocaleString()}),e.jsx(Ce,{icon:e.jsx(Wt,{className:"w-4 h-4"}),label:"Unique Visitors",value:t.kpis.uniqueSessions.toLocaleString()}),e.jsx(Ce,{icon:e.jsx(os,{className:"w-4 h-4"}),label:"Avg Time",value:i(t.kpis.avgTime)}),e.jsx(Ce,{icon:e.jsx(et,{className:"w-4 h-4"}),label:"Bounce Rate",value:`${t.kpis.bounceRate}%`})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold mb-1",children:"Top-of-funnel (page views)"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Excludes admin/internal accounts."}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap text-sm",children:[e.jsx(ae,{label:"Homepage",value:t.funnel.homepageVisits}),e.jsx(W,{className:"w-3 h-3 text-muted-foreground"}),e.jsx(ae,{label:"Auth Page",value:t.funnel.authVisits,rate:o(t.funnel.authVisits,t.funnel.homepageVisits)}),e.jsx(W,{className:"w-3 h-3 text-muted-foreground"}),e.jsx(ae,{label:"Signups",value:t.funnel.signups,rate:o(t.funnel.signups,t.funnel.authVisits)}),e.jsx(W,{className:"w-3 h-3 text-muted-foreground"}),e.jsx(ae,{label:"Newsletter",value:t.funnel.newsletterConverts})]})]}),t.paidFunnel&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold mb-1",children:"Paid conversion"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Signup â email verified â pricing â checkout â subscribed."}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap text-sm",children:[e.jsx(ae,{label:"Signed up",value:t.paidFunnel.signup}),e.jsx(W,{className:"w-3 h-3 text-muted-foreground"}),e.jsx(ae,{label:"Verified",value:t.paidFunnel.email_verified,rate:o(t.paidFunnel.email_verified,t.paidFunnel.signup)}),e.jsx(W,{className:"w-3 h-3 text-muted-foreground"}),e.jsx(ae,{label:"Pricing",value:t.paidFunnel.pricing_viewed,rate:o(t.paidFunnel.pricing_viewed,t.paidFunnel.email_verified)}),e.jsx(W,{className:"w-3 h-3 text-muted-foreground"}),e.jsx(ae,{label:"Checkout",value:t.paidFunnel.checkout_started,rate:o(t.paidFunnel.checkout_started,t.paidFunnel.pricing_viewed)}),e.jsx(W,{className:"w-3 h-3 text-muted-foreground"}),e.jsx(ae,{label:"Subscribed",value:t.paidFunnel.subscription_active,rate:o(t.paidFunnel.subscription_active,t.paidFunnel.signup)})]})]}),t.newsletterBySource&&t.newsletterBySource.length>0&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold mb-3",children:"Newsletter signups by source"}),e.jsx("div",{className:"space-y-2",children:t.newsletterBySource.map((c,a)=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"capitalize",children:c.source.replace(/_/g," ")}),e.jsx(F,{variant:"secondary",children:c.count})]},a))})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold mb-3",children:"Top Pages"}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Ot,{children:[e.jsx(Kt,{children:e.jsxs(ys,{children:[e.jsx(ke,{children:"Page"}),e.jsx(ke,{className:"text-right",children:"Views"}),e.jsx(ke,{className:"text-right",children:"Avg Time"}),e.jsx(ke,{className:"text-right",children:"Avg Scroll"})]})}),e.jsx(Gt,{children:t.topPages.slice(0,10).map((c,a)=>e.jsxs(ys,{children:[e.jsx(_e,{className:"font-mono text-xs max-w-[200px] truncate",children:c.page_path}),e.jsx(_e,{className:"text-right",children:c.views}),e.jsx(_e,{className:"text-right",children:i(c.avg_time)}),e.jsxs(_e,{className:"text-right",children:[c.avg_scroll,"%"]})]},a))})]})})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold mb-3",children:"Traffic Sources"}),e.jsx("div",{className:"space-y-2",children:t.trafficSources.slice(0,8).map((c,a)=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"truncate max-w-[180px]",children:c.source}),e.jsx(F,{variant:"secondary",children:c.count})]},a))})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold mb-3",children:"Top Countries"}),e.jsx("div",{className:"space-y-2",children:t.geoBreakdown.slice(0,8).map((c,a)=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{children:c.country}),e.jsx(F,{variant:"secondary",children:c.count})]},a))})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold mb-3",children:"Devices"}),e.jsx("div",{className:"flex gap-4",children:Object.entries(t.deviceBreakdown).map(([c,a])=>e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[c==="mobile"?e.jsx(Bt,{className:"w-4 h-4"}):c==="tablet"?e.jsx(Ut,{className:"w-4 h-4"}):e.jsx(Vt,{className:"w-4 h-4"}),e.jsx("span",{className:"capitalize",children:c}),e.jsx(F,{variant:"outline",children:a})]},c))})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold mb-3",children:"Recent Visits"}),e.jsx("div",{className:"space-y-2",children:t.recentActivity.map((c,a)=>e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-mono truncate max-w-[200px]",children:c.page_path}),c.country&&e.jsx("span",{children:c.country}),c.time_on_page!=null&&e.jsx("span",{children:i(c.time_on_page)}),e.jsx("span",{className:"ml-auto",children:new Date(c.viewed_at).toLocaleTimeString()})]},a))})]})]}):null})]})},Ce=({icon:s,label:r,value:t})=>e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs mb-1",children:[s,r]}),e.jsx("div",{className:"text-2xl font-bold",children:t})]}),ae=({label:s,value:r,rate:t})=>e.jsxs("div",{className:"bg-muted/50 rounded-md px-3 py-2 text-center",children:[e.jsx("div",{className:"font-semibold",children:r}),e.jsx("div",{className:"text-xs text-muted-foreground",children:s}),t&&e.jsx("div",{className:"text-xs text-primary",children:t})]}),_a=()=>{const{session:s}=V(),[r,t]=_.useState(""),[d,n]=_.useState(!1),i=async()=>
70{if(!s)return;const o=r.trim();if(!o){N.error("Enter an email");return}if(confirm(`Revoke access for ${o}? They will be sent back to /pricing on next request.`)){n(!0);try{const{data:c,error:a}=await f.functions.invoke("admin-revoke-access",{body:{email:o},headers:{Authorization:`Bearer ${s.access_token}`}});if(a)throw a;if(c?.success===!1)throw new Error(c.error||c.errorCode||"Revoke failed");N.success(`Access revoked for ${o}`),t("")}catch(c){const a=c instanceof Error?c.message:String(c);N.error("Revoke failed",{description:a})}finally{n(!1)}}};return e.jsxs(q,{className:"mb-12 glass-effect",children:[e.jsxs(O,{children:[e.jsxs(K,{className:"flex items-center gap-2",children:[e.jsx(ma,{className:"w-5 h-5 text-destructive"}),"Revoke Access"]}),e.jsx(J,{children:"End an access-code or paid user's access immediately. Sets subscription_end to now and tier to inactive."})]}),e.jsx(D,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(Je,{htmlFor:"revoke-email",className:"text-xs",children:"User email"}),e.jsx(he,{id:"revoke-email",type:"email",placeholder:"[email protected]",value:r,onChange:o=>t(o.target.value),disabled:d})]}),e.jsx("div",{className:"flex items-end",children:e.jsx(b,{variant:"destructive",onClick:i,disabled:d||!r.trim(),children:d?e.jsx(Q,{className:"h-4 w-4 animate-spin"}):"Revoke"})})]})})]})},Se={lastJournalEntry:"2026-06-11",nowItemsCount:0,lastCheckAllGreen:"2026-06-11"},Ca=()=>{const{data:s,isLoading:r}=P({queryKey:["admin-system-health-audit"],queryFn:async()=>{const{data:h,error:g}=await f.functions.invoke("cleanup-inline-faqs",{body:{action:"audit"}});if(g)throw g;return h},staleTime:3e5,retry:!1}),t=(s?.summary?.inline_only??0)+(s?.summary?.inline_plus_db??0),d=h=>{const g=(Date.now()-new Date(h).getTime())/864e5;return Math.max(0,Math.floor(g))}
70,n=d(Se.lastJournalEntry),i=d(Se.lastCheckAllGreen),o=i<=7,c=n<=14,a=!r&&t===0,m=o&&c&&a;return e.jsxs(q,{className:"glass-effect",children:[e.jsxs(O,{children:[e.jsxs(K,{className:"flex items-center gap-2",children:[e.jsx(fs,{className:"w-5 h-5 text-primary"}),"System Health",m?e.jsxs(F,{variant:"outline",className:"ml-2 border-green-500/40 text-green-600",children:[e.jsx(is,{className:"w-3 h-3 mr-1"})," All green"]}):e.jsxs(F,{variant:"outline",className:"ml-2 border-yellow-500/40 text-yellow-600",children:[e.jsx(ye,{className:"w-3 h-3 mr-1"})," Check items"]})]}),e.jsxs(J,{children:["Anti-regression snapshot. If green, close the tab. See"," ",e.jsx("code",{className:"text-xs",children:".lovable/runbooks/weekly-review.md"}),"."]})]}),e.jsx(D,{children:e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3",children:[e.jsx(qe,{ok:o,icon:e.jsx(fs,{className:"w-4 h-4"}),label:"check:all",value:`${i}d ago`,hint:o?"OK":"Run: npm run check:all"}),e.jsx(qe,{ok:a,icon:e.jsx(ye,{className:"w-4 h-4"}),label:"Legacy inline FAQs",value:r?"â¦":String(t),hint:a?"None":"Open Maintenance â Inline FAQ Cleanup"}),e.jsx(qe,{ok:c,icon:e.jsx(be,{className:"w-4 h-4"}),label:"Last journal",value:`${n}d ago`,hint:c?"Fresh":"Add entry under .lovable/progress/journal/"}),e.jsx(qe,{ok:Se.nowItemsCount<=3,icon:e.jsx(oa,{className:"w-4 h-4"}),label:"Backlog Now",value:String(Se.nowItemsCount),hint:"Focused"})]})})]})},qe=({ok:s,icon:r,label:t,value:d,hint:n})=>e.jsxs("div",{className:`rounded-lg border p-3 ${s?"border-green-500/20 bg-green-500/5":"border-yellow-500/30 bg-yellow-500/5"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[r,e.jsx("span",{children:t})]}),e.jsx("div",{className:"mt-1 text-lg font-semibold",children:d}),e.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:n})]}),Sa=({variant:s="inline",className:r})=>s==="inline"?e.jsxs("div",{className:pe("flex items-center gap-2 text-sm text-muted-foreground",r),children:[e.jsx(Te,{className:"h-4 w-4"}),e.jsx("span",{children:"Subscribe to ThoughtForge to publish."}),e.jsx(Z,{to:"/pricing",className:"text-primary hover:underline font-medium",children:"Subscribe"})]}):s==="card"?e.jsx(q,{className:pe("border-primary/20 bg-primary/5",r),children:e.jsx(D,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"p-2 rounded-full bg-primary/10",children:e.jsx(Te,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h4",{className:"font-medium mb-1",children:"Subscribe to Publish"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"Get unlimited access to all ThoughtForge features for $99/month."}),e.jsx(b,{asChild:!0,size:"sm",children:e.jsxs(Z,{to:"/pricing",children:["Subscribe ",e.jsx(W,{className:"h-4 w-4 ml-1"})]})})]})]})})}):e.jsxs("div",{className:pe("w-full py-2 px-4 flex items-center justify-between gap-4","bg-primary/5 border-primary/20 border rounded-lg",r),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Te,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm font-medium",children:"Subscribe to unlock all features"})]}),e.jsx(b,{asChild:!0,size:"sm",children:e.jsx(Z,{to:"/pricing",children:"Subscribe Now"})})]});function qa({userId:s}){const r=X(),t=se(),{data:d,isLoading:n}=P({queryKey:["weekly-brief",s],queryFn:async()=>{if(!s)return null;const{data:h,error:g}=await f.from("weekly_briefs").select("*").eq("user_id",s).order("week_of",{ascending:!1}).limit(1).single();if(g&&g.code!=="PGRST116")throw g;return h},enabled:!!s}),i=Y({mutationFn:async()=>{const{data:h,error:g}=await f.functions.invoke("generate-weekly-brief",{body:{user_id:s}});if(g)throw g;return h},onSuccess:()=>{t.invalidateQueries({queryKey:["weekly-brief"]}),N.success("Weekly brief generated!")},onError:h=>{N.error(`Failed to generate brief: ${h.message}`)}});if(n)return null;const o=d?.brief;if(!o)return e.jsxs(q,{className:"mb-12 glass-effect border-primary/20 bg-gradient-to-br from-primary/5 to-background",children:[e.jsxs(O,{children:[e.jsxs(K,{className:"flex items-center gap-2 text-lg",children:[e.jsx(M,{className:"w-5 h-5 text-primary"}),"Your Weekly Content Brief"]}),e.jsx(J,{children:"Get a personalized content plan based on your pillars and search rankings"})]}),e.jsx(D,{children:e.jsxs(b,{onClick:()=>i.mutate(),disabled:i.isPending,variant:"default",size:"sm",children:[i.isPending?e.jsx(ie,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(M,{className:"w-4 h-4 mr-2"}),"Generate This Week's Brief"]})})]});const c=o.article_topics||[],a=o.social_ideas||[],m=o.quick_win;return e.jsxs(q,{className:"mb-12 glass-effect border-primary/20",children:[e.jsxs(O,{className:"flex flex-row items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs(K,{className:"flex items-center gap-2 text-lg",children:[e.jsx(M,{className:"w-5 h-5 text-primary"}),"This Week's Content Plan"]}),e.jsx(J,{className:"mt-1",children:o.summary||"Your personalized content strategy"})]}),e.jsx(b,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>i.mutate(),disabled:i.isPending,title:"Regenerate brief",children:e.jsx(ie,{className:`h-4 w-4 ${i.isPending?"animate-spin":""}`})})]}),e.jsxs(D,{className:"space-y-6",children:[c.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"text-sm font-medium text-muted-foreground mb-3 flex items-center gap-2",children:[e.jsx(ne,{className:"w-4 h-4"})," Article Ideas"]}),e.jsx("div",{className:"space-y-2",children:c.map((h,g)=>e.jsxs("div",{className:"flex items-start justify-between gap-3 p-3 rounded-lg bg-muted/30 hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:h.title}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:h.why}),h.target_keyword&&e.jsxs(F,{variant:"outline",className:"mt-1 text-xs",children:[e.jsx(ms,{className:"w-3 h-3 mr-1"}),h.target_keyword]})]}),e.jsx(b,{size:"sm",variant:"ghost",onClick:()=>r("/agent"),className:"shrink-0",children:"Start"})]},g))})]}),m&&e.jsxs("div",{className:"p-3 rounded-lg bg-accent/30 border border-accent/20",children:[e.jsxs("h4",{className:"text-sm font-medium flex items-center gap-2 mb-1",children:[e.jsx(Te,{className:"w-4 h-4 text-accent-foreground"})," Quick Win"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[m.action," â ",m.reason]})]}),a.length>0&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium text-muted-foreground mb-2",children:"Social Ideas"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map((h,g)=>e.jsxs(F,{variant:"secondary",className:"text-xs",children:[h.platform,": ",h.idea.substring(0,60),h.idea.length>60?"...":""]},g))})]})]})]})}function Aa(){const{user:s}=V(),r=new Date(Date.now()-7*24*60*60*1e3).toISOString(),{data:t,isLoading:d}=P({queryKey:["wins-this-week",s?.id],enabled:!!s,staleTime:5*6e4,queryFn:async()=>{const i=s.id,o=f,[c,a,m,h,g,A]=await Promise.all([o.from("ranking_alerts").select("id",{count:"exact",head:!0}).eq("user_id",i).eq("alert_type","improved").gte("created_at",r),o.from("page_views").select("id",{count:"exact",head:!0}).eq("user_id",i).gte("created_at",r),o.from("posts").select("id",{count:"exact",head:!0}).eq("user_id",i).not("published_at","is",null).gte("published_at",r),o.from("posts").select("id",{count:"exact",head:!0}).eq("user_id",i).gte("linkedin_published_at",r),o.from("posts").select("id",{count:"exact",head:!0}).eq("user_id",i).gte("twitter_published_at",r),o.from("posts").select("id",{count:"exact",head:!0}).eq("user_id",i).gte("threads_published_at",r)]),C=(h.count||0)+(g.count||0)+(A.count||0);return{improved:c.count||0,views:a.count||0,published:m.count||0,social:C}}});
70return d?e.jsx(Ne,{className:"h-20 w-full mb-8"}):!t||t.improved+t.views+t.published+t.social===0?null:e.jsxs("div",{className:"mb-8 rounded-lg border border-border bg-gradient-to-br from-primary/5 via-background to-background p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(M,{className:"w-4 h-4 text-primary"}),e.jsx("h3",{className:"text-sm font-medium tracking-wide uppercase text-muted-foreground",children:"Your wins this week"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:[t.improved>0&&e.jsxs(Z,{to:"/discovery",className:"flex items-start gap-3 p-3 rounded-md hover:bg-muted/40 transition-colors",children:[e.jsx(ge,{className:"w-5 h-5 text-emerald-500 mt-0.5 shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-light",children:t.improved}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["ranking",t.improved===1?"":"s"," moved up"]})]})]}),t.views>0&&e.jsxs(Z,{to:"/platform-analytics",className:"flex items-start gap-3 p-3 rounded-md hover:bg-muted/40 transition-colors",children:[e.jsx(We,{className:"w-5 h-5 text-blue-500 mt-0.5 shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-light",children:t.views.toLocaleString()}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["page view",t.views===1?"":"s"," on your articles"]})]})]}),t.published>0&&e.jsxs("div",{className:"flex items-start gap-3 p-3",children:[e.jsx(Tt,{className:"w-5 h-5 text-purple-500 mt-0.5 shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-light",children:t.published}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["article",t.published===1?"":"s"," published"]})]})]}),t.social>0&&e.jsxs(Z,{to:"/distribute",className:"flex items-start gap-3 p-3 rounded-md hover:bg-muted/40 transition-colors",children:[e.jsx(cs,{className:"w-5 h-5 text-foreground/70 mt-0.5 shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-light",children:t.social}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["social post",t.social===1?"":"s"," shipped"]})]})]})]})]})}function Pa(){const{user:s}=V(),{data:r=0}=P({queryKey:["failed-scheduled-count",s?.id],queryFn:async()=>{const{count:t,error:d}=await f.from("scheduled_posts").select("id",{count:"exact",head:!0}).eq("user_id",s.id).eq("status","failed");if(d)throw d;return t||0},enabled:!!s,staleTime:3e4});return r?e.jsx(Z,{to:"/schedule#needs-attention",className:"block mb-4 group","aria-label":`${r} scheduled posts need attention`,children:e.jsx(q,{className:"p-3 border-destructive/40 bg-destructive/5 transition-colors group-hover:bg-destructive/10",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(ye,{className:"w-5 h-5 text-destructive"}),e.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 rounded-full bg-destructive animate-pulse","aria-hidden":!0})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"text-sm font-medium",children:[r," scheduled ",r===1?"post":"posts"," need attention"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Reconnect a platform or retry to publish."})]}),e.jsxs("span",{className:"text-xs text-destructive font-medium flex items-center gap-1 whitespace-nowrap",children:["Review ",e.jsx(W,{className:"w-3 h-3 transition-transform group-hover:translate-x-0.5"})]})]})})}):null}function Ta({hasPublishedPosts:s}){const{user:r}=V(),{data:t,isLoading:d}=Qt(),[n,i]=_.useState(!1),o=se();if(!s)return null;const c=async()=>{if(r){i(!0),N.info("Checking Perplexity for your contentâ¦",{description:"This usually takes 30-60 seconds."});try{const{data:h,error:g}=await f.functions.invoke("probe-ai-citations",{body:{userId:r.id}});if(g)throw g;h?.success===!1?N.error("Check failed",{description:h.errorCode||"Try again later."}):(N.success("Check complete. Refreshing resultsâ¦"),await o.invalidateQueries({queryKey:["ai-citation-probes"]}))}catch(h){N.error(h.message||"Check failed")}finally{i(!1)}}};if(d)return e.jsx(Ne,{className:"h-40 w-full mb-8"});const a=(t||[]).filter(h=>h.cited),m=t?.length||0;return e.jsxs(q,{className:"mb-8 glass-effect",children:[e.jsx(O,{children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs(K,{className:"flex items-center gap-2 text-base",children:[e.jsx(M,{className:"w-4 h-4 text-primary"}),"AI citation tracking"]}),e.jsx(J,{className:"mt-1",children:a.length>0?`Cited by Perplexity ${a.length} time${a.length===1?"":"s"} in the last 30 days`:m>0?`Checked ${m} buyer-intent queries â no citations yet. Keep publishing & optimizing.`:"We haven't checked your content yet. Run a check to see if Perplexity cites you."})]}),e.jsxs(b,{size:"sm",variant:"outline",onClick:c,disabled:n,children:[n?e.jsx(Q,{className:"w-4 h-4 animate-spin"}):e.jsx(ls,{className:"w-4 h-4 mr-2"}),n?"Checkingâ¦":"Check now"]})]})}),a.length>0&&e.jsx(D,{className:"space-y-3",children:a.slice(0,5).map(h=>e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-md bg-muted/30 border border-border",children:[e.jsx(F,{variant:"default",className:"shrink-0 mt-0.5",children:"cited"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:h.post_title||h.keyword}),e.jsxs("p",{className:"text-xs text-muted-foreground italic mt-0.5",children:['"',h.question,'"']})]}),h.citation_url&&e.jsx("a",{href:h.citation_url,target:"_blank",rel:"noopener noreferrer",className:"text-muted-foreground hover:text-foreground shrink-0",title:"Open citation",children:e.jsx(Ke,{className:"w-4 h-4"})})]}
70,h.id))})]})}function Ia(){const{user:s}=V(),{data:r,isLoading:t}=P({queryKey:["ai-visibility-hero",s?.id],enabled:!!s,staleTime:6e4,refetchInterval:5*6e4,queryFn:async()=>{const n=f,i=new Date(Date.now()-30*864e5).toISOString(),{data:o}=await n.from("ai_citation_probes").select("ai_engine, mention_type, cited, probed_at").eq("user_id",s.id).gte("probed_at",i).limit(2e3),c=(o??[]).filter(C=>C.cited||C.mention_type),a=new Set(c.map(C=>String(C.ai_engine).toLowerCase())),m=new Set((o??[]).map(C=>String(C.ai_engine).toLowerCase())),{count:h}=await n.from("page_views").select("id",{count:"exact",head:!0}).eq("user_id",s.id).eq("traffic_type","ai_referral").gte("viewed_at",i),{count:g}=await n.from("tracked_queries").select("id",{count:"exact",head:!0}).eq("user_id",s.id).eq("active",!0),{data:A}=await n.from("tracked_queries").select("last_probed_at").eq("user_id",s.id).not("last_probed_at","is",null).order("last_probed_at",{ascending:!1}).limit(1).maybeSingle();return{mentionCount:c.length,enginesHitCount:a.size,enginesWithDataCount:m.size,enginesWithData:Array.from(m),aiClicks:h??0,trackedCount:g??0,lastScanAt:A?.last_probed_at}}});if(t)return e.jsx(Ne,{className:"h-32 w-full mb-6"});if(!r)return null;const d=r.trackedCount===0&&r.mentionCount===0;return e.jsxs(q,{className:"mb-6 p-5 bg-gradient-to-br from-primary/10 via-background to-background border-primary/30",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ee,{className:"w-5 h-5 text-primary"}),e.jsx("h3",{className:"font-semibold",children:"AI Visibility Radar"}),r.lastScanAt&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1 ml-2",children:[e.jsx(os,{className:"w-3 h-3"}),"last scan ",oe(new Date(r.lastScanAt),{addSuffix:!0})]})]}),e.jsx(b,{asChild:!0,size:"sm",variant:"ghost",className:"text-xs",children:e.jsxs(Z,{to:"/analytics?tab=search",children:["Open radar ",e.jsx(W,{className:"w-3 h-3 ml-1"})]})})]}),d?e.jsx("p",{className:"text-sm text-muted-foreground",children:"We're scanning ChatGPT, Claude, Gemini & Perplexity for your topics. First results appear within 24 hours of publishing."}):e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(Ae,{icon:e.jsx(M,{className:"w-4 h-4"}),label:"AI mentions (30d)",value:r.mentionCount.toString(),sub:`${r.enginesHitCount}/${Math.max(1,r.enginesWithDataCount)} engines with data`}),e.jsx(Ae,{icon:e.jsx(Jt,{className:"w-4 h-4"}),label:"Clicks from AI",value:r.aiClicks.toString(),sub:r.aiClicks===0?"no clicks yet â bots crawl first, humans follow":"humans who clicked through"}),e.jsx(Ae,{icon:e.jsx(ms,{className:"w-4 h-4"}),label:"Queries tracked",value:r.trackedCount.toString(),sub:"across all 4 engines"}),e.jsx(Ae,{icon:e.jsx(Ee,{className:"w-4 h-4"}),label:"Engines reporting",value:`${r.enginesWithDataCount}/4`,sub:r.enginesWithDataCount===0?"warming up â first scan within 24h":r.enginesWithData.map(n=>n[0].toUpperCase()+n.slice(1)).join(" · ")})]})]})}function Ae({icon:s,label:r,value:t,sub:d}){return e.jsxs("div",{className:"bg-background/60 backdrop-blur-sm rounded-lg p-3 border border-border/50",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground mb-1",children:[s,r]}),e.jsx("div",{className:"text-2xl font-bold leading-none",children:t}),d&&e.jsx("div",{className:"text-[10px] text-muted-foreground mt-1",children:d})]})}const Qe=["chatgpt","claude","gemini","perplexity"],$a={chatgpt:"GPT",claude:"Cl",gemini:"Gm",perplexity:"Px"},Fa={chatgpt:"ChatGPT",claude:"Claude",gemini:"Gemini",perplexity:"Perplexity"};function Da({postId:s}){const{user:r}=V(),{data:t}=P({queryKey:["post-engine-chips",r?.id],enabled:!!r,staleTime:5*6e4,queryFn:async()=>{const i=f,o=new Date(Date.now()-30*864e5).toISOString(),{data:c}=await i.from("ai_citation_probes").select("post_id, ai_engine, cited, mention_type").eq("user_id",r.id).gte("probed_at",o).not("post_id","is",null).limit(5e3),a=new Map;for(const m of c??[]){const h=m.post_id,g=String(m.ai_engine).toLowerCase();if(!Qe.includes(g))continue;a.has(h)||a.set(h,{chatgpt:{cited:!1,mentioned:!1},claude:{cited:!1,mentioned:!1},gemini:{cited:!1,mentioned:!1},perplexity:{cited:!1,mentioned:!1}});const A=a.get(h)[g];m.cited&&(A.cited=!0),m.mention_type&&(A.mentioned=!0)}return a}}),d=t?.get(s);
70return!d||!Qe.some(i=>d[i].mentioned||d[i].cited)?null:e.jsx("div",{className:"flex items-center gap-1","aria-label":"AI engine citations",children:Qe.map(i=>{const o=d[i],c=o.cited?"bg-emerald-500/20 text-emerald-700 border-emerald-500/50 dark:text-emerald-300":o.mentioned?"bg-amber-500/15 text-amber-700 border-amber-500/40 dark:text-amber-300":"bg-muted/40 text-muted-foreground/60 border-border",a=o.cited?"cited (URL match)":o.mentioned?"mentioned":"not detected";return e.jsxs(Ds,{children:[e.jsx(Ls,{asChild:!0,children:e.jsx(F,{variant:"outline",className:`text-[10px] px-1.5 py-0 h-4 font-medium ${c}`,children:$a[i]})}),e.jsxs(Es,{side:"top",className:"text-xs",children:[Fa[i],": ",a]})]},i)})})}function La(){const{data:s=[],isLoading:r}=Xt();return _.useMemo(()=>{if(r||s.length===0)return{avgPct:null,postCount:s.length,belowGoodCount:0,weakestPostId:null,isLoading:r};let t=0,d=0,n=null,i=101;for(const o of s){const c=Zt(o.title||"",o.content||"",o.meta_description||""),a=ea(c);t+=a,a<70&&d++,a<i&&(i=a,n=o.id)}return{avgPct:Math.round(t/s.length),postCount:s.length,belowGoodCount:d,weakestPostId:n,isLoading:!1}},[s,r])}function Ea(){return P({queryKey:["corpus-health"],queryFn:async()=>{const{data:{user:s}}=await f.auth.getUser();if(!s)return{current:null,previous:null};const{data:r,error:t}=await f.from("corpus_health_snapshots").select("*").eq("user_id",s.id).order("snapshot_date",{ascending:!1}).limit(2);if(t)throw t;return{current:r?.[0]||null,previous:r?.[1]||null}},staleTime:6e4})}function za(){const s=X(),{avgPct:r,postCount:t,belowGoodCount:d,isLoading:n}=La(),{data:i}=Ea();if(n||t===0)return null;const o=r===null?"text-muted-foreground":r>=80?"text-emerald-600":r>=60?"text-foreground":"text-amber-600",c=i?.current?.avg_score!=null&&i?.previous?.avg_score!=null?i.current.avg_score-i.previous.avg_score:null;return e.jsxs(q,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(zs,{className:"h-3.5 w-3.5"})," Portfolio GEO health"]}),e.jsxs("div",{className:"flex items-baseline gap-2 mt-1",children:[e.jsx("div",{className:`text-3xl font-light tabular-nums ${o}`,children:r??"â"}),c!==null&&e.jsxs("div",{className:`flex items-center gap-0.5 text-xs tabular-nums ${c>0?"text-emerald-600":c<0?"text-amber-600":"text-muted-foreground"}`,children:[c>0?e.jsx(st,{className:"h-3 w-3"}):c<0?e.jsx(tt,{className:"h-3 w-3"}):e.jsx(at,{className:"h-3 w-3"}),c>0?`+${c}`:c," vs last"]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1 truncate",children:["Avg across ",t," post",t===1?"":"s",d>0?` · ${d} need work`:" · all healthy"]})]}),e.jsxs(b,{size:"sm",variant:"ghost",onClick:()=>s("/discovery"),className:"shrink-0",children:["Open ",e.jsx(rs,{className:"ml-1 h-3 w-3"})]})]}),i?.current&&e.jsxs("div",{className:"mt-3 pt-3 border-t grid grid-cols-2 md:grid-cols-4 gap-2 text-[11px]",children:[e.jsx(Pe,{label:"FAQs",value:i.current.pct_with_faqs}),e.jsx(Pe,{label:"Authority cites",value:i.current.pct_with_authority_citations}),e.jsx(Pe,{label:"TL;DR",value:i.current.pct_with_tldr}),e.jsx(Pe,{label:"Fresh <90d",value:i.current.pct_fresh_90d})]})]})}function Pe({label:s,value:r}){const t=r>=70?"text-emerald-600":r>=40?"text-foreground":"text-amber-600";return e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-muted-foreground truncate",children:s}),e.jsxs("span",{className:`tabular-nums font-medium ${t}`,children:[r,"%"]})]})}const Ra={visibility:{label:"Visibility",icon:e.jsx(M,{className:"h-4 w-4"})},refresh:{label:"Refresh",icon:e.jsx(ie,{className:"h-4 w-4"})},publish:{label:"Publish",icon:e.jsx(cs,{className:"h-4 w-4"})},create:{label:"Create",icon:e.jsx(M,{className:"h-4 w-4"})}};function Ma(){const{user:s}=V(),r=X(),[t,d]=_.useState(null);return _.useEffect(()=>{if(!s)return;let n=!1;return Ht(s.id,3).then(i=>{n||d(i)}).catch(()=>{n||d([])}),()=>{n=!0}},[s?.id]),t===null?e.jsxs(q,{className:"p-5 mb-8 flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Q,{className:"h-4 w-4 animate-spin"})," Looking at your dayâ¦"]}):t.length===0?e.jsxs(q,{className:"p-5 mb-8 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:"You're caught up."}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:"Nothing urgent â explore Discovery or start a new article."})]}),e.jsxs(b,{variant:"outline",size:"sm",onClick:()=>r("/discovery"),children:["Discovery ",e.jsx(rs,{className:"ml-1 h-3 w-3"})]})]}):e.jsxs("div",{className:"mb-8",children:[e.jsx("h2",{className:"text-sm font-medium text-muted-foreground mb-3 uppercase tracking-wider",children:"Today"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:t.map(n=>{const i=Ra[n.category];return e.jsxs(q,{className:"p-4 flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mb-2",children:[i.icon,e.jsx("span",{className:"uppercase tracking-wider",children:i.label})]}),e.jsx("div",{className:"text-sm font-medium leading-snug line-clamp-2",children:n.title}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1 line-clamp-2 flex-1",children:n.reason}),e.jsxs(b,{variant:"outline",size:"sm",className:"mt-3 self-start",onClick:()=>r(n.ctaHref),children:[n.ctaLabel," ",e.jsx(rs,{className:"ml-1 h-3 w-3"})]})]},n.key)})})]})}function Ps({userId:s,postsPublishedCount:r,postsTotalCount:t}){const d=X(),{data:n=0}=P({queryKey:["first-run-tracked",s],queryFn:async()=>{const{count:g}=await f.from("tracked_queries").select("id",{count:"exact",head:!0}).eq("user_id",s);return g||0},enabled:!!s}),{data:i=0}=P({queryKey:["first-run-probes",s],queryFn:async()=>{const{count:g}=await f.from("ai_citation_probes").select("id",{count:"exact",head:!0}).eq("user_id",s);return g||0},enabled:!!s}),o=r>0,c=n>0,a=i>0;if(o&&c&&a)return e.jsxs("div",{className:"mb-6 rounded-lg border border-primary/20 bg-primary/5 px-4 py-3 flex items-center gap-3 text-sm",children:[e.jsx(ze,{className:"w-4 h-4 text-primary flex-shrink-0"}),e.jsx("span",{className:"text-foreground",children:"You're set â your content is live, tracked, and being watched across every major AI engine."})]});const h=({done:g,num:A,title:C,subtitle:p,ctaLabel:w,onCta:L,icon:j,disabled:x=!1})=>e.jsxs("div",{className:`flex items-center gap-4 p-4 rounded-lg border transition-colors ${g?"bg-primary/5 border-primary/20":"bg-card border-border hover:border-primary/40"}`,children:[e.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${g?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground"}`,children:g?e.jsx(ze,{className:"w-4 h-4"}):e.jsx("span",{className:"text-sm font-semibold",children:A})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(j,{className:`w-4 h-4 ${g?"text-primary":"text-muted-foreground"}`}),e.jsx("p",{className:`font-medium ${g?"text-muted-foreground line-through":""}`,children:C})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:p})]}),!g&&e.jsxs(b,{size:"sm",variant:"secondary",onClick:L,disabled:x,children:[w,e.jsx(W,{className:"w-3.5 h-3.5 ml-1"})]})]});return e.jsxs(q,{className:"mb-8 border-primary/20 bg-gradient-to-br from-primary/5 to-background",children:[e.jsxs(O,{children:[e.jsxs(K,{className:"flex items-center gap-2 text-2xl",children:[e.jsx(M,{className:"w-6 h-6 text-primary"}),"Your first AI-visibility win"]}),e.jsx(J,{className:"text-base",children:"Three quick steps and you'll see exactly which AI engines quote your work."})]}),e.jsxs(D,{className:"space-y-3",children:[e.jsx(h,{done:o,num:1,title:"Publish your first article",subtitle:t>0&&!o?"You have a draft â publish it to unlock steps 2 and 3.":"The editor walks y
70ou through writing, SEO, and publishing.",ctaLabel:t>0?"Continue draft":"Open editor",onCta:()=>d(t>0?"/dashboard":"/editor/new"),icon:ne}),e.jsx(h,{done:c,num:2,title:"Track a query you want to rank for",subtitle:"We'll watch every major AI engine and tell you when they start quoting you.",ctaLabel:"Add query",onCta:()=>d("/analytics?add_query=1"),icon:ls,disabled:!o}),e.jsx(h,{done:a,num:3,title:"See which AI engines quote you",subtitle:o?"Click Run now on the Analytics page â takes about a minute.":"Unlocks after you publish your first article.",ctaLabel:"Run now",onCta:()=>d("/analytics"),icon:Ee,disabled:!o})]})]})}function Oa(){const{user:s}=V(),{data:r,isLoading:t}=P({queryKey:["two-moats-strip",s?.id],enabled:!!s,staleTime:6e4,queryFn:async()=>{const n=f,i=new Date(Date.now()-30*864e5).toISOString(),[{data:o},{data:c},{count:a}]=await Promise.all([n.from("ai_citation_probes").select("ai_engine, mention_type, cited").eq("user_id",s.id).gte("probed_at",i).limit(2e3),n.from("writer_patterns").select("articles_analyzed, last_analyzed_at").eq("user_id",s.id).maybeSingle(),n.from("tracked_queries").select("id",{count:"exact",head:!0}).eq("user_id",s.id).eq("active",!0)]);return{mentions:(o??[]).filter(h=>h.cited||h.mention_type).length,tracked:a??0,articlesAnalyzed:c?.articles_analyzed??0}}});if(t)return e.jsx(Ne,{className:"h-28 w-full mb-4"});if(!r)return null;const d=r.articlesAnalyzed===0?{label:"not started",dot:"bg-muted-foreground/40"}:r.articlesAnalyzed<3?{label:"learning",dot:"bg-yellow-500"}:r.articlesAnalyzed<7?{label:"developing",dot:"bg-blue-500"}:{label:"strong",dot:"bg-green-500"};return e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"flex items-baseline justify-between mb-2 px-1",children:[e.jsx("h2",{className:"text-sm font-semibold tracking-tight text-muted-foreground uppercase",children:"Your two moats this week"}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Compounding advantages competitors can't copy"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsx(Ts,{to:"/analytics?tab=search",icon:e.jsx(Ee,{className:"w-4 h-4"}),title:"AI Visibility",subtitle:"Cited by ChatGPT, Claude, Gemini, Perplexity",primary:`${r.mentions} mentions · ${r.tracked} queries watched`,hint:r.tracked===0?"Track your first query to start scanning":"See the radar â",accent:"from-primary/10 to-transparent border-primary/30"}),e.jsx(Ts,{to:"/profile#voice",icon:e.jsx(ca,{className:"w-4 h-4"}),title:"Human Voice",subtitle:"Your patterns power every AI surface here",primary:e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx("span",{className:pe("h-1.5 w-1.5 rounded-full",d.dot)}),"Voice: ",d.label,r.articlesAnalyzed>0&&e.jsxs("span",{className:"text-muted-foreground",children:["· ",r.articlesAnalyzed," article",r.articlesAnalyzed===1?"":"s"," analyzed"]})]}),hint:r.articlesAnalyzed===0?"Publish your first article to begin":"Manage voice â",accent:"from-accent/15 to-transparent border-accent/30"})]})]})}function Ts({to:s,icon:r,title:t,subtitle:d,primary:n,hint:i,accent:o}){return e.jsx(Z,{to:s,className:"group block",children:e.jsxs(q,{className:pe("p-4 h-full bg-gradient-to-br border transition-shadow hover:shadow-md",o),children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1 text-sm font-semibold",children:[r,e.jsx("span",{children:t})]}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:d}),e.jsx("div",{className:"text-base font-medium",children:n}),e.jsxs("div",{className:"mt-2 text-[11px] text-primary/80 inline-flex items-center gap-1 opacity-80 group-hover:opacity-100",children:[i,e.jsx(W,{className:"w-3 h-3 transition-transform group-hover:translate-x-0.5"})]})]})})}const Is=10,Ka=8;function Ga(){const{user:s}=V(),r=X(),{data:t,isLoading:d}=P({queryKey:["pillar-coverage-strip",s?.id],enabled:!!s,staleTime:6e4,queryFn:async()=>{const{data:i,error:o}=await f.from("content_pillars").select("id, name, icon, color, created_at").eq("user_id",s.id).order("created_at",{ascending:!0});if(o)throw o;if(!i?.length)return[];const c=i.map(m=>m.id),{data:a}=await f.from("content_pillar_items").select("pillar_id, platform, created_at, post_id").in("pillar_id",c);return i.map(m=>{const h=(a||[]).filter(w=>w.pillar_id===m.id),A=new Set(h.filter(w=>w.platform==="article").map(w=>
70w.post_id).filter(Boolean)).size,C=h.filter(w=>w.platform!=="article").length,p=h.map(w=>w.created_at).filter(Boolean).sort().pop()||null;return{id:m.id,name:m.name,icon:m.icon,color:m.color,articleCount:A,atomizedCount:C,lastActivityAt:p}})}}),n=_.useMemo(()=>{if(!t)return null;const i=t.filter(c=>c.articleCount===0).length,o=t.filter(c=>c.lastActivityAt?(Date.now()-new Date(c.lastActivityAt).getTime())/864e5>Is&&c.articleCount>0:!1).length;return{empty:i,stale:o,total:t.length}},[t]);return d||!t||t.length===0?null:e.jsxs(q,{className:"mb-6 glass-effect",children:[e.jsxs(O,{className:"flex flex-row items-center justify-between space-y-0 pb-3",children:[e.jsxs("div",{children:[e.jsxs(K,{className:"flex items-center gap-2 text-base",children:[e.jsx(M,{className:"w-4 h-4 text-primary"}),"Pillar coverage"]}),e.jsx(J,{className:"text-xs",children:"How visibly you're building each theme. Click a pillar to plan or write."})]}),n&&(n.empty>0||n.stale>0)&&e.jsxs("div",{className:"flex gap-2",children:[n.empty>0&&e.jsxs(F,{variant:"outline",className:"text-xs gap-1",children:[e.jsx(Xe,{className:"w-3 h-3"}),n.empty," empty"]}),n.stale>0&&e.jsxs(F,{variant:"outline",className:"text-xs gap-1",children:[e.jsx(ge,{className:"w-3 h-3"}),n.stale," stale"]})]})]}),e.jsxs(D,{className:"pt-0",children:[e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2",children:t.map(i=>{const o=Math.min(100,Math.round(i.articleCount/Ka*100)),c=i.articleCount===0,a=i.lastActivityAt?(Date.now()-new Date(i.lastActivityAt).getTime())/864e5:null,m=a!==null&&a>Is,h=i.color||"hsl(var(--primary))";return e.jsxs("button",{type:"button",onClick:()=>r(`/content-plan?pillar=${i.id}`),className:"group flex flex-col gap-1.5 p-3 rounded-lg border bg-card/40 hover:bg-card hover:border-primary/40 transition-all text-left",style:{borderColor:`${h}33`},"aria-label":`Open pillar ${i.name}`,children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"text-base shrink-0",children:i.icon||"ð"}),e.jsx("span",{className:"text-sm font-medium truncate flex-1",children:i.name}),c?e.jsxs(F,{variant:"outline",className:"text-[10px] py-0 h-4 px-1.5 gap-0.5",children:[e.jsx(we,{className:"w-2.5 h-2.5"})," empty"]}):m?e.jsx(F,{variant:"outline",className:"text-[10px] py-0 h-4 px-1.5",children:"stale"}):null]}),e.jsx("div",{className:"h-1.5 w-full rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Math.max(o,c?0:6)}%`,backgroundColor:h,opacity:c?0:.85}})}),e.jsxs("div",{className:"flex items-center justify-between text-[11px] text-muted-foreground",children:[e.jsxs("span",{children:[i.articleCount," article",i.articleCount===1?"":"s",i.atomizedCount>0?` · ${i.atomizedCount} atomized`:""]}),e.jsx("span",{className:"opacity-70",children:i.lastActivityAt?`last ${oe(new Date(i.lastActivityAt),{addSuffix:!1})}`:"no activity"})]})]},i.id)})}),n&&n.empty===n.total&&e.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 p-2.5 rounded-md bg-muted/40 border border-dashed",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"No articles tagged to pillars yet â auto-scan from the Pillars panel below, or plan one now."}),e.jsx(b,{size:"sm",variant:"outline",onClick:()=>r("/content-plan"),children:"Plan content"})]})]})]})}const Wa="tf:first_win_import_content";function Ba(){const s=X(),[r,t]=_.useState("idle"),[d,n]=_.useState(""),[i,o]=_.useState(""),[c,a]=_.useState(!1),m=()=>{const g=d.trim();if(g.length<8){N.error("Give me at least a sentence to work with");return}a(!0);const A=new URLSearchParams({title:g.slice(0,200)});s(`/editor/new?${A.toString()}`)},h=()=>{const g=i.trim();if(g.length<40){N.error("Paste at least a paragraph â the more, the better");return}a(!0);try{const A=g.split(/\r?\n/),C=A[0]?.trim()||"",p=A.slice(1).join(` 71`).trim(),w=C.length>0&&C.length<140&&p.length>0,L={title:w?C:"",content:w?p:g,savedAt:Date.now()};sessionStorage.setItem(Wa,JSON.stringify(L))}catch{N.error("Could not stage your paste â try again"),a(!1);return}s("/editor/new?import=1")};return r==="idea"?e.jsxs("div",{className:"rounded-md border border-border bg-background p-5 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Re,{className:"h-4 w-4 text-primary"}),e.jsx("h3",{className:"text-sm font-semibold",children:"One sentence about what you know"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Not a title â the actual point you'd make. Editor will open with this in the title field. You write the body; the toolbar helps with hooks, proofreading, and pull-quotes."}),e.jsx(re,{value:d,onChange:g=>n(g.target.value),placeholder:"e.g. Founder-led content beats agency content because buyers can tell the difference in under 5 seconds.",className:"min-h-[90px] text-sm",autoFocus:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(b,{onClick:m,disabled:c,size:"sm",children:[c?e.jsx(Q,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(W,{className:"h-3.5 w-3.5 mr-1.5"}),"Open editor with this"]}),e.jsx(b,{variant:"ghost",size:"sm",onClick:()=>
71t("idle"),disabled:c,children:"Back"})]})]}):r==="import"?e.jsxs("div",{className:"rounded-md border border-border bg-background p-5 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ks,{className:"h-4 w-4 text-primary"}),e.jsx("h3",{className:"text-sm font-semibold",children:"Paste writing you already have"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"A blog post, a long LinkedIn post, notes from a talk â anything real. First line is treated as the title if it looks short enough. We don't rewrite it; we bring it in as your starting draft."}),e.jsx(re,{value:i,onChange:g=>o(g.target.value),placeholder:"Paste here â plain text or lightly formatted markdown both work.",className:"min-h-[160px] text-sm font-mono",autoFocus:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(b,{onClick:h,disabled:c,size:"sm",children:[c?e.jsx(Q,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(W,{className:"h-3.5 w-3.5 mr-1.5"}),"Open in editor"]}),e.jsx(b,{variant:"ghost",size:"sm",onClick:()=>t("idle"),disabled:c,children:"Back"})]})]}):e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("button",{type:"button",onClick:()=>t("import"),className:"text-left rounded-md border border-border bg-background p-4 hover:border-primary hover:bg-muted/40 transition-colors group",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(ks,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"}),e.jsx("span",{className:"text-sm font-semibold",children:"Import writing you have"})]}),e.jsx("p",{className:"text-xs text-muted-foreground leading-snug",children:"Paste a blog post, a long LinkedIn post, or notes. Comes into the editor as your starting draft â and gives your voice model something real to learn from."}),e.jsxs("span",{className:"mt-3 inline-flex items-center gap-1 text-xs font-medium text-primary",children:["Paste it in",e.jsx(W,{className:"h-3 w-3"})]})]}),e.jsxs("button",{type:"button",onClick:()=>t("idea"),className:"text-left rounded-md border border-border bg-background p-4 hover:border-primary hover:bg-muted/40 transition-colors group",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Re,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"}),e.jsx("span",{className:"text-sm font-semibold",children:"Start with one real idea"})]}),e.jsx("p",{className:"text-xs text-muted-foreground leading-snug",children:"Type one sentence about what you know. Editor opens with it in the title. You write the piece â the toolbar helps with hooks, proofreading, and pull-quotes."}),e.jsxs("span",{className:"mt-3 inline-flex items-center gap-1 text-xs font-medium text-primary",children:["Type one sentence",e.jsx(W,{className:"h-3 w-3"})]})]})]})}const Ua=[{n:1,icon:ne,title:"Write one article",description:"Use the editor (or the AI Agent) to draft a real piece of content."},{n:2,icon:ds,title:"Transform for social",description:"Turn the article into LinkedIn, X, and Threads posts with one click."},{n:3,icon:cs,title:"Publish or schedule",description:"Push to your connected platforms manually â nothing auto-posts."},{n:4,icon:Rs,title:"Track performance",description:"Watch views and search rankings improve as your work compounds."}];function Va(s){const{user:r}=V(),t=X(),d=se(),n=jt(),i=Y({mutationFn:async()=>{if(!r)return;const{data:a}=await f.from("profiles").select("first_run_state").eq("id",r.id).maybeSingle(),m={...a?.first_run_state||{},checklist_dismissed:!0,force_show:!1};await f.from("profiles").update({first_run_state:m}).eq("id",r.id)},onSuccess:()=>{d.invalidateQueries({queryKey:["onboarding-progress",r?.id]})}}),o=Y({mutationFn:async()=>{if(!r)return;const{data:a}=await f.from("profiles").select("first_run_state").eq("id",r.id).maybeSingle(),m={...a?.first_run_state||{},checklist_dismissed:!1,force_show:!0};await f.from("profiles").update({first_run_state:m}).eq("id",r.id)},onSuccess:()=>{d.invalidateQueries({queryKey:["onboarding-progress",r?.id]})}});if(!n.shouldShow)return null;const c=n.totalPosts===0;return e.jsxs("div",{id:"first-run-checklist",className:"mb-6 rounded-lg border border-border bg-card overflow-hidden scroll-mt-20",children:[e.jsxs("div",{className:"flex items-start justify-between p-5 pb-3",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"text-xs font-medium uppercase tracking-wider text-muted-foreground",children:["Welcome to ThoughtForge",n.forceShow&&e.jsx("span",{className:"ml-2 inline-block rounded bg-muted px-1.5 py-0.5 text-[10px] normal-case tracking-normal text-muted-foreground",children:"admin preview"})]}),e.jsx("h2",{className:"text-lg font-semibold text-foreground mt-1",children:c?"Let's ship your first article. Two ways in.":"How it works â write once, ship everywhere"}),c&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Neither path auto-writes for you. Both end with a real article under your name â under 15 minutes if you already know what to say."})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[n.isAdmin&&!n.forceShow&&e.jsxs(b,{variant:"ghost",size:"sm",onClick:()=>o.mutate(),className:"h-7 text-xs text-muted-foreground hover:text-foreground",title:"Admin only: re-show explainer for QA",children:[e.jsx(It,{className:"h-3 w-3 mr-1"}),"Reset"]}),e.jsx(b,{variant:"ghost",size:"icon",className:"h-7 w-7 -mt-1 -mr-1 text-muted-foreground hover:text-foreground",onClick:()=>i.mutate(),"aria-label":"Dismiss explainer",children:e.jsx(Oe,{className:"h-4 w-4"})})]})]}),c?e.jsx("div",{className:"px-5 pb-5",children:e.jsx(Ba,{})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 px-5 pb-4",children:Ua.map(a=>{const m=a.icon;return e.jsxs("div",{className:"rounded-md border border-border bg-background p-4 flex flex-col gap-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-xs font-mono text-muted-foreground",children:["0",a.n]}),e.jsx(m,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx("p",{className:"text-sm font-medium text-foreground",children:a.title}),e.jsx("p",{className:"text-xs text-muted-foreground leading-snug",children:a.description})]},a.n)})}),e.jsx("div",{className:"px-5 pb-5",children:e.jsxs(b,{onClick:()=>t("/editor/new"),className:"w-full sm:w-auto gap-2",size:"lg",children:["Write your first article",e.jsx(W,{className:"h-4 w-4"})]})})]})]})}function Qa(){const{user:s}=V(),{data:r,isLoading:t}=P({queryKey:["voice-strength-badge",s?.id],enabled:!!s,staleTime:6e4,queryFn:async()=>{const{data:o}=await f.from("writer_patterns").select("articles_analyzed, last_analyzed_at").eq("user_id",s.id).maybeSingle();return o}});if(t||!s)return null;const d=r?.articles_analyzed??0,n=d===0?{label:"Voice: waiting",dotClass:"bg-muted-foreground
71/40",textClass:"text-muted-foreground"}:d<3?{label:`Voice: learning (${d})`,dotClass:"bg-yellow-500",textClass:"text-foreground"}:d<7?{label:`Voice: trained (${d})`,dotClass:"bg-blue-500",textClass:"text-foreground"}:{label:`Voice: trained (${d})`,dotClass:"bg-green-500",textClass:"text-foreground"},i=d===0?"Publish your first article and I'll start learning your voice. Every AI feature â transformation, optimization, distribution â uses your voice so drafts sound like you, not like a bot.":"I'm learning your voice from your published articles. Every AI feature uses this so drafts sound like you. Sharper with every article you publish.";return e.jsx(bt,{children:e.jsxs(Ds,{children:[e.jsx(Ls,{asChild:!0,children:e.jsxs("div",{className:pe("inline-flex items-center gap-2 h-7 px-3 rounded-full border border-border bg-card text-xs font-medium",n.textClass),children:[e.jsx(M,{className:"h-3 w-3"}),e.jsx("span",{className:pe("h-1.5 w-1.5 rounded-full",n.dotClass)}),n.label]})}),e.jsx(Es,{side:"bottom",className:"max-w-[260px]",children:e.jsx("p",{className:"text-xs",children:i})})]})})}function Ha(){const{user:s}=V(),r=se(),[t,d]=_.useState(!1),[n,i]=_.useState(null),[o,c]=_.useState(""),[a,m]=_.useState(""),{data:h=[],isLoading:g}=P({queryKey:["private-notes",s?.id],queryFn:async()=>{if(!s)return[];const{data:j,error:x}=await f.from("private_notes").select("*").order("pinned",{ascending:!1}).order("updated_at",{ascending:!1});if(x)throw x;return j||[]},enabled:!!s}),A=Y({mutationFn:async()=>{if(!s)throw new Error("not authenticated");const{data:j,error:x}=await f.from("private_notes").insert({user_id:s.id,title:"Untitled note",body:""}).select().single();if(x)throw x;return j},onSuccess:j=>{r.invalidateQueries({queryKey:["private-notes",s?.id]}),i(j.id),c(j.title),m(j.body),d(!0)},onError:j=>N.error(`Could not create note: ${j.message}`)}),C=Y({mutationFn:async({id:j,title:x,body:v})=>{const{error:T}=await f.from("private_notes").update({title:x,body:v}).eq("id",j);if(T)throw T},onSuccess:()=>{r.invalidateQueries({queryKey:["private-notes",s?.id]}),N.success("Saved"),i(null)},onError:j=>N.error(`Save failed: ${j.message}`)}),p=Y({mutationFn:async j=>{const{error:x}=await f.from("private_notes").update({pinned:!j.pinned}).eq("id",j.id);if(x)throw x},onSuccess:()=>r.invalidateQueries({queryKey:["private-notes",s?.id]})}),w=Y({mutationFn:async j=>{const{error:x}=await f.from("private_notes").delete().eq("id",j);if(x)throw x},onSuccess:()=>{r.invalidateQueries({queryKey:["private-notes",s?.id]}),n&&i(null),N.success("Deleted")}}),L=_.useCallback(j=>{i(j.id),c(j.title),m(j.body)},[]);return s?e.jsx(q,{className:"mb-8 border-dashed",children:e.jsxs(Hs,{open:t,onOpenChange:d,children:[e.jsx(O,{children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Ze,{className:"w-4 h-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs(K,{className:"text-base flex items-center gap-2",children:["Private Notes",e.jsx(F,{variant:"secondary",className:"text-[10px] uppercase tracking-wider",children:"Only you"})]}),e.jsxs(J,{className:"text-xs",children:["Never read by AI, agents, digests, or analytics. ",h.length>0&&`${h.length} note${h.length===1?"":"s"}.`]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs(b,{size:"sm",variant:"outline",onClick:j=>{j.stopPropagation(),A.mutate()},disabled:A.isPending,children:[e.jsx(we,{className:"w-3.5 h-3.5 mr-1"})," New"]}),e.jsx(Ys,{asChild:!0,children:e.jsx(b,{size:"sm",variant:"ghost",children:e.jsx(ns,{className:`w-4 h-4 transition-transform ${t?"rotate-180":""}`})})})]})]})}),e.jsx(Js,{children:e.jsxs(D,{className:"space-y-3",children:[g&&e.jsxs("div",{className:"text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(Q,{className:"w-4 h-4 animate-spin"})," Loadingâ¦"]}),!g&&h.length===0&&e.jsxs("p",{className:"text-sm text-muted-foreground py-2",children:["No notes yet. Click ",e.jsx("strong",{children:"New"})," to add your first one. Use this for outreach lists, draft ideas, things to remember â anything you want kept off the system."]}),h.map(j=>{const x=n===j.id;return e.jsx("div",{className:"border rounded-md p-3 bg-background/50 space-y-2",children:x?e.jsxs(e.Fragment,{children:[e.jsx(he,{value:o,onChange:v=>c(v.target.value),placeholder:"Title",className:"font-medium"}),e.jsx(re,{value:a,onChange:v=>m(v.target.value),placeholder:"Markdown is fine. This stays between you and your browser session.",rows:8,className:"font-mono text-sm"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(b,{size:"sm",onClick:()=>C.mutate({id:j.id,title:o,body:a}),disabled:C.isPending,children:[e.jsx(sa,{className:"w-3.5 h-3.5 mr-1"}),C.isPending?"Savingâ¦":"Save"]}),e.jsx(b,{size:"sm",variant:"ghost",onClick:()=>i(null),children:"Cancel"}),e.jsx("div",{className:"flex-1"}),e.jsx(b,{size:"sm",variant:"ghost",onClick:()=>{confirm("Delete this note?")&&w.mutate(j.id)},children:e.jsx(Ge,{className:"w-3.5 h-3.5 text-destructive"})})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>L(j),className:"flex-1 text-left min-w-0",children:[e.jsxs("div",{className:"font-medium truncate flex items-center gap-2",children:[j.pinned&&e.jsx(ws,{className:"w-3 h-3 text-primary shrink-0"}),j.title||"Untitled note"]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Updated ",oe(new Date(j.updated_at),{addSuffix:!0})]})]}),e.jsx(b,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>p.mutate(j),title:j.pinned?"Unpin":"Pin",children:j.pinned?e.jsx(Yt,{className:"w-3.5 h-3.5"}):e.jsx(ws,{className:"w-3.5 h-3.5"})})]}),j.body&&e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap line-clamp-4",children:j.body})]})},j.id)})]})})]})}):null}function Ya(){const{user:s}=V(),r=X(),[t,d]=_.useState(!1),{data:n}=P({queryKey:["personal-site-card-profile",s?.id],enabled:!!s?.id,staleTime:6e4,queryFn:async()=>{const{data:g}=await f.from("profiles").select("username, full_name, custom_domain").eq("id",s.id).maybeSingle();return g}}),{data:i}=P({queryKey:["personal-site-card-latest",s?.id],enabled:!!s?.id,staleTime:6e4,queryFn:async()=>{const{data:g}=await f.from("posts").select("title, slug, published_at").eq("author_id",s.id).eq("status","published").eq("published_to_platform",!0).order("published_at",{ascending:!1}).limit(1).maybeSingle();return g}}),{data:o}=P({queryKey:["personal-site-card-count",s?.id],enabled:!!s?.id,staleTime:6e4,queryFn:async()=>{const{count:g}=await f.from("posts").select("*",{count:"exact",head:!0}).eq("author_id",s.id).eq("status","published").eq("published_to_platform",!0);return g??0}});if(!s||!n?.username)return null;const c=n.custom_domain?`https://${n.custom_domain}`:`${window.location.origin}/user/${n.username}`,a=n.custom_domain||`${window.location.host}/user/${n.username}`,m=async()=>{try{await navigator.clipboard.writeText(c),d(!0),N.success("Link copied"),setTimeout(()=>d(!1),1600)}catch{N.error("Could not copy link")}}
71,h=(o??0)>0;return e.jsxs(q,{className:"glass-effect mb-6",children:[e.jsx(O,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs(K,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(xe,{className:"h-4 w-4 text-primary"}),"Your site is live"]}),e.jsxs("button",{onClick:m,className:"mt-1 group flex items-center gap-2 text-base sm:text-lg font-mono font-medium text-foreground hover:text-primary transition-colors truncate max-w-full text-left",title:"Click to copy",children:[e.jsx("span",{className:"truncate",children:a}),t?e.jsx(ze,{className:"h-3.5 w-3.5 shrink-0 text-green-500"}):e.jsx(Me,{className:"h-3.5 w-3.5 shrink-0 opacity-40 group-hover:opacity-100 transition-opacity"})]})]}),n.custom_domain&&e.jsx(F,{variant:"outline",className:"shrink-0",children:"Custom domain"})]})}),e.jsxs(D,{className:"space-y-4",children:[h&&i?e.jsxs("div",{className:"text-sm",children:[e.jsx("div",{className:"text-xs text-muted-foreground uppercase tracking-wide mb-1",children:"Latest article"}),e.jsx("div",{className:"font-medium truncate",children:i.title}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-0.5",children:[i.published_at&&`Published ${oe(new Date(i.published_at),{addSuffix:!0})}`," · ",o," article",o===1?"":"s"," live"]})]}):e.jsx("div",{className:"text-sm text-muted-foreground",children:"Your site is ready â publish your first article to fill it."}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[h?e.jsx(b,{size:"sm",asChild:!0,children:e.jsxs("a",{href:c,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Ke,{className:"h-3.5 w-3.5 mr-1.5"}),"Visit site"]})}):e.jsxs(b,{size:"sm",onClick:()=>r("/editor/new"),children:[e.jsx(ne,{className:"h-3.5 w-3.5 mr-1.5"}),"Write your first article"]}),e.jsx(b,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs(Z,{to:"/personal-site-preview",children:[e.jsx(We,{className:"h-3.5 w-3.5 mr-1.5"}),"Preview in app"]})}),e.jsxs(b,{size:"sm",variant:"ghost",onClick:m,children:[t?e.jsx(ze,{className:"h-3.5 w-3.5 mr-1.5 text-green-500"}):e.jsx(Me,{className:"h-3.5 w-3.5 mr-1.5"}),"Copy link"]}),h&&e.jsx(b,{size:"sm",variant:"ghost",asChild:!0,children:e.jsxs("a",{href:`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(c)}`,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(je,{className:"h-3.5 w-3.5 mr-1.5"}),"Share on LinkedIn"]})})]})]})]})}const Ja={editor:"/editor/new",pillars:"/discovery",radar:"/analytics",distribute:"/distribute",analytics:"/analytics","personal-site":"/personal-site"};function Xa(){const s=new Date,r=s.getDay(),t=s.getDate()-r+(r===0?-6:1);return s.setDate(t),s.toISOString().split("T")[0]}function Za(){const{user:s}=V(),r=X(),t=se(),d=Xa(),{data:n,isLoading:i}=P({queryKey:["weekly-coach",s?.id,d],enabled:!!s,staleTime:5*6e4,queryFn:async()=>{const{data:a}=await f.from("weekly_briefs").select("brief").eq("user_id",s.id).eq("week_of",d).maybeSingle();return a?.brief?.coach??null}}),o=Y({mutationFn:async()=>{const{data:a,error:m}=await f.functions.invoke("weekly-coach-brief",{body:{force:!0}});if(m)throw m;return a},onSuccess:()=>{N.success("Coach brief refreshed"),t.invalidateQueries({queryKey:["weekly-coach"]})},onError:a=>N.error(a.message||"Failed to refresh coach")});if(i)return e.jsx(Ne,{className:"h-52 w-full"});if(!n)return e.jsx(q,{className:"border-primary/20 bg-gradient-to-br from-primary/5 to-transparent",children:e.jsx(O,{children:e.jsxs("div",{className:"flex items-start justify-between gap-4 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs(K,{className:"flex items-center gap-2 text-base",children:[e.jsx(M,{className:"w-4 h-4 text-primary"}),"Your Founder Coach â Week of ",vs(new Date(d),"MMM d")]}),e.jsx(J,{className:"mt-1",children:"Get an honest read of what worked, what broke, and the exact next move for the week."})]}),e.jsx(b,{size:"sm",onClick:()=>o.mutate(),disabled:o.isPending,children:o.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ie,{className:"w-3.5 h-3.5 mr-2 animate-spin"})," Analyzingâ¦"]}):e.jsxs(e.Fragment,{children:[e.jsx(M,{className:"w-3.5 h-3.5 mr-2"})," Generate this week's coach"]})})]})})});const c={low:{label:"Low confidence",cls:"text-muted-foreground border-border"},medium:{label:"Medium confidence",cls:"text-blue-600 border-blue-500/30 dark:text-blue-400"},high:{label:"High confidence",cls:"text-emerald-600 border-emerald-500/30 dark:text-emerald-400"}}
71[n.confidence];return e.jsxs(q,{className:"border-primary/20 bg-gradient-to-br from-primary/5 to-transparent",children:[e.jsx(O,{children:e.jsxs("div",{className:"flex items-start justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs(K,{className:"flex items-center gap-2 text-base",children:[e.jsx(M,{className:"w-4 h-4 text-primary"}),"Your Founder Coach â Week of ",vs(new Date(d),"MMM d")]}),e.jsx("p",{className:"mt-2 text-base font-medium leading-snug",children:n.headline}),e.jsxs("div",{className:"flex items-center gap-2 mt-2 flex-wrap",children:[e.jsx(F,{variant:"outline",className:`text-[10px] h-5 ${c.cls}`,children:c.label}),n.sample&&e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["Based on ",n.sample.articles_published,"p · ",n.sample.category_probes,"cat probes ·"," ",n.sample.gsc_impressions," impr · ",n.sample.ai_referrals," AI refs"]})]})]}),e.jsx(b,{variant:"ghost",size:"sm",onClick:()=>o.mutate(),disabled:o.isPending,title:"Refresh coach",children:e.jsx(ie,{className:`w-3.5 h-3.5 ${o.isPending?"animate-spin":""}`})})]})}),e.jsxs(D,{className:"grid gap-4 md:grid-cols-2",children:[n.won_this_week&&n.won_this_week.length>0&&e.jsxs("section",{children:[e.jsxs("h4",{className:"text-xs font-semibold uppercase tracking-wide text-emerald-700 dark:text-emerald-400 mb-2 flex items-center gap-1.5",children:[e.jsx(ge,{className:"w-3.5 h-3.5"})," Won this week"]}),e.jsx("ul",{className:"space-y-2",children:n.won_this_week.map((a,m)=>e.jsxs("li",{className:"text-sm",children:[e.jsx("div",{className:"font-medium",children:a.metric}),e.jsx("div",{className:"text-xs text-muted-foreground",children:a.why_it_matters})]},m))})]}),n.broke_this_week&&n.broke_this_week.length>0&&e.jsxs("section",{children:[e.jsxs("h4",{className:"text-xs font-semibold uppercase tracking-wide text-amber-700 dark:text-amber-400 mb-2 flex items-center gap-1.5",children:[e.jsx(ye,{className:"w-3.5 h-3.5"})," Needs attention"]}),e.jsx("ul",{className:"space-y-2",children:n.broke_this_week.map((a,m)=>e.jsxs("li",{className:"text-sm",children:[e.jsx("div",{className:"font-medium",children:a.issue}),e.jsx("div",{className:"text-xs text-muted-foreground mb-1",children:a.fix_action}),e.jsxs(b,{variant:"link",size:"sm",className:"h-auto p-0 text-xs",onClick:()=>r(Ja[a.action_target]||"/analytics"),children:["Go fix it ",e.jsx(W,{className:"w-3 h-3 ml-1"})]})]},m))})]}),n.double_down&&e.jsxs("section",{className:"md:col-span-2 border-t pt-3",children:[e.jsxs("h4",{className:"text-xs font-semibold uppercase tracking-wide text-primary mb-2 flex items-center gap-1.5",children:[e.jsx(ms,{className:"w-3.5 h-3.5"})," Double down"]}),e.jsx("p",{className:"text-sm font-medium",children:n.double_down.recommendation}),n.double_down.suggested_title&&e.jsxs("p",{className:"text-xs mt-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"Suggested title:"})," ",e.jsxs("span",{className:"italic",children:['"',n.double_down.suggested_title,'"']})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:n.double_down.reason}),e.jsxs(b,{size:"sm",className:"mt-2",onClick:()=>r(n.double_down?.suggested_title?`/editor/new?seed=${encodeURIComponent(n.double_down.suggested_title)}`:"/editor/new"),children:["Start writing ",e.jsx(W,{className:"w-3.5 h-3.5 ml-1"})]})]}),n.experiment&&e.jsxs("section",{className:"md:col-span-2 border-t pt-3",children:[e.jsxs("h4",{className:"text-xs font-semibold uppercase tracking-wide text-blue-700 dark:text-blue-400 mb-2 flex items-center gap-1.5",children:[e.jsx(yt,{className:"w-3.5 h-3.5"})," This week's experiment"]}),e.jsx("p",{className:"text-sm font-medium",children:n.experiment.bet}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[e.jsx("span",{className:"font-medium",children:"Hypothesis:"})," ",n.experiment.hypothesis]})]}),n.empty_state&&e.jsx("p",{className:"md:col-span-2 text-xs text-muted-foreground border-t pt-3",children:"The coach improves with every article you publish. Come back after 3â5 pieces for high-confidence signal."})]})]})}const er={perplexity:"Perplexity",chatgpt:"ChatGPT",claude:"Claude",gemini:"Gemini"};function sr(){const s=new Date,r=s.getDay(),t=s.getDate()-r+(r===0?-6:1);return s.setDate(t),s.toISOString().split("T")[0]}function tr({points:s}){if(!s||s.length<2)return e.jsx("div",{className:"h-3 w-16 rounded bg-muted/40"});const r=64,t=14,d=s.map(m=>m>0?-m:0),n=Math.min(...d),o=Math.max(...d)-n||1,c=r/(s.length-1),a=s.map((m,h)=>{const g=h*c,A=t-(d[h]-n)/o*t;return`${h===0?"M":"L"}${g.toFixed(1)},${A.toFixed(1)}`}).join(" ");return e.jsx("svg",{width:r,height:t,className:"text-primary shrink-0","aria-hidden":!0,
71children:e.jsx("path",{d:a,fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round"})})}const He={rising:{label:"RISING",icon:ge,cls:"bg-emerald-500/15 text-emerald-700 dark:text-emerald-400 border-emerald-500/30"},flat:{label:"FLAT",icon:at,cls:"bg-muted text-muted-foreground border-border"},slipping:{label:"SLIPPING",icon:et,cls:"bg-amber-500/15 text-amber-700 dark:text-amber-400 border-amber-500/30"}};function ar(){const{user:s}=V(),r=X(),t=se(),d=sr(),{data:n,isLoading:i}=P({queryKey:["weekly-coach",s?.id,d],enabled:!!s,staleTime:5*6e4,queryFn:async()=>{const{data:j}=await f.from("weekly_briefs").select("brief").eq("user_id",s.id).eq("week_of",d).maybeSingle();return j?.brief?.coach??null}}),o=Y({mutationFn:async()=>{const{data:j,error:x}=await f.functions.invoke("weekly-coach-brief",{body:{force:!0}});if(x)throw x;return j},onSuccess:()=>{N.success("Coach brief refreshed"),t.invalidateQueries({queryKey:["weekly-coach"]})},onError:j=>N.error(j.message||"Failed to refresh")}),{data:c,isLoading:a}=P({queryKey:["one-screen-probes",s?.id],enabled:!!s,staleTime:5*6e4,queryFn:async()=>{const j=new Date(Date.now()-2592e6).toISOString(),{data:x}=await f.from("ai_citation_probes").select("keyword, ai_engine, cited, rank_position, probed_at").eq("user_id",s.id).gte("probed_at",j).order("probed_at",{ascending:!1}).limit(500);return x||[]}}),m=_.useMemo(()=>{if(!c||c.length===0)return[];const j=new Map;for(const v of c){if(!v.cited)continue;const T=`${v.keyword}::${v.ai_engine}`,G=v.rank_position??99,k=new Date(v.probed_at).getTime(),E=j.get(T)||{query:v.keyword,engine:v.ai_engine,ranks:[],cites:0};E.ranks.push({ts:k,rank:G}),E.cites+=1,j.set(T,E)}const x=Array.from(j.values()).map(v=>{const T=v.ranks.sort((E,u)=>E.ts-u.ts),G=Math.min(...T.map(E=>E.rank)),k=T.slice(-8).map(E=>E.rank);return{query:v.query,engine:v.engine,bestRank:G,cites:v.cites,spark:k}});return x.sort((v,T)=>v.bestRank-T.bestRank||T.cites-v.cites),x.slice(0,3)},[c]);if(i||a)return e.jsx(Ne,{className:"h-64 w-full mb-6"});if(!n)return e.jsx(q,{className:"mb-6 border-primary/20 bg-gradient-to-br from-primary/5 via-background to-background",children:e.jsx(D,{className:"p-6 sm:p-8",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center gap-4 justify-between",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(M,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground font-medium",children:"Your One Screen"})]}),e.jsx("h2",{className:"text-xl sm:text-2xl font-semibold leading-tight",children:"Get an honest read of your week in one glance."}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1.5",children:"We'll analyze your citations, ranks, and referrals â then hand you the single move to make this week."})]}),e.jsx(b,{size:"lg",onClick:()=>o.mutate(),disabled:o.isPending,children:o.isPending?e.jsxs(e.Fragment,{children:[e.jsx(ie,{className:"w-4 h-4 mr-2 animate-spin"})," Analyzingâ¦"]}):e.jsxs(e.Fragment,{children:[e.jsx(M,{className:"w-4 h-4 mr-2"})," Show me the one screen"]})})]})})});const g=n.won_this_week?.length??0,A=n.broke_this_week?.length??0,C=n.verdict,p=C&&C in He?C:g>A?"rising":A>g?"slipping":"flat",w=He[p]??He.flat,L=w.icon;return e.jsx(q,{className:"mb-6 border-primary/20 bg-gradient-to-br from-primary/5 via-background to-background overflow-hidden",children:e.jsxs(D,{className:"p-5 sm:p-7 space-y-6",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(F,{variant:"outline",className:`h-7 px-3 text-xs font-bold tracking-wider border ${w.cls}`,children:[e.jsx(L,{className:"w-3.5 h-3.5 mr-1.5"}),w.label]}),e.jsx("span",{className:"text-[11px] text-muted-foreground uppercase tracking-wide",children:"last 7 days"})]}),e.jsx("p",{className:"mt-3 text-base sm:text-lg font-medium leading-snug text-foreground",children:n.headline})]}),e.jsx(b,{variant:"ghost",size:"sm",onClick:()=>o.mutate(),disabled:o.isPending,title:"Refresh coach",className:"shrink-0",children:e.jsx(ie,{className:`w-3.5 h-3.5 ${o.isPending?"animate-spin":""}`})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[e.jsx(zs,{className:"h-3.5 w-3.5 text-emerald-600 dark:text-emerald-400"}),e.jsx("span",{className:"text-xs uppercase tracking-wide font-semibold text-muted-foreground",children:"Where you're winning"})]}),m.length===0?e.jsxs("div",{className:"rounded-lg border border-dashed border-border p-4 text-sm text-muted-foreground",children:["No AI citations yet in the last 30 days. Track a query to start measuring."," ",e.jsx("button",{className:"text-primary hover:underline font-medium",onClick:()=>r("/analytics?tab=search"),children:"Track a query â"})]}):e.jsx("ul",{className:"divide-y divide-border/50 rounded-lg border border-border bg-card/40",children:m.map((j,x)=>e.jsxs("li",{className:"flex items-center gap-3 px-3 py-2.5",children:[e.jsxs("span",{className:"text-sm font-medium truncate flex-1 min-w-0",title:j.query,children:['"',j.query,'"']}),e.jsx("span",{className:"text-xs text-muted-foreground w-20 shrink-0 hidden sm:inline",children:er[j.engine]??j.engine}),e.jsxs(F,{variant:"secondary",className:"text-[10px] h-5 tabular-nums shrink-0",children:["#",j.bestRank]}),e.jsx(tr,{points:j.spark})]},x))})]}),n.double_down?e.jsxs("div",{className:"rounded-lg border border-primary/30 bg-primary/5 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[e.jsx(M,{className:"h-3.5 w-3.5 text-primary"}),e.jsx("span",{className:"text-xs uppercase tracking-wide font-semibold text-primary",children:"This week's one move"})]}),e.jsx("p",{className:"text-sm font-medium leading-snug",children:n.double_down.recommendation}),n.double_down.suggested_title&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 italic",children:['"',n.double_down.suggested_title,'"']}),n.double_down.reason&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1.5",children:n.double_down.reason}),e.jsxs(b,{size:"sm",className:"mt-3",onClick:()=>r(n.double_down?.suggested_title?`/editor/new?seed=${encodeURIComponent(n.double_down.suggested_title)}`:"/editor/new"),children:["Draft it now ",e.jsx(W,{className:"w-3.5 h-3.5 ml-1.5"})]})]}):e.jsx("div",{className:"rounded-lg border border-dashed border-border p-4 text-sm text-muted-foreground",children:"The coach hasn't picked this week's move yet. Publish 1â2 articles and refresh."})]})})}const Yr=()=>{const{user:s,loading:r}=V(),{tier:t,subscribed:d}=wt(),n=X(),i=se(),[o,c]=_.useState("all"),[a,m]=_.useState("recent"),[h,g]=_.useState(null),[A,C]=_.useState(""),[p,w]=_.useState(30),[L,j]=_.useState(!1),[x,v]=_.useState(""),T=$t(),[G,k]=_.useState(null),E=async l=>{const y={id:l.id,title:l.title,content:l.content||"",meta:l.meta_description||""};k(y),N.info("Optimizing for AI citationsâ¦",{description:"This usually takes 15-30 seconds."}),await T.run({postId:y.id,title:y.title,content:y.content,metaDescription:y.meta,failingChecks:["geo-tldr","geo-meta-direct","geo-question-headings","geo-direct-answers","geo-faq","geo-definitive"]})||k(null)};_.useEffect(()=>{localStorage.getItem("tf_first_login")==="true"&&(localStorage.removeItem("tf_first_login"),N.success("Welcome to ThoughtForge ð",{description:"Your content engine is ready. Write your first article â the AI handles SEO, voice, and publishing.",duration:8e3,action:{label:"Start writing",onClick:()=>n("/editor/new")}}))},[n]),_.useEffect(()=>{const l=new URLSearchParams(window.location.search);if(l.get("test_checkout")!=="1")return;const y=Number(l.get("started")||0),U=y?((Date.now()-y)/1e3).toFixed(1):"?";N.success("Sandbox checkout complete",{description:`Round-trip to /dashboard in ${U}s. Live subscription state untouched.`,duration:1e4}),window.history.replaceState({},"","/dashboard")},[]);const{data:u}=P({queryKey:["is-admin",s?.id],queryFn:async()=>
71{if(!s)return!1;const{data:l}=await f.from("user_roles").select("role").eq("user_id",s.id).eq("role","admin").single();return!!l},enabled:!!s}),{data:S}=P({queryKey:["ranking-alerts",s?.id],queryFn:async()=>{if(!s)return[];const{data:l}=await f.from("ranking_alerts").select("*").eq("user_id",s.id).order("created_at",{ascending:!1}).limit(20);return l||[]},enabled:!!s}),R=S?.filter(l=>!l.seen)||[],I=async()=>{!s||R.length===0||(await f.from("ranking_alerts").update({seen:!0}).eq("user_id",s.id).eq("seen",!1),i.invalidateQueries({queryKey:["ranking-alerts"]}))},{data:B}=P({queryKey:["access-codes"],queryFn:async()=>{const{data:l}=await f.from("access_codes").select("*").order("created_at",{ascending:!1}).limit(20);return l||[]},enabled:!!u}),ce=async()=>{if(s){j(!0);try{const l=Array.from(crypto.getRandomValues(new Uint8Array(4))).map(U=>U.toString(36).toUpperCase().padStart(2,"0")).join("").slice(0,8),{error:y}=await f.from("access_codes").insert({code:l,label:A||null,created_by:s.id,duration_days:p,expires_at:new Date(Date.now()+p*24*60*60*1e3).toISOString()});if(y)throw y;v(l),C(""),i.invalidateQueries({queryKey:["access-codes"]}),N.success("Access code generated!")}catch(l){N.error(l.message||"Failed to generate code")}finally{j(!1)}}},de=Y({mutationFn:async l=>{const{error:y}=await f.from("posts").delete().eq("id",l);if(y)throw y},onSuccess:()=>{i.invalidateQueries({queryKey:["posts"]}),N.success("Article deleted successfully")},onError:l=>{N.error(`Failed to delete: ${l.message}`)}}),{data:$}=P({queryKey:["user-profile",s?.id],queryFn:async()=>{if(!s)return null;const{data:l,error:y}=await f.from("profiles").select("username").eq("id",s.id).single();if(y)throw y;return l},enabled:!!s}),te=l=>{if(!$?.username){N.error("Username not set. Please set your username in profile settings.");return}const y=`${window.location.origin}/user/${$.username}/${l.slug}`;navigator.clipboard.writeText(y),N.success("Link copied to clipboard!")},[us,rt]=_.useState(()=>localStorage.getItem("tf_onboarding_dismissed")==="true"),{data:ve}=P({queryKey:["connection-status",s?.id],queryFn:async()=>{if(!s)return null;const[l,y,U]=await Promise.all([f.from("linkedin_connections").select("id",{count:"exact",head:!0}).eq("user_id",s.id),f.from("twitter_connections").select("id",{count:"exact",head:!0}).eq("user_id",s.id),f.from("cms_integrations").select("id",{count:"exact",head:!0}).eq("user_id",s.id).eq("status","active")]);return{hasLinkedin:(l.count||0)>0,hasTwitter:(y.count||0)>0,hasCms:(U.count||0)>0}},enabled:!!s&&!us}),nt=!us&&ve&&!ve.hasLinkedin&&!ve.hasTwitter&&!ve.hasCms,it=()=>{localStorage.setItem("tf_onboarding_dismissed","true"),rt(!0)},{data:z,isLoading:xs}=P({queryKey:["posts",s?.id,$?.username],queryFn:async()=>{const{data:l,error:y}=await f.from("posts").select("*").eq("author_id",s.id).order("updated_at",{ascending:!1});if(y)throw y;const U=$?.username||"",H={},ps=10;for(let me=0;me<l.length;me+=ps){const dt=l.slice(me,me+ps);(await Promise.all(dt.map(async ue=>{const mt=U?`page_path.eq./${ue.slug},page_path.eq./user/${U}/${ue.slug}`:`page_path.eq./${ue.slug}`,{count:ut}=await f.from("page_views").select("*",{count:"exact",head:!0}).eq("is_bot",!1).or(mt);return{post_id:ue.id,count:ut||0}}))).forEach(ue=>{H[ue.post_id]=ue.count})}return l.map(me=>({...me,viewCount:H[me.id]||0,linkedInEngagement:0}))},enabled:!!s}),hs=_.useMemo(()=>{if(!z)return[];let l=[...z];switch(o){case"drafts":l=l.filter(y=>y.status==="draft");break;case"platform":l=l.filter(y=>y.published_to_platform);break;case"linkedin":l=l.filter(y=>y.linkedin_post_url);break;case"top":l=l.filter(y=>y.viewCount>50||y.linkedInEngagement>10);break;case"attention":l=l.filter(y=>y.status==="published"&&y.published_to_platform&&y.viewCount<10&&y.linkedInEngagement<5);break}switch(a){case"views":l.sort((y,U)=>U.viewCount-y.viewCount);break;case"engagement":l.sort((y,U)=>U.linkedInEngagement-y.linkedInEngagement);break;case"recent":default:l.sort((y,U)=>new Date(U.updated_at).getTime()-new Date(y.updated_at).getTime());break}return l},[z,o,a]);if(r||!s)return e.jsx(Nt,{});const lt=z?.filter(l=>l.status==="draft").length||0,Be=z?.filter(l=>l.published_to_platform).length||0,ot=z?.filter(l=>l.linkedin_post_url).length||0,Ue=l=>{const y=l.viewCount+l.linkedInEngagement*2;if(y>=500)return{label:"Viral",variant:"default",color:"text-purple-500",icon:e.jsx(M,{className:"w-3 h-3 mr-1"})};if(y>=61)return{label:"Hot",variant:"default",color:"text-orange-500",icon:e.jsx(js,{className:"w-3 h-3 mr-1"})};if(y>=21)return{label:"Growing",variant:"secondary",color:"text-blue-500",icon:e.jsx(ge,{className:"w-3 h-3 mr-1"})};const U=l.platform_published_at||l.published_at;return U&&Date.now()-new Date(U).getTime()>48*60*60*1e3?{label:"Needs Boost",variant:"outline",color:"text-yellow-500",icon:e.jsx(xe,{className:"w-3 h-3 mr-1"})}:{label:"New",variant:"outline",color:"text-muted-foreground",icon:e.jsx(xe,{className:"w-3 h-3 mr-1"})}},ct=l=>{const y=l.viewCount+l.linkedInEngagement;return y>60?e.jsx(js,{className:"w-4 h-4 text-orange-500"}):l.published_to_platform&&y<10?e.jsx(Xe,{className:"w-4 h-4 text-yellow-500"}):null};return e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsxs("main",{className:"container mx-auto px-4 sm:px-6 py-8",children:[u&&e.jsxs("div",{className:"mb-12 space-y-6",children:[e.jsx(Ca,{}),e.jsx(Rt,{}),e.jsx(ka,{}),e.jsx(wa,{}),e.jsx(ba,{}),e.jsx(ya,{}),e.jsx(va,{})]}),u&&e.jsxs(q,{className:"mb-12 glass-effect",children:[e.jsxs(O,{children:[e.jsxs(K,{className:"flex items-center gap-2",children:[e.jsx(vt,{className:"w-5 h-5 text-primary"}),"Access Code Generator"]}),e.jsx(J,{children:"Generate invite codes for new users"})]}),e.jsxs(D,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(Je,{htmlFor:"code-label",className:"text-xs",children:"Label (optional)"}),e.jsx(he,{id:"code-label",placeholder:"e.g. LinkedIn prospect",value:A,onChange:l=>C(l.target.value)})]}),e.jsxs("div",{className:"w-full sm:w-32",children:[e.jsx(Je,{htmlFor:"code-duration",className:"text-xs",children:"Days"}),e.jsxs(es,{value:String(p),onValueChange:l=>w(Number(l)),children:[e.jsx(ss,{children:e.jsx(ts,{})}),e.jsxs(as,{children:[e.jsx(ee,{value:"7",children:"7 days"}),e.jsx(ee,{value:"14",children:"14 days"}),e.jsx(ee,{value:"30",children:"30 days"}),e.jsx(ee,{value:"90",children:"90 days"}),e.jsx(ee,{value:"365",children:"1 year"})]})]})]}),e.jsx("div",{className:"flex items-end",children:e.jsx(b,{onClick:ce,disabled:L,children:L?e.jsx(Q,{className:"h-4 w-4 animate-spin"}):"Generate"})})]}),x&&e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-primary/10 border border-primary/20",children:[e.jsx("code",{className:"text-lg font-mono font-bold tracking-widest flex-1",children:x}),e.jsx(b,{size:"sm",variant:"outline",onClick:()=>
71{navigator.clipboard.writeText(x),N.success("Code copied!")},children:e.jsx(Me,{className:"h-4 w-4"})})]}),B&&B.length>0&&e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-muted/50",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left p-2 font-medium",children:"Code"}),e.jsx("th",{className:"text-left p-2 font-medium",children:"Label"}),e.jsx("th",{className:"text-left p-2 font-medium",children:"Duration"}),e.jsx("th",{className:"text-left p-2 font-medium",children:"Status"})]})}),e.jsx("tbody",{children:B.map(l=>{const y=l.label&&(l.label.includes("DO NOT SHARE")||l.label.includes("META REVIEWER"));return e.jsxs("tr",{className:`border-t ${y?"bg-destructive/10":""}`,children:[e.jsx("td",{className:"p-2 font-mono text-xs",children:l.code}),e.jsxs("td",{className:"p-2 text-muted-foreground",children:[y&&e.jsx(Xe,{className:"inline h-3.5 w-3.5 text-destructive mr-1"}),l.label||"â"]}),e.jsxs("td",{className:"p-2",children:[l.duration_days,"d"]}),e.jsx("td",{className:"p-2",children:l.redeemed_by?e.jsx(F,{variant:"secondary",className:"text-xs",children:"Redeemed"}):e.jsx(F,{variant:"outline",className:"text-xs text-green-600",children:"Available"})})]},l.id)})})]})})]})]}),u&&e.jsx(_a,{}),nt&&z&&z.length>0&&e.jsxs(q,{className:"mb-8 glass-effect border-primary/20 bg-gradient-to-br from-primary/5 to-background relative",children:[e.jsx(b,{size:"icon",variant:"ghost",className:"absolute top-3 right-3 h-7 w-7 text-muted-foreground hover:text-foreground",onClick:it,children:e.jsx(Oe,{className:"h-4 w-4"})}),e.jsxs(O,{children:[e.jsxs(K,{className:"flex items-center gap-2 text-lg",children:[e.jsx(kt,{className:"w-5 h-5 text-primary"}),"Complete Your Setup"]}),e.jsx(J,{children:"Connect your accounts to unlock the full power of ThoughtForge"})]}),e.jsxs(D,{className:"space-y-3",children:[e.jsxs(Z,{to:"/profile",className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted/50 transition-colors group",children:[e.jsx(je,{className:"w-5 h-5 text-muted-foreground group-hover:text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Connect LinkedIn"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Publish posts & track analytics"})]})]}),e.jsxs(Z,{to:"/profile",className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted/50 transition-colors group",children:[e.jsx(Le,{className:"w-5 h-5 text-muted-foreground group-hover:text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Connect Twitter/X"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Publish threads & grow your audience"})]})]}),e.jsxs(Z,{to:"/profile",className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted/50 transition-colors group",children:[e.jsx(xe,{className:"w-5 h-5 text-muted-foreground group-hover:text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Connect your blog"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"WordPress or Shopify â cross-post articles automatically"})]})]})]})]}),e.jsx(Pa,{}),z&&z.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(ar,{}),e.jsx(_t,{type:"single",collapsible:!0,className:"mb-6",children:e.jsxs(Ct,{value:"details",className:"border rounded-lg bg-card/40",children:[e.jsx(St,{className:"px-4 hover:no-underline",children:e.jsx("span",{className:"text-sm font-medium",children:"Explore details"})}),e.jsx(qt,{className:"px-4 pb-4",children:e.jsxs("div",{className:"space-y-6 pt-2",children:[e.jsx(Za,{}),e.jsx(Oa,{}),e.jsxs("div",{className:"flex items-start justify-between gap-3 mb-2",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(Ia,{})}),e.jsx("div",{className:"hidden md:block pt-1",children:e.jsx(Ns,{})})]}),e.jsx("div",{className:"md:hidden mb-3",children:e.jsx(Ns,{})}),e.jsx(Aa,{}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4 mb-6",children:[e.jsx("div",{className:"lg:col-span-2",children:e.jsx(Ta,{hasPublishedPosts:Be>0})}),e.jsx(za,{})]}),e.jsx(Ya,{}),e.jsx(qa,{userId:s?.id})]})})]})}),e.jsx(Ha,{}),e.jsx("div",{id:"content-radar",className:"mb-12 scroll-mt-20",children:e.jsx(xa,{})}),e.jsxs("div",{className:"mb-12",children:[e.jsx(Ga,{}),e.jsx(ja,{})]})]}),z&&z.length===0&&!xs&&s&&e.jsx(Ps,{userId:s.id,postsPublishedCount:0,postsTotalCount:0}),z&&z.length>0&&s&&e.jsx(Ps,{userId:s.id,postsPublishedCount:Be,postsTotalCount:z.length}),z&&z.length>0&&e.jsxs("div",{className:"flex flex-col md:flex-row justify-between items-start md:items-center gap-4 sm:gap-6 mb-8",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl sm:text-4xl font-bold mb-2",children:"Your Articles"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage and edit your content"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(aa,{onOpenChange:l=>{l&&I()},children:[e.jsx(ra,{asChild:!0,children:e.jsxs(b,{variant:"outline",size:"icon",className:"relative","aria-label":"Ranking alerts",children:[e.jsx(ia,{className:"h-4 w-4"}),R.length>0&&e.jsx("span",{className:"absolute -top-1 -right-1 h-5 w-5 rounded-full bg-destructive text-destructive-foreground text-xs flex items-center justify-center",children:R.length})]})}),e.jsxs(na,{className:"w-80 p-0",align:"end",children:[e.jsx("div",{className:"p-3 border-b",children:e.jsx("h4",{className:"font-semibold text-sm",children:"Ranking Alerts"})}),e.jsx("div",{className:"max-h-80 overflow-y-auto",children:S&&S.length>0?S.map(l=>e.jsxs("div",{className:`p-3 border-b last:border-0 hover:bg-muted/50 cursor-pointer ${l.seen?"":"bg-primary/5"}`,onClick:()=>l.article_id&&n(`/editor/${l.article_id}?panel=seo`),children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[l.alert_type==="climb"||l.alert_type==="page_one"?e.jsx(st,{className:"h-4 w-4 text-green-500"}):l.alert_type==="drop"?e.jsx(tt,{className:"h-4 w-4 text-red-500"}):e.jsx(ge,{className:"h-4 w-4 text-blue-500"}),e.jsxs("span",{className:"text-sm font-medium truncate",children:[l.alert_type==="climb"&&`Climbed ${Math.abs(l.change_amount)} spots`,l.alert_type==="drop"&&`Dropped ${Math.abs(l.change_amount)} spots`,l.alert_type==="page_one"&&"Page 1!",l.alert_type==="new_ranking"&&"New ranking"]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:['"',l.query,'" â #',l.current_position]}),l.created_at&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:oe(new Date(l.created_at),{addSuffix:!0})})]},l.id)):e.jsx("div",{className:"p-6 text-center text-sm text-muted-foreground",children:"No ranking alerts yet. Connect Google Search Console to get started."})})]})]}),e.jsxs(b,{variant:"hero",size:"default",onClick:()=>n("/editor/new"),className:"group w-full sm:w-auto",children:[e.jsx(ne,{className:"w-4 h-4 sm:w-5 sm:h-5 mr-2"}),"New Article"]})]})]}),z&&z.length>0&&e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 sm:gap-4 mb-8",children:[e.jsxs(q,{className:"glass-effect",children:[e.jsx(O,{className:"pb-3",children:e.jsx(K,{className:"text-sm font-medium text-muted-foreground",children:"Total Articles"})}),e.jsx(D,{children:e.jsx("div",{className:"text-3xl font-bold",children:z?.length||0})})]}),e.jsxs(q,{className:"glass-effect",children:[e.jsx(O,{className:"pb-3",children:e.jsx(K,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(D,{children:e.jsx("div",{className:"text-3xl font-bold text-primary",children:Be})})]}),e.jsxs(q,{className:"glass-effect",children:[e.jsx(O,{className:"pb-3",children:e.jsx(K,{className:"text-sm font-medium text-muted-foreground",children:"Drafts"})}),e.jsx(D,{children:e.jsx("div",{className:"text-3xl font-bold text-muted-foreground",children:lt})})]}),e.jsxs(q,{className:"glass-effect",children:[e.jsx(O,{className:"pb-3",children:e.jsx(K,{className:"text-sm font-medium text-muted-foreground",children:"LinkedIn Posts"})}),e.jsx(D,{children:e.jsx("div",{className:"text-3xl font-bold text-blue-500",children:ot})})]})]}),e.jsx(Va,{posts:z}),e.jsx("div",{className:"mb-4 flex",children:e.jsx(Qa,{})}),z&&z.length>0&&e.jsx(Ma,{}),!d&&!u&&z&&z.length>=0&&e.jsx("div",{className:"mb-8",children:e.jsx(Sa,{variant:"card"})}),z&&z.length>0&&e.jsxs("div",{className:"mb-6 flex flex-col gap-3 sm:gap-4",children:[e.jsx($s,{value:o,onValueChange:l=>c(l),className:"w-full overflow-x-auto",children:e.jsxs(Fs,{className:"grid grid-cols-3 lg:grid-cols-6 w-full",children:[e.jsx(le,{value:"all",className:"text-xs sm:text-sm",children:"All"}),e.jsx(le,{value:"drafts",className:"text-xs sm:text-sm",children:"Drafts"}),e.jsx(le,{value:"platform",className:"text-xs sm:text-sm",children:"Platform"}),e.jsx(le,{value:"linkedin",className:"text-xs sm:text-sm",children:"LinkedIn"}),e.jsx(le,{value:"top",className:"text-xs sm:text-sm",children:"Top"}),e.jsx(le,{value:"attention",className:"text-xs sm:text-sm",children:"Needs work"})]})}),e.jsxs(es,{value:a,onValueChange:l=>m(l),children:[e.jsx(ss,{className:"w-full sm:w-[180px]",children:e.jsx(ts,{placeholder:"Sort by"})}),e.jsxs(as,{children:[e.jsx(ee,{value:"recent",children:"Recent"}),e.jsx(ee,{value:"views",children:"Most Views"}),e.jsx(ee,{value:"engagement",children:"Most Engagement"})]})]})]}
71),xs?e.jsx(At,{}):hs.length>0?e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6",children:hs.map(l=>e.jsxs(q,{className:"glass-effect hover:shadow-glow transition-smooth group relative",children:[e.jsxs("div",{className:"absolute top-4 right-4 z-10 opacity-0 group-hover:opacity-100 transition-opacity flex gap-2",children:[e.jsx(b,{size:"icon",variant:"secondary",className:"h-8 w-8",onClick:y=>{y.stopPropagation(),n(`/editor/${l.id}`)},children:e.jsx(ne,{className:"h-4 w-4"})}),l.published_to_platform&&$?.username&&e.jsxs(e.Fragment,{children:[e.jsx(b,{size:"icon",variant:"secondary",className:"h-8 w-8",onClick:y=>{y.stopPropagation(),window.open(`/user/${$.username}/${l.slug}`,"_blank")},title:"View published article",children:e.jsx(Ke,{className:"h-4 w-4"})}),e.jsx(b,{size:"icon",variant:"secondary",className:"h-8 w-8",onClick:y=>{y.stopPropagation(),te(l)},title:"Copy article link",children:e.jsx(Me,{className:"h-4 w-4"})}),e.jsx(ta,{baseUrl:`${window.location.origin}/${$.username}/${l.slug}`,defaultCampaign:l.slug,stopPropagation:!0,label:"Copy tagged share link (LinkedIn, Threadsâ¦)"}),e.jsx(b,{size:"icon",variant:"secondary",className:"h-8 w-8",disabled:T.isRunning&&G?.id===l.id,onClick:y=>{y.stopPropagation(),E(l)},title:"Make AI-Ready (rewrite for ChatGPT/Claude/Perplexity citations)",children:T.isRunning&&G?.id===l.id?e.jsx(Q,{className:"h-4 w-4 animate-spin"}):e.jsx(ds,{className:"h-4 w-4"})})]}),e.jsx(b,{size:"icon",variant:"secondary",className:"h-8 w-8",onClick:y=>{y.stopPropagation(),n(`/platform-analytics?article=${l.id}`)},children:e.jsx(Rs,{className:"h-4 w-4"})}),e.jsx(b,{size:"icon",variant:"destructive",className:"h-8 w-8",onClick:y=>{y.stopPropagation(),g({id:l.id,title:l.title})},children:e.jsx(Ge,{className:"h-4 w-4"})})]}),e.jsxs("div",{onClick:()=>n(`/editor/${l.id}`),className:"cursor-pointer",children:[l.featured_image_url&&e.jsx("div",{className:"aspect-video w-full overflow-hidden rounded-t-lg",children:e.jsx("img",{src:l.featured_image_url,alt:l.title,loading:"lazy",decoding:"async",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"})}),e.jsxs(O,{children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-2",children:[e.jsxs("div",{className:"flex gap-2 flex-wrap items-center",children:[e.jsx(F,{variant:l.status==="published"?"default":"secondary",children:l.status}),[{key:"platform",label:"TF",icon:xe,isDone:l.published_to_platform,isWip:l.status==="published"&&!l.published_to_platform},{key:"linkedin",label:"in",icon:je,isDone:!!l.linkedin_post_url,isWip:!!l.linkedin_transformed_content&&!l.linkedin_post_url},{key:"twitter",label:"ð",icon:Le,isDone:!!l.twitter_post_url,isWip:!!l.twitter_transformed_content&&!l.twitter_post_url},{key:"threads",label:"ð§µ",icon:null,isDone:!!l.threads_post_url,isWip:!!l.threads_transformed_content&&!l.threads_post_url},{key:"wordpress",label:"WP",icon:xe,isDone:!!l.wordpress_published_url,isWip:!1},{key:"shopify",label:"Shop",icon:Ft,isDone:!!l.shopify_published_url,isWip:!1}].filter(H=>H.isDone||H.isWip).map(H=>e.jsxs(F,{variant:"outline",className:`text-xs gap-1 ${H.isDone?"bg-green-500/15 text-green-700 border-green-500/40 dark:text-green-400":"bg-amber-500/10 text-amber-700 border-amber-500/30 dark:text-amber-400"}`,title:H.isDone?`Published to ${H.label}`:`Draft ready for ${H.label}`,children:[H.icon&&e.jsx(H.icon,{className:"w-2.5 h-2.5"}),!H.icon&&H.label,H.isDone?"â":"â"]},H.key)),(l.published_to_platform||l.linkedin_post_url)&&e.jsx(F,{variant:Ue(l).variant,className:Ue(l).color,children:Ue(l).label}),ct(l),l.status==="published"&&e.jsx(Da,{postId:l.id})]}),e.jsxs("div",{className:"flex items-center text-xs text-muted-foreground whitespace-nowrap",children:[e.jsx(os,{className:"w-3 h-3 mr-1"}),oe(new Date(l.updated_at),{addSuffix:!0})]})]}),e.jsx(K,{className:"line-clamp-2 group-hover:text-primary transition-smooth",children:l.title}),e.jsx(J,{className:"line-clamp-3",children:l.excerpt||(l.content?l.content.replace(/<[^>]*>/g,"").substring(0,150):"No content yet...")})]}),e.jsx(D,{className:"pt-0",children:e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground flex-wrap",children:[l.viewCount>0&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(We,{className:"w-4 h-4"}),e.jsx("span",{children:l.viewCount})]}),l.linkedInEngagement>0&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(je,{className:"w-4 h-4"}),e.jsx("span",{children:l.linkedInEngagement})]})]})})]})]},l.id))}):z&&z.length>0?e.jsx(q,{className:"glass-effect",children:e.jsxs(D,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(be,{className:"w-16 h-16 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-xl font-semibold mb-2",children:"No articles match this filter"}),e.jsx("p",{className:"text-muted-foreground mb-6 text-center max-w-md",children:"Try changing your filter or create a new article."}),e.jsx(b,{variant:"outline",onClick:()=>c("all"),children:"Clear Filters"})]})}):e.jsx(q,{className:"glass-effect",children:e.jsxs(D,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(be,{className:"w-16 h-16 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-xl font-semibold mb-2",children:"No articles yet"}),e.jsx("p",{className:"text-muted-foreground mb-6 text-center max-w-md",children:"Start your content journey by creating your first article. Your ideas deserve to be shared with the world."}),e.jsxs(b,{variant:"hero",onClick:()=>n("/editor/new"),children:[e.jsx(ne,{className:"w-4 h-4 mr-2"}),"Create Your First Article"]})]})})]}),e.jsx(Os,{open:!!h,onOpenChange:l=>!l&&g(null),children:e.jsxs(Ks,{children:[e.jsxs(Gs,{children:[e.jsxs(Ws,{children:['Delete "',h?.title,'"?']}),e.jsx(Bs,{children:"This will permanently delete this article and all associated data. This action cannot be undone."})]}),e.jsxs(Us,{children:[e.jsx(Vs,{children:"Cancel"}),e.jsx(Qs,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:()=>{h&&(de.mutate(h.id),g(null))},children:"Delete"})]})]})}),G&&e.jsx(Dt,{open:!!T.result,onOpenChange:l=>{l||(T.dismiss(),k(null))},articleTitle:G.title,originalContent:G.content,originalMeta:G.meta,result:T.result,isApplying:T.isApplying,onApply:async()=>{await T.apply()&&(k(null),i.invalidateQueries({queryKey:["dashboard-posts"]}),i.invalidateQueries({queryKey:["posts"]}))}})]})};export{Yr 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.