PageSourceSearch

https://stuartandrews.me/assets/AdminInsights-D-7RLH9N.js

js stuartandrews.me collected 2026-10-02 10:32:51 UTC 325,042 bytes, 30 lines download raw bytes

1import{r as h,j as e}from"./react-vendor-DHsc3z8R.js";import{c as Ta,u as Aa,b as La}from"./query-vendor-BpSM1h0G.js";import{c as Re,a as De,j as oe,B as ee,X as Ae,y as us,M as Da}from"./index-zHdis8yY.js";import{I as he}from"./input-D86cZEUo.js";import{B as ve}from"./badge-BMErch5M.js";import{D as st,a as at,b as ut,c as ht,d as At,e as mt}from"./dialog-C7idHVgq.js";import{S as ft,a as bt,b as wt,c as yt,d as Ee,e as Ia,f as Ea}from"./select-BeVb6aKY.js";import{A as Lt,g as rt}from"./articleTypes-BG-MYcQi.js";import{P as ss}from"./PageErrorBoundary-RmNLIGu0.js";import{A as pt}from"./arrow-left-JgCzxNqq.js";import{S as Dt}from"./search-N0Xs0rvp.js";import{L as Vt}from"./list-BsOcByus.js";import{L as $a}from"./layout-grid-BAiSHzd2.js";import{E as It}from"./eye-c9lYZIvq.js";import{M as Pa}from"./message-square-CFhbWAT7.js";import{L as Jt}from"./layers-CjzU_5pc.js";import{Z as Se}from"./zap-C_syKUsu.js";import{C as Yt}from"./chart-no-axes-column-Kvv-7F6D.js";import{B as Ks}from"./book-open-DPMNMq_z.js";import{C as Qt}from"./clock-BFoMnJIE.js";import{T as ze}from"./textarea-BsrzVG_D.js";import{T as hs,a as ms,b as Ve,c as Je}from"./tabs-CsfHzQR_.js";import{L as Ce}from"./label-qjGkmDrY.js";import{C as Ye,b as Qe,c as Xe,a as Ze,d as ot,e as Bt}from"./card-AZbWOk9M.js";import{C as jt}from"./checkbox-DF1ob9FD.js";import{R as Ma,a as _t}from"./radio-group-Dh1LPM39.js";import{S as Fa}from"./separator-F_hBsTyV.js";import{L as ie}from"./loader-circle-DxZ1IHlT.js";import{C as Te}from"./circle-check-B-zaIBbq.js";import{C as Ra}from"./chevron-down-BCRbrPcx.js";import{U as Oa}from"./user-DibzpjBr.js";import{H as ps}from"./history-DhuFnllV.js";import{F as nt}from"./file-text-BjKJQzre.js";import{C as Xt}from"./code-BZjyeWzq.js";import{C as Ha}from"./cloud-G700UWx-.js";import{I as Ba}from"./info-Cpo_KlRL.js";import{S as _a}from"./scroll-area-Uber-mke.js";import{D as za}from"./download-C8XXfVHM.js";import{R as Ue}from"./refresh-cw-Bj2pST-f.js";import{C as gs}from"./circle-alert-BKvLX5J3.js";import{c as tt}from"./registry-DnM1V7GL.js";import{a as me,S as Gs,F as xs,C as zt,b as fs,c as Wa,g as Nt,D as qa,L as Ua,d as Ka,e as Zt,f as kt,h as Wt}from"./AdminInsightsHelpers-DIHDc34a.js";/* empty css                     */import{H as Ga,G as Va,Z as Ja,_ as Ya,$ as Qa,N as Rt,m as Ke,K as Xa,L as Za,a0 as Et,T as as,p as Pe,P as er,c as tr,f as Be,S as sr,F as ar,M as Vs,a1 as it,a as rr,b as nr,u as ir,E as or}from"./index-PJoVzck_.js";import{s as lr,a as cr,b as dr}from"./index-CoNyIfKk.js";import{s as ur}from"./index-CLZ9MIj7.js";import{c as hr,t as mr,C as Js,f as pr,g as bs,a as gr,m as ws,b as ys,d as xr,e as vs,h as fr,i as br,j as wr,k as yr,l as vr,n as jr,o as Nr,s as kr}from"./index-D1Uaolmw.js";import{U as $t}from"./upload-D8yl8ueN.js";import{L as rs}from"./link-Bklju1ED.js";import{S as js,C as Cr,a as Sr,b as Tr,c as Ar,D as Lr,R as Dr,d as Ir,E as Er,e as $r,f as Pr,g as Mr,I as Fr}from"./ProseEditorDialogs-CNZ6Fe_4.js";import{B as Ns,I as ks}from"./italic-BZVwGhX8.js";import{U as Cs}from"./underline-CK86p3ny.js";import{S as Ss}from"./strikethrough-DcF7TXUS.js";import{T as Ts}from"./text-align-start-QoJZCiYy.js";import{L as As}from"./list-ordered-0SKPLiHI.js";import{Q as Ls}from"./quote-ClWNv_Wu.js";import{L as Tt}from"./link-2-Sty5dGhT.js";import{U as Rr}from"./undo-2-B6FnSiyt.js";import{R as Or}from"./redo-2-Zf4Iz130.js";import{I as Pt}from"./image-DoI_os45.js";import{T as Ys}from"./trash-2-DJIf7TdW.js";import{P as gt}from"./plus-Bh-cew8F.js";import{C as lt}from"./circle-check-big-DleXm_l7.js";import{T as es}from"./triangle-alert-DzmV-SIh.js";import{M as Hr,f as Br}from"./ModelPriceLine-QHA-w-0S.js";import{S as $e}from"./sparkles-DCgSGxw7.js";import{W as ct}from"./wand-sparkles-DHFKsCh0.js";import{T as Mt}from"./target-Ca5vOv0A.js";import{L as Ds}from"./lightbulb-D146hD3Q.js";import{S as xt}from"./send-DqsKC_ri.js";import{C as _r}from"./copy-CLmDbulq.js";import{s as zr}from"./scrollWithinPane-BO6j6lXO.js";import{E as _e}from"./external-link-CcWlngXT.js";import{C as Ct}from"./check-toxosa8q.js";import{C as Qs}from"./circle-DpFjhvB5.js";import{T as Wr}from"./trending-up-CyNlbGuN.js";import{H as Is}from"./headphones-DYjGXdbx.js";import{P as qr}from"./play-COEvH8wB.js";import{E as Xs}from"./eye-off-DUaPnKPV.js";import{S as Ur}from"./save-DtItu1Tc.js";import{G as Kr}from"./gauge-tcpm69SK.js";import{G as qt}from"./globe-BYAYA1n6.js";import{S as Gr}from"./StatusPill-ByttfFpw.js";import{C as Vr}from"./CountStrip-DuzUr4KA.js";import"./dropdown-menu-D7htail8.js";import{S as Es}from"./star-CfqVz9BN.js";import{P as Jr}from"./pencil-B6FVJQc7.js";import Yr from"./article-vendor-Cz4mVeUR.js";import{C as Qr}from"./chevron-right-OP-RSzSu.js";import{T as Xr}from"./tag-BWSN6V5z.js";import{S as Zr}from"./skip-forward-XEfxWlOW.js";import{M as en,a as tn}from"./minimize-2-BBNOP6Vd.js";import{A as sn}from"./arrow-right-ByJ_gr84.js";import"./ui-vendor-CSbCjZRx.js";import"./motion-vendor-BtpmimIC.js";import"./chevron-up-CeLdHqV9.js";import"./with-selector-DvP4baQS.js";const an=[["path",{d:"M4 20h16",key:"14thso"}],["path",{d:"m6 16 6-12 6 12",key:"1b4byz"}],["path",{d:"M8 12h8",key:"1wcyev"}]],rn=Re("baseline",an);const nn=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M12 12v6",key:"3ahymv"}],["path",{d:"m15 15-3-3-3 3",key:"15xj92"}]],$s=Re("file-up",nn);const on=[["path",{d:"m9 11-6 6v3h9l3-3",key:"1a3l36"}],["path",{d:"m22 12-4.6 4.6a2 2 0 0 1-2.8 0l-5.2-5.2a2 2 0 0 1 0-2.8L14 4",key:"14a9rk"}]],ln=Re("highlighter",on);const cn=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M9 21V9",key:"1oto5p"}]],dt=Re("panels-top-left",cn);const dn=[["path",{d:"M4 7V4h16v3",key:"9msm58"}],["path",{d:"M5 20h6",key:"1h6pxn"}],["path",{d:"M13 4 8 20",key:"kqq6aj"}],["path",{d:"m15 15 5 5",key:"me55sn"}],["path",{d:"m20 15-5 5",key:"11p7ol"}]],un=Re("remove-formatting",dn);const hn=[["path",{d:"m10.344 4.688 1.181-2.393a.53.53 0 0 1 .95 0l2.31 4.679a2.12 2.12 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.237 3.152",key:"19ctli"}],["path",{d:"m17.945 17.945.43 2.505a.53.53 0 0 1-.771.56l-4.618-2.428a2.12 2.12 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.12 2.12 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a8 8 0 0 0 .4-.099",key:"ptqqvy"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],mn=Re("star-off",hn);const pn=[["path",{d:"M21 5H3",key:"1fi0y6"}],["path",{d:"M17 12H7",key:"16if0g"}],["path",{d:"M19 19H5",key:"vjpgq2"}]],Ps=Re("text-align-center",pn);const gn=[["path",{d:"M21 5H3",key:"1fi0y6"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M21 19H7",key:"4cu937"}
1]],Ms=Re("text-align-end",gn);const xn=[["path",{d:"M3 5h18",key:"1u36vt"}],["path",{d:"M3 12h18",key:"1i2n21"}],["path",{d:"M3 19h18",key:"awlh7x"}]],fn=Re("text-align-justify",xn),bn=Object.freeze(Object.defineProperty({__proto__:null,Decoration:Ga,DecorationSet:Va,EditorView:Ja,__endComposition:Ya,__parseFromClipboard:Qa},Symbol.toStringTag,{value:"Module"})),Fs=["Leadership Frameworks","Case Studies","Quick Tips","Deep Dives","Opinion/POV"],Rs={"Leadership Frameworks":Ks,"Case Studies":Yt,"Quick Tips":Se,"Deep Dives":Jt,"Opinion/POV":Pa},wn={"Leadership Frameworks":"from-blue-600/20 to-indigo-600/20","Case Studies":"from-emerald-600/20 to-teal-600/20","Quick Tips":"from-amber-600/20 to-orange-600/20","Deep Dives":"from-purple-600/20 to-pink-600/20","Opinion/POV":"from-slate-600/20 to-secondary/20"};function yn({token:t,onClose:s,onEditArticle:a}){const{toast:n}=De(),i=Ta(),[m,j]=h.useState(""),[k,p]=h.useState("All"),[u,N]=h.useState(null),[P,x]=h.useState(null),[H,T]=h.useState("grid"),[A,L]=h.useState({title:"",slug:"",category:"Leadership Architecture"}),{data:E=[],isLoading:B,isError:U,error:c}=Aa({queryKey:["/api/admin/templates"],queryFn:async()=>{const o=await fetch("/api/admin/templates",{headers:{...oe()}});if(!o.ok)throw new Error("Failed to fetch templates");return o.json()}}),D=La({mutationFn:async o=>{const S=await fetch(`/api/admin/templates/${o.slug}/use`,{method:"POST",headers:{"Content-Type":"application/json",...oe()},body:JSON.stringify({title:o.title,slug:o.targetSlug,category:o.category})});if(!S.ok){const l=await S.json().catch(()=>({error:"Failed to create article"}));throw new Error(l.error||"Failed to create article")}return S.json()},onSuccess:o=>{i.invalidateQueries({queryKey:["/api/admin/articles"]}),n({title:"Article created successfully"}),x(null),a&&a(o.id)},onError:o=>{n({title:"Failed to create article",description:o.message,variant:"destructive"})}}),$=E.filter(o=>{const S=o.name.toLowerCase().includes(m.toLowerCase())||o.description.toLowerCase().includes(m.toLowerCase()),l=k==="All"||o.category===k;return S&&l}),F=Fs.reduce((o,S)=>{const l=$.filter(b=>b.category===S);return l.length>0&&(o[S]=l),o},{}),J=o=>{x(o),L({title:o.name,slug:rt(o.name),category:"Leadership Architecture"})},re=o=>{L(S=>({...S,title:o,slug:rt(o)}))},I=()=>{if(P){if(!A.title.trim()||!A.slug.trim()){n({title:"Title and slug are required",variant:"destructive"});return}D.mutate({slug:P.slug,title:A.title,targetSlug:A.slug,category:A.category})}};return e.jsx(ss,{pageName:"AdminTemplates",children:e.jsxs("div",{className:"flex flex-col h-full bg-background text-foreground",children:[e.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-border",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(ee,{variant:"ghost",size:"icon",onClick:s,className:"hover:bg-secondary",children:e.jsx(pt,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Article Templates"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Choose a pre-built structure to start writing faster"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 w-full max-w-md",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Dt,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(he,{"data-testid":"input-template-search",placeholder:"Search templates...",value:m,onChange:o=>j(o.target.value),className:"pl-9 bg-card border-border text-foreground focus:ring-ring/50"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border border-border p-0.5 bg-card",children:[e.jsx(ee,{"data-testid":"button-view-list",variant:"ghost",size:"icon",onClick:()=>T("list"),className:`w-8 h-8 ${H==="list"?"bg-accent-gold text-navy-deep hover:bg-accent-gold-light":"text-muted-foreground hover:text-navy-deep hover:bg-secondary"}`,title:"List view",children:e.jsx(Vt,{className:"w-4 h-4"})}),e.jsx(ee,{"data-testid":"button-view-grid",variant:"ghost",size:"icon",onClick:()=>T("grid"),className:`w-8 h-8 ${H==="grid"?"bg-accent-gold text-navy-deep hover:bg-accent-gold-light":"text-muted-foreground hover:text-navy-deep hover:bg-secondary"}`,title:"Grid view",children:e.jsx($a,{className:"w-4 h-4"})})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 p-4 px-6 overflow-x-auto no-scrollbar border-b border-border bg-card/50",children:[e.jsx(ee,{"data-testid":"button-category-all",variant:k==="All"?"default":"ghost",size:"sm",onClick:()=>p("All"),className:k==="All"?"bg-accent-gold text-navy-deep hover:bg-accent-gold-light":"text-muted-foreground hover:text-foreground hover:bg-secondary",children:"All Templates"}),Fs.map(o=>e.jsx(ee,{"data-testid":`button-category-${o.toLowerCase().replace(/\s+/g,"-")}`,variant:k===o?"default":"ghost",size:"sm",onClick:()=>p(o),className:k===o?"bg-accent-gold text-navy-deep hover:bg-accent-gold-light":"text-muted-foreground hover:text-foreground hover:bg-secondary",children:o},o))]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-6 space-y-10 custom-scrollbar",children:B?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:[1,2,3,4,5,6].map(o=>
1e.jsx("div",{className:"h-64 rounded-xl bg-card animate-pulse border border-border"},o))}):U?e.jsxs("div",{className:"flex flex-col items-center justify-center h-64 text-muted-foreground",children:[e.jsx(dt,{className:"w-12 h-12 mb-4 opacity-20"}),e.jsxs("p",{children:["Failed to load templates",c instanceof Error?`: ${c.message}`:""]})]}):Object.keys(F).length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-64 text-muted-foreground",children:[e.jsx(dt,{className:"w-12 h-12 mb-4 opacity-20"}),e.jsx("p",{children:"No templates found matching your criteria"})]}):H==="list"?e.jsx("div",{className:"overflow-x-auto rounded-xl border border-border",children:e.jsxs("table",{className:"w-full text-sm","data-testid":"table-templates",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border bg-card/50 text-left text-xs uppercase tracking-wider text-muted-foreground",children:[e.jsx("th",{className:"px-4 py-3 font-semibold",children:"Name"}),e.jsx("th",{className:"px-4 py-3 font-semibold",children:"Category"}),e.jsx("th",{className:"px-4 py-3 font-semibold",children:"Difficulty"}),e.jsx("th",{className:"px-4 py-3 font-semibold",children:"Blocks"}),e.jsx("th",{className:"px-4 py-3 font-semibold",children:"Read Time"}),e.jsx("th",{className:"px-4 py-3 font-semibold text-right",children:"Actions"})]})}),e.jsx("tbody",{children:$.map(o=>e.jsxs("tr",{"data-testid":`row-template-${o.id}`,className:"border-b border-border last:border-b-0 hover:bg-secondary/50 transition-colors",children:[e.jsxs("td",{className:"px-4 py-3",children:[e.jsx("div",{className:"font-semibold text-foreground",children:o.name}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-1",children:o.description})]}),e.jsx("td",{className:"px-4 py-3 text-muted-foreground",children:o.category}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(ve,{variant:"outline",className:"border-border text-muted-foreground text-[10px] uppercase",children:o.difficulty})}),e.jsx("td",{className:"px-4 py-3 text-muted-foreground",children:o.blockCount}),e.jsxs("td",{className:"px-4 py-3 text-muted-foreground",children:[o.estimatedReadTime,"m"]}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(ee,{"data-testid":`button-use-template-row-${o.id}`,size:"sm",onClick:()=>J(o),className:"bg-accent-gold hover:bg-accent-gold-light text-navy-deep font-semibold h-8",children:"Use"}),e.jsx(ee,{"data-testid":`button-preview-template-row-${o.id}`,variant:"ghost",size:"icon",onClick:()=>N(o),className:"w-8 h-8 text-muted-foreground hover:text-foreground hover:bg-secondary",children:e.jsx(It,{className:"w-4 h-4"})})]})})]},o.id))})]})}):Object.entries(F).map(([o,S])=>e.jsxs("section",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[(()=>{const l=Rs[o];return l?e.jsx(l,{className:"w-5 h-5 text-accent-gold"}):null})(),e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:o}),e.jsx(ve,{variant:"outline",className:"ml-2 border-border text-muted-foreground font-normal",children:S.length})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:S.map(l=>e.jsxs("div",{className:"group bg-card border border-border rounded-xl overflow-hidden hover:border-accent-gold/50 transition-all hover:shadow-2xl hover:shadow-accent-gold/10 flex flex-col",children:[e.jsxs("div",{className:`h-32 bg-gradient-to-br ${wn[l.category]} flex items-center justify-center relative overflow-hidden`,children:[e.jsx("div",{className:"absolute inset-0 opacity-10 flex flex-wrap gap-2 p-2 pointer-events-none",children:Array.from({length:20}).map((b,M)=>e.jsx("div",{className:"h-1 w-8 bg-white rounded-full"},M))}),e.jsx(dt,{className:"w-12 h-12 text-foreground/20 group-hover:scale-110 transition-transform duration-500"}),e.jsx("div",{className:"absolute top-3 right-3",children:e.jsx(ve,{variant:"outline",className:"bg-black/40 backdrop-blur-md border-white/10 text-foreground text-[10px] uppercase tracking-wider px-2 py-0",children:l.difficulty})})]}),e.jsxs("div",{className:"p-5 flex-1 flex flex-col",children:[e.jsx("h3",{className:"text-lg font-bold mb-1 group-hover:text-accent-gold transition-colors",children:l.name}),e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-4 flex-1",children:l.description}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground mb-5",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Jt,{className:"w-3.5 h-3.5 text-accent-gold"}),e.jsxs("span",{children:[l.blockCount," Blocks"]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Qt,{className:"w-3.5 h-3.5 text-info"}),e.jsxs("span",{children:[l.estimatedReadTime,"m Read"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ee,{"data-testid":`button-use-template-${l.id}`,onClick:()=>J(l),className:"flex-1 bg-accent-gold hover:bg-accent-gold-light text-navy-deep font-semibold h-9",children:"Use Template"}),e.jsx(ee,{"data-testid":`button-preview-template-${l.id}`,variant:"ghost",size:"icon",onClick:()=>N(l),className:"w-9 h-9 text-muted-foreground hover:text-foreground hover:bg-secondary",children:e.jsx(It,{className:"w-4 h-4"})})]})]})]},l.id))})]},o))}),e.jsx(st,{open:!!u,onOpenChange:o=>!o&&N(null),children:e.jsx(at,{className:"max-w-3xl bg-card border-border text-foreground max-h-[85vh] flex flex-col p-0 overflow-hidden",children:u&&e.jsxs(e.Fragment,{children:[e.jsxs(ut,{className:"p-6 border-b border-border shrink-0",children:[e.jsx("div",{className:"flex items-start justify-between gap-4",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[(()=>{const o=Rs[u.category];return o?e.jsx(o,{className:"w-4 h-4 text-accent-gold"}):null})(),e.jsx("span",{className:"text-xs uppercase tracking-widest text-accent-gold-ink font-bold",children:u.category})]}),e.jsx(ht,{className:"text-2xl font-bold",children:u.name}),e.jsx(At,{className:"text-muted-foreground text-base leading-relaxed",children:u.description})]})}),e.jsxs("div",{className:"flex items-center gap-6 mt-4 py-3 px-4 bg-secondary/50 rounded-lg border border-border/50",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-[10px] uppercase text-muted-foreground font-bold tracking-tighter",children:"Read Time"}),e.jsxs("div",{className:"flex items-center gap-1.5 text-sm font-semibold",children:[e.jsx(Qt,{className:"w-3.5 h-3.5 text-info"}),u.estimatedReadTime," Minutes"]})]}),e.jsx("div",{className:"w-px h-8 bg-secondary"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-[10px] uppercase text-muted-foreground font-bold tracking-tighter",children:"Content Depth"}),e.jsxs("div",{className:"flex items-center gap-1.5 text-sm font-semibold",children:[e.jsx(Jt,{className:"w-3.5 h-3.5 text-accent-gold"}),u.blockCount," Structural Blocks"]})]}),e.jsx("div",{className:"w-px h-8 bg-secondary"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-[10px] uppercase text-muted-foreground font-bold tracking-tighter",children:"Difficulty"}),e.jsx(ve,{className:"mt-0.5 bg-accent-gold/10 text-accent-gold-ink border-accent-gold/20 text-[10px] px-1.5 py-0 h-4",children:u.difficulty})]})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-6 space-y-4 custom-scrollbar bg-background/30",children:[e.jsxs("h4",{className:"text-sm font-bold text-muted-foreground uppercase tracking-widest mb-2 flex items-center gap-2",children:[e.jsx(Ks,{className:"w-4 h-4"}),"Structure Preview"]}),e.jsx("div",{className:"space-y-3",children:u.blocks.map((o,S)=>e.jsxs("div",{className:"flex gap-4 group",children:[e.jsxs("div",{className:"flex flex-col items-center",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-secondary border border-border flex items-center justify-center text-[10px] font-bold text-muted-foreground group-hover:border-accent-gold/50 group-hover:text-accent-gold-ink transition-colors",children:S+1}),S<u.blocks.length-1&&e.jsx("div",{className:"w-px flex-1 bg-secondary my-1 group-hover:bg-accent-gold/20 transition-colors"})]}),e.jsxs("div",{className:"flex-1 bg-card/80 border border-border rounded-lg p-3 group-hover:border-border group-hover:bg-secondary/50 transition-all",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-xs font-bold uppercase tracking-wider text-muted-foreground capitalize",children:o.type}),o.type==="heading"&&e.jsxs(ve,{variant:"outline",className:"text-[10px] h-4 border-border text-muted-foreground",children:["H",o.level]}),o.type==="callout"&&e.jsx(ve,{variant:"outline",className:"text-[10px] h-4 border-border text-muted-foreground capitalize",children:o.variant})]}),e.jsx("p",{className:"text-sm text-foreground line-clamp-2",children:"content"in o?o.content:"items"in o?`${o.items.length} items included...`:"description"in o?o.description:"Divider line"})]})]},S))})]}),e.jsxs(mt,{className:"p-4 border-t border-border shrink-0 bg-card",children:[e.jsx(ee,{variant:"ghost",onClick:()=>N(null),className:"text-muted-foreground hover:text-foreground hover:bg-secondary",children:"Cancel"}),e.jsx(ee,{"data-testid":"button-use-from-preview",onClick:()=>{const o=u;N(null),J(o)},className:"bg-accent-gold hover:bg-accent-gold-light text-navy-deep font-bold px-8",children:"Use This Template"})]})]})})}),e.jsx(st,{open:!!P,onOpenChange:o=>!o&&x(null),children:e.jsxs(at,{className:"bg-card border-border text-foreground sm:max-w-md",children:[e.jsxs(ut,{children:[e.jsxs(ht,{children:["Use Template: ",P?.name]}),e.jsx(At,{className:"text-muted-foreground",children:"Set the initial article details before continuing to the editor."})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-foreground",children:"Article Title"}),e.jsx(he,{"data-testid":"input-use-template-title",value:A.title,onChange:o=>re(o.target.value),placeholder:"Enter article title...",className:"bg-secondary border-border text-foreground focus:ring-ring/50"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-foreground",children:"URL Slug"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(he,{"data-testid":"input-use-template-slug",value:A.slug,onChange:o=>L({...A,slug:o.target.value}),placeholder:"article-slug",className:"bg-secondary border-border text-foreground focus:ring-ring/50 flex-1"})}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Auto-generated from title, must be unique."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium text-foreground",children:"Article Category"}),e.jsxs(ft,{value:A.category,onValueChange:o=>L({...A,category:o}),children:[e.jsx(bt,{className:"bg-secondary border-border text-foreground",children:e.jsx(wt,{placeholder:"Select category"})}),e.jsx(yt,{className:"bg-secondary border-border text-foreground",children:Lt.map(o=>e.jsx(Ee,{value:o,className:"hover:bg-secondary focus:bg-secondary",children:o},o))})]})]})]}),e.jsxs(mt,{children:[e.jsx(ee,{variant:"ghost",onClick:()=>x(null),className:"text-muted-foreground hover:text-foreground hover:bg-secondary",disabled:D.isPending,children:"Cancel"}),e.jsx(ee,{"data-testid":"button-confirm-use-template",onClick:I,disabled:D.isPending,className:"bg-accent-gold hover:bg-accent-gold-light text-navy-deep font-bold min-w-[120px]",children:D.isPending?"Creating...":"Create Article"})]})]})})]})})}function Ut(t){const s=t.trim();if(!s)return!1;try{const a=new URL(s);return a.protocol==="http:"||a.protocol==="https:"}catch{return!1}}async function Os(t,s,a){const n=await fetch(t,{...a,headers:{"Content-Type":"application/json",...oe(),...a?.headers||{}}});if(!n.ok){const i=await n.json().catch(()=>({error:"Request failed"}));throw new Error(i.error||"Request failed")}return n.json()}function vn({token:t,onClose:s,onImportComplete:a}){const{toast:n}=De(),[i,m]=h.useState({step:"input",type:"markdown",parsedArticles:[]}),[j,k]=h.useState(""),[p,u]=h.useState(""),[N,P]=h.useState(""),[x,H]=h.useState(""),[T,A]=h.useState("wordpress"),[L,E]=h.useState([]),[B,U]=h.useState(""),[c,D]=h.useState(null),$=h.useRef(null),F=async(I,o)=>{const S=I.target.files?.[0];if(!S)return;const l=new FileReader;l.onload=b=>{const M=b.target?.result;o==="markdown"?k(M):o==="html"?u(M):o==="xml"&&P(M)},l.readAsText(S)},J=async(I,o,S)=>{m(l=>({...l,step:"parsing",type:I}));try{const l=await Os("/api/admin/import/preview",t,{method:"POST",body:JSON.stringify({type:I,content:o,url:S})}),b=l.articles.map(M=>({...M,slug:rt(M.title),category:M.categories?.[0]&&Lt.includes(M.categories[0])?M.categories[0]:"Leadership Architecture",isSelected:!0}));E(b),m(M=>({...M,step:"preview",parsedArticles:l.articles}))}catch(l){n({title:"Parsing failed",description:l.message,variant:"destructive"}),m(b=>({...b,step:"input"}))}},re=async()=>{const I=L.filter(o=>o.isSelected);if(!I.length){n({title:"No articles selected",variant:"destructive"});return}m(o=>({...o,step:"importing"}));
1try{const o={articles:I.map(l=>({title:l.title,slug:l.slug,excerpt:l.excerpt,category:l.category,blocks:l.blocks,tags:l.tags,author:l.author,importedFrom:i.type,publishDate:l.publishDate}))},S=await Os("/api/admin/import/confirm",t,{method:"POST",body:JSON.stringify(o)});m(l=>({...l,step:"done",results:S})),n({title:"Import successful",description:`${S.created} articles created.`}),a()}catch(o){n({title:"Import failed",description:o.message,variant:"destructive"}),m(S=>({...S,step:"preview"}))}};return i.step==="parsing"||i.step==="importing"?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[60vh] space-y-4",children:[e.jsx(ie,{className:"w-12 h-12 text-accent-gold animate-spin"}),e.jsx("h2",{className:"text-xl font-semibold text-foreground",children:i.step==="parsing"?"Analyzing content...":"Creating articles..."}),e.jsx("p",{className:"text-muted-foreground",children:"Please wait a moment."})]}):i.step==="done"?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[60vh] space-y-6 text-center",children:[e.jsx("div",{className:"w-16 h-16 bg-success/10 border border-success/30 rounded-full flex items-center justify-center",children:e.jsx(Te,{className:"w-10 h-10 text-success-ink"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold text-foreground",children:"Import Complete!"}),e.jsxs("p",{className:"text-muted-foreground mt-2",children:["Successfully imported ",i.results?.created," articles as drafts."]})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx(ee,{variant:"outline",onClick:()=>{m({step:"input",type:"markdown",parsedArticles:[]}),k(""),u(""),P(""),H(""),E([])},children:"Import More"}),e.jsx(ee,{className:"bg-accent-gold hover:bg-accent-gold-light text-navy-deep",onClick:s,children:"View Articles"})]})]}):i.step==="preview"?e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto pb-12",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(ee,{variant:"ghost",size:"icon",onClick:()=>{L.length>0&&!window.confirm("Going back will discard your edits to this preview. Continue?")||m(I=>({...I,step:"input"}))},children:e.jsx(pt,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold text-foreground",children:"Preview Import"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Review and edit metadata before creating drafts"})]})]}),e.jsxs(ee,{className:"bg-accent-gold hover:bg-accent-gold-light text-navy-deep font-bold",onClick:()=>{const I=L.filter(o=>o.isSelected).length;window.confirm(`Create ${I} draft article${I===1?"":"s"}? This cannot be undone.`)&&re()},children:["Create ",L.filter(I=>I.isSelected).length," Drafts"]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-3 text-sm text-muted-foreground",children:[e.jsxs("span",{children:[e.jsx("span",{className:"text-foreground font-semibold",children:L.length})," parsed"]}),e.jsx("span",{"aria-hidden":"true",children:"·"}),e.jsxs("span",{children:[e.jsx("span",{className:"text-foreground font-semibold",children:L.filter(I=>I.isSelected).length})," selected"]})]}),e.jsxs("div",{className:"relative w-full max-w-xs",children:[e.jsx(Dt,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(he,{value:B,onChange:I=>U(I.target.value),placeholder:"Search articles by title...",className:"bg-secondary border-border text-foreground pl-9"})]})]}),e.jsx("div",{className:"space-y-3",children:L.map((I,o)=>({article:I,idx:o})).filter(({article:I})=>I.title.toLowerCase().includes(B.toLowerCase())).map(({article:I,idx:o})=>e.jsxs(Ye,{className:"bg-card border-border overflow-hidden",children:[e.jsxs(Qe,{className:"bg-secondary/50 py-3 flex flex-row items-center justify-between space-y-0 cursor-pointer",onClick:()=>D(S=>S===o?null:o),children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx(jt,{checked:I.isSelected,onClick:S=>S.stopPropagation(),onCheckedChange:S=>{const l=[...L];l[o].isSelected=!!S,E(l)}}),e.jsx(Xe,{className:"text-lg font-medium text-foreground truncate max-w-md",children:I.title}),e.jsx(ve,{variant:"outline",className:"text-muted-foreground border-border shrink-0",children:I.category})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsxs(ve,{variant:"outline",className:"text-muted-foreground border-border",children:[I.blocks.length," blocks detected"]}),!I.isSelected&&e.jsx(ve,{variant:"secondary",className:"bg-secondary text-muted-foreground border-border",children:"Excluded"}),e.jsx(Ra,{className:`w-4 h-4 text-muted-foreground transition-transform ${c===o?"rotate-180":""}`})]})]}),c===o&&e.jsxs(Ze,{className:"p-6 space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ce,{className:"text-muted-foreground",children:"Article Title"}),e.jsx(he,{value:I.title,onChange:S=>{const l=[...L];l[o].title=S.target.value,l[o].slug=rt(S.target.value),E(l)},className:"bg-secondary border-border text-foreground"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ce,{className:"text-muted-foreground",children:"URL Slug"}),e.jsx(he,{value:I.slug,onChange:S=>{const l=[...L];l[o].slug=S.target.value,E(l)},className:"bg-secondary border-border text-foreground"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ce,{className:"text-muted-foreground",children:"Category"}),e.jsxs(ft,{value:I.category,onValueChange:S=>{const l=[...L];l[o].category=S,E(l)},children:[e.jsx(bt,{className:"bg-secondary border-border text-foreground",children:e.jsx(wt,{})}),e.jsx(yt,{className:"bg-secondary border-border text-foreground",children:Lt.map(S=>e.jsx(Ee,{value:S,children:S},S))})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ce,{className:"text-muted-foreground",children:"Excerpt"}),e.jsx(ze,{value:I.excerpt,onChange:S=>{const l=[...L];l[o].excerpt=S.target.value,E(l)},className:"bg-secondary border-border text-foreground min-h-[120px] resize-none"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ce,{className:"text-muted-foreground",children:"Author"}),e.jsxs("div",{className:"relative",children:[e.jsx(Oa,{className:"absolute left-3 top-3 w-4 h-4 text-muted-foreground"}),e.jsx(he,{value:I.author||"Stuart Andrews",readOnly:!0,className:"bg-secondary/50 border-border text-muted-foreground pl-10"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ce,{className:"text-muted-foreground",children:"Date"}),e.jsxs("div",{className:"relative",children:[e.jsx(ps,{className:"absolute left-3 top-3 w-4 h-4 text-muted-foreground"}),e.jsx(he,{value:I.publishDate?new Date(I.publishDate).toLocaleDateString():"Draft",readOnly:!0,className:"bg-secondary/50 border-border text-muted-foreground pl-10"})]})]})]})]})]}),e.jsx(Fa,{className:"bg-secondary"}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(Ce,{className:"text-muted-foreground block",children:"Content Blocks Preview"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:I.blocks.map((S,l)=>e.jsxs(ve,{variant:"secondary",className:"bg-secondary text-foreground border-border px-2 py-1 flex items-center gap-2",children:[S.type==="paragraph"&&e.jsx(nt,{className:"w-3 h-3 text-info"}),S.type==="heading"&&e.jsxs("span",{className:"text-[10px] font-bold text-accent-gold-ink",children:["H",S.level]}),S.type==="image"&&e.jsx(dt,{className:"w-3 h-3 text-pink-700"}),S.type==="bulletList"&&e.jsx("span",{className:"text-[10px] text-purple-700",children:"•"}),S.type==="numberedList"&&e.jsx("span",{className:"text-[10px] text-purple-700",children:"1."}),S.type==="blockquote"&&e.jsx("span",{className:"text-[10px] text-success",children:'"'}),S.type==="divider"&&e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"—"}
1),e.jsx("span",{className:"capitalize text-[11px]",children:S.type})]},l))})]})]})]},o))})]}):e.jsx(ss,{pageName:"AdminImport",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-8 pb-12",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(ee,{variant:"ghost",size:"icon",onClick:s,className:"text-muted-foreground hover:text-foreground shrink-0",children:e.jsx(pt,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold text-foreground",children:"Import Articles"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Choose a source to import your leadership content from"})]})]}),e.jsxs(hs,{defaultValue:"markdown",className:"w-full",onValueChange:I=>m(o=>({...o,type:I})),children:[e.jsxs(ms,{className:"grid w-full grid-cols-4 bg-card border border-border h-auto p-1",children:[e.jsx(Ve,{value:"markdown",className:"data-[state=active]:bg-accent-gold data-[state=active]:text-navy-deep py-2.5",children:e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsx(Xt,{className:"w-4 h-4"}),e.jsx("span",{className:"text-xs",children:"Markdown"})]})}),e.jsx(Ve,{value:"cloud",className:"data-[state=active]:bg-accent-gold data-[state=active]:text-navy-deep py-2.5",children:e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsx(Ha,{className:"w-4 h-4"}),e.jsx("span",{className:"text-xs",children:"Cloud Docs"})]})}),e.jsx(Ve,{value:"xml",className:"data-[state=active]:bg-accent-gold data-[state=active]:text-navy-deep py-2.5",children:e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsx(ps,{className:"w-4 h-4"}),e.jsx("span",{className:"text-xs",children:"XML / RSS"})]})}),e.jsx(Ve,{value:"html",className:"data-[state=active]:bg-accent-gold data-[state=active]:text-navy-deep py-2.5",children:e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsx(nt,{className:"w-4 h-4"}),e.jsx("span",{className:"text-xs",children:"HTML"})]})})]}),e.jsxs("div",{className:"mt-8",children:[e.jsx(Je,{value:"markdown",className:"space-y-6",children:e.jsxs(Ye,{className:"bg-card border-border",children:[e.jsxs(Qe,{children:[e.jsx(Xe,{className:"text-foreground",children:"Import from Markdown"}),e.jsx(ot,{className:"text-muted-foreground",children:"Upload a .md file or paste your markdown content directly below."})]}),e.jsxs(Ze,{className:"space-y-4",children:[e.jsxs("div",{className:"border-2 border-dashed border-border rounded-lg p-8 text-center hover:border-accent-gold/50 transition-colors cursor-pointer group",onClick:()=>$.current?.click(),children:[e.jsx("input",{type:"file",accept:".md,.markdown",className:"hidden",ref:$,onChange:I=>F(I,"markdown")}),e.jsx($s,{className:"w-10 h-10 text-muted-foreground group-hover:text-accent-gold mx-auto mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground group-hover:text-foreground",children:"Click to upload .md or .markdown file"})]}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("span",{className:"w-full border-t border-border"})}),e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:"bg-card px-2 text-muted-foreground",children:"Or paste content"})})]}),e.jsx(ze,{placeholder:"# Article Title\\n\\nYour content here...",className:"bg-secondary border-border text-foreground min-h-[300px] font-mono text-sm",value:j,onChange:I=>k(I.target.value)})]}),e.jsxs(Bt,{className:"flex justify-between border-t border-border pt-6",children:[e.jsx("div",{className:"flex items-center gap-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(jt,{id:"md-sections",defaultChecked:!0}),e.jsx("label",{htmlFor:"md-sections",className:"text-xs text-muted-foreground cursor-pointer",children:"Convert headings to sections"})]})}),e.jsx(ee,{className:"bg-accent-gold hover:bg-accent-gold-light text-navy-deep font-bold",disabled:!j.trim(),onClick:()=>J("markdown",j),children:"Preview Import"})]})]})}),e.jsx(Je,{value:"cloud",className:"space-y-6",children:e.jsxs(hs,{defaultValue:"google",className:"w-full",children:[e.jsxs(m
1s,{className:"bg-secondary/50 p-1 mb-6",children:[e.jsx(Ve,{value:"google",className:"data-[state=active]:bg-secondary",children:"Google Docs"}),e.jsx(Ve,{value:"microsoft",className:"data-[state=active]:bg-secondary",children:"Microsoft OneDrive / SharePoint"})]}),e.jsx(Je,{value:"google",className:"space-y-4",children:e.jsxs(Ye,{className:"bg-card border-border",children:[e.jsxs(Qe,{children:[e.jsx(Xe,{className:"text-foreground",children:"Import from Google Docs"}),e.jsx(ot,{className:"text-muted-foreground",children:"Import content directly from a Google Doc using its URL."})]}),e.jsxs(Ze,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ce,{className:"text-foreground",children:"Google Doc URL"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(he,{placeholder:"https://docs.google.com/document/d/...",className:"bg-secondary border-border text-foreground",value:x,onChange:I=>H(I.target.value)}),e.jsx(ee,{className:"bg-accent-gold hover:bg-accent-gold-light text-navy-deep font-bold",disabled:!x.includes("docs.google.com"),onClick:()=>J("google-docs",void 0,x),children:"Import"})]})]}),e.jsxs("div",{className:"bg-warning/5 border border-warning/20 rounded-lg p-4 flex gap-3",children:[e.jsx(Ba,{className:"w-5 h-5 text-warning shrink-0"}),e.jsxs("p",{className:"text-xs text-warning-ink/80 leading-relaxed",children:[e.jsx("strong",{children:"Important:"})," Ensure your document sharing settings are set to",e.jsx("span",{className:"font-bold underline ml-1",children:'"Anyone with the link can view"'}),"for the importer to access the content."]})]})]})]})}),e.jsx(Je,{value:"microsoft",className:"space-y-4",children:e.jsxs(Ye,{className:"bg-card border-border",children:[e.jsxs(Qe,{children:[e.jsx(Xe,{className:"text-foreground",children:"Import from OneDrive / SharePoint"}),e.jsx(ot,{className:"text-muted-foreground",children:"Import from Microsoft 365 cloud storage."})]}),e.jsx(Ze,{className:"space-y-6",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ce,{className:"text-foreground",children:"Share Link URL"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(he,{placeholder:"https://1drv.ms/w/s!...",className:"bg-secondary border-border text-foreground",value:x,onChange:I=>H(I.target.value)}),e.jsx(ee,{className:"bg-accent-gold hover:bg-accent-gold-light text-navy-deep font-bold",disabled:!Ut(x),onClick:()=>J("microsoft",void 0,x),children:"Import"})]})]})})]})})]})}),e.jsx(Je,{value:"xml",className:"space-y-6",children:e.jsxs(Ye,{className:"bg-card border-border",children:[e.jsxs(Qe,{children:[e.jsx(Xe,{className:"text-foreground",children:"Import from XML / RSS"}),e.jsx(ot,{className:"text-muted-foreground",children:"Bulk import articles from WordPress exports, RSS feeds, or generic XML."})]}),e.jsxs(Ze,{className:"space-y-6",children:[e.jsxs(Ma,{defaultValue:"wordpress",className:"flex gap-6",onValueChange:I=>A(I),children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(_t,{value:"wordpress",id:"xml-wp"}),e.jsx(Ce,{htmlFor:"xml-wp",className:"text-foreground",children:"WordPress Export"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(_t,{value:"rss",id:"xml-rss"}),e.jsx(Ce,{htmlFor:"xml-rss",className:"text-foreground",children:"RSS Feed URL"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(_t,{value:"generic",id:"xml-gen"}),e.jsx(Ce,{htmlFor:"xml-gen",className:"text-foreground",children:"Generic XML"})]})]}),T==="rss"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ce,{className:"text-foreground",children:"RSS Feed URL"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(he,{placeholder:"https://example.com/feed",className:"bg-secondary border-border text-foreground",value:x,onChange:I=>H(I.target.value)}),e.jsx(ee,{className:"bg-accent-gold hover:bg-accent-gold-light text-navy-deep font-bold",disabled:!Ut(x),onClick:async()=>{if(!Ut(x)){n({title:"Invalid RSS feed URL",description:"Enter a valid http:// or https:// URL.",variant:"destructive"});return}m(I=>({...I,step:"parsing"}));try{const o=await(await fetch(x)).text();J("xml",o)}
1catch(I){n({title:"Failed to fetch RSS",description:I.message,variant:"destructive"}),m(o=>({...o,step:"input"}))}},children:"Parse Feed"})]})]}):e.jsxs("div",{className:"border-2 border-dashed border-border rounded-lg p-12 text-center hover:border-accent-gold/50 transition-colors cursor-pointer group",onClick:()=>$.current?.click(),children:[e.jsx("input",{type:"file",accept:".xml",className:"hidden",ref:$,onChange:I=>F(I,"xml")}),e.jsx($s,{className:"w-12 h-12 text-muted-foreground group-hover:text-accent-gold mx-auto mb-4"}),e.jsx("p",{className:"text-foreground font-medium",children:N?"File loaded: "+N.slice(0,30)+"...":"Click to upload XML file"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Maximum file size: 50MB"})]})]}),e.jsx(Bt,{className:"flex justify-end border-t border-border pt-6",children:T!=="rss"&&e.jsx(ee,{className:"bg-accent-gold hover:bg-accent-gold-light text-navy-deep font-bold",disabled:!N.trim(),onClick:()=>J("xml",N),children:"Preview Import"})})]})}),e.jsx(Je,{value:"html",className:"space-y-6",children:e.jsxs(Ye,{className:"bg-card border-border",children:[e.jsxs(Qe,{children:[e.jsx(Xe,{className:"text-foreground",children:"Import from HTML"}),e.jsx(ot,{className:"text-muted-foreground",children:"Paste raw HTML content to convert it into structured article blocks."})]}),e.jsx(Ze,{className:"space-y-4",children:e.jsx(ze,{placeholder:"<article>\\n  <h1>Title</h1>\\n  <p>Content...</p>\\n</article>",className:"bg-secondary border-border text-foreground min-h-[400px] font-mono text-sm",value:p,onChange:I=>u(I.target.value)})}),e.jsxs(Bt,{className:"flex justify-between border-t border-border pt-6",children:[e.jsxs("div",{className:"flex gap-4",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(jt,{id:"html-clean",defaultChecked:!0}),e.jsx("label",{htmlFor:"html-clean",className:"text-xs text-muted-foreground cursor-pointer",children:"Clean scripts/styles"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(jt,{id:"html-inline",defaultChecked:!0}),e.jsx("label",{htmlFor:"html-inline",className:"text-xs text-muted-foreground cursor-pointer",children:"Strip inline styles"})]})]}),e.jsx(ee,{className:"bg-accent-gold hover:bg-accent-gold-light text-navy-deep font-bold",disabled:!p.trim(),onClick:()=>J("html",p),children:"Preview Import"})]})]})})]})]})]})})}const Fe=[{slug:"what-factors-create-a-positive-workplace-culture",h1:"What Factors Create A Positive Workplace Culture?",metaTitle:"Creating a Positive Workplace Culture | Key Factors",metaDescription:"Learn the key factors for creating a positive workplace culture with Stuart Andrews' expert tips for fostering a thriving team environment.",url:"https://www.stuartandrews.me/blog/what-factors-create-a-positive-workplace-culture/"},{slug:"how-to-manage-conflict-through-executive-coaching",h1:"How to Manage Conflict Through Executive Coaching",metaTitle:"Mastering Conflict Management Through Executive Coaching",metaDescription:"Executive coaching has emerged as one of the most powerful tools for developing conflict management capabilities in leaders.",url:"https://www.stuartandrews.me/blog/how-to-manage-conflict-through-executive-coaching/"},{slug:"hybrid-is-the-future-how-to-lead-a-hybrid-workforce",h1:"Hybrid is the Future - How to Lead a Hybrid Workforce?",metaTitle:"Hybrid is the Future - How to Lead a Hybrid Workforce?",metaDescription:"Learn how to lead a hybrid workforce effectively with Stuart Andrews' expert insights and strategies for the future of work.",url:"https://www.stuartandrews.me/blog/hybrid-is-the-future-how-to-lead-a-hybrid-workforce/"},{slug:"the-five-c-s-of-effective-leadership-in-a-hybrid-world",h1:"The Five C's Of Effective Leadership In A Hybrid World",metaTitle:"The Five C's of Effective Leadership in a Hybrid World",metaDescription:"Learn the five Cs of effective leadership for the hybrid workplace with insights from Stuart Andrews to strengthen unity focus and long term success today wide",url:"https://www.stuartandrews.me/blog/the-five-c-s-of-effective-leadership-in-a-hybrid-world/"},{slug:"how-to-build-trust-with-your-team-and-leadership",h1:"How to Build Trust With Your Team and Leadership",metaTitle:"How to Build Trust With Your Team and Leadership",metaDescription:"Learn how to build trust with your team and leadership using clear communication accountability and consistent actions that strengthen performance and culture up",url:"https://www.stuartandrews.me/blog/how-to-build-trust-with-your-team-and-leadership/"},{slug:"5-reasons-leadership-coaching-can-boost-your-business",h1:"5 Reasons Leadership Coaching Can Boost Your Business",metaTitle:"5 Reasons Leadership Coaching Can Boost Your Business",metaDescription:"Boost business performance with leadership coaching. Discover 5 key reasons leadership coaching drives growth, clarity, team alignment and stronger results.",url:"https://www.stuartandrews.me/blog/5-reasons-leadership-coaching-can-boost-your-business/"},{slug:"mastering-emotional-intelligence-for-effective-leadership",h1:"Mastering Emotional Intelligence for Effective Leadership",metaTitle:"Mastering Emotional Intelligence for Effective Leadership",metaDescription:"Develop emotional intelligence for effective leadership with Stuart Andrews' insights, helping leaders connect, inspire, and lead with empathy.",url:"https://www.stuartandrews.me/blog/mastering-emotional-intelligence-for-effective-leadership/"},{slug:"adapting-to-change-the-art-of-leadership",h1:"Adapting To Change: The Art Of Leadership",metaTitle:"Adapting to Change | The Art of Leadership",metaDescription:"Explore how effective leaders adapt to change, build resilience, and drive success with strategic leadership insights for thriving in evolving business environments.",url:"https://www.stuartandrews.me/blog/adapting-to-change-the-art-of-leadership/"},{slug:"stop-making-these-6-mistakes-when-hiring-a-business-coach",h1:"Stop Making These 6 Mistakes When Hiring a Business Coach",metaTitle:"Avoid These 6 Mistakes When Hiring a Business Coach",metaDescription:"Avoid common pitfalls when hiring a business coach with Stuart Andrews' guide to selecting the right fit for your leadership needs.",url:"https://www.stuartandrews.me/blog/stop-making-these-6-mistakes-when-hiring-a-business-coach/"},{slug:"how-to-improve-business-performance-through-employee-experience",h1:"How to Improve Business Performance Through Employee Experience",metaTitle:"Boost Business Performance Through Employee Experience",metaDescription:"Improve business performance by enhancing employee experience with Stuart Andrews' actionable insights for creating a motivated 
1workforce.",url:"https://www.stuartandrews.me/blog/how-to-improve-business-performance-through-employee-experience/"},{slug:"four-tips-to-drive-high-performance-culture",h1:"Four Tips to Drive High Performance Culture",metaTitle:"Four Tips to Drive a High-Performance Culture",metaDescription:"Create a high-performance culture with Stuart Andrews' four essential tips to inspire and sustain exceptional team results.",url:"https://www.stuartandrews.me/blog/four-tips-to-drive-high-performance-culture/"},{slug:"definition-of-ethical-challenges-in-workplace",h1:"Definition of Ethical Challenges in Workplace",metaTitle:"Definition of Ethical Challenges in Workplace",metaDescription:"Learn the definition of ethical challenges in the workplace, why they arise, common examples, and how organisations manage them through ethical leadership info.",url:"https://www.stuartandrews.me/blog/definition-of-ethical-challenges-in-workplace/"},{slug:"how-much-do-executive-coaches-charge-in-sydney",h1:"How Much Do Executive Coaches Charge in Sydney?",metaTitle:"How Much Do Executive Coaches Charge in Sydney?",metaDescription:"Discover executive coaching fees in Sydney, typical price ranges, factors influencing costs, and how to choose the right executive coach for your goals.",url:"https://www.stuartandrews.me/blog/how-much-do-executive-coaches-charge-in-sydney/"},{slug:"ten-tips-to-avoid-distractions-and-become-a-more-effective-leader",h1:"Ten Tips To Avoid Distractions And Become A More Effective Leader",metaTitle:"10 Tips to Avoid Distractions and Boost Leadership Effectiveness",metaDescription:"Discover 10 actionable tips from Stuart Andrews to stay focused and boost your leadership effectiveness in any environment.",url:"https://www.stuartandrews.me/blog/ten-tips-to-avoid-distractions-and-become-a-more-effective-leader/"},{slug:"how-leaders-can-avoid-analysis-paralysis-in-a-constantly-changing-world",h1:"How Leaders can avoid Analysis Paralysis in a Constantly Changing World",metaTitle:"How Leaders Can Avoid Analysis Paralysis - Stuart Andrews",metaDescription:"Learn how to overcome analysis paralysis with Stuart Andrews' strategies for decisive leadership and effective decision-making.",url:"https://www.stuartandrews.me/blog/how-leaders-can-avoid-analysis-paralysis-in-a-constantly-changing-world/"},{slug:"what-does-an-executive-leadership-coach-do",h1:"What Does an Executive Leadership Coach Do?",metaTitle:"What Does an Executive Leadership Coach Do?",metaDescription:"An executive leadership coach supports senior leaders with strategy, decision making, behaviour change, and capability development for lasting impact.",url:"https://www.stuartandrews.me/blog/what-does-an-executive-leadership-coach-do/"},{slug:"how-the-best-managers-find-and-develop-talent",h1:"How the Best Managers Find and Develop Talent",metaTitle:"How the Best Managers Find and Develop Talent",metaDescription:"Discover how the best managers identify potential, develop talent, and build high-performing teams that drive growth, retention, and long term business success.",url:"https://www.stuartandrews.me/blog/how-the-best-managers-find-and-develop-talent/"},{slug:"the-silent-killer-of-growth",h1:"The Silent Killer of Growth",metaTitle:"The Silent Killer of Growth",metaDescription:"The challenges of rapid business growth",url:"https://www.stuartandrews.me/blog/the-silent-killer-of-growth/"},{slug:"what-are-the-capabilities-influenced-by-contextual-leadership",h1:"What Are the Capabilities Influenced by Contextual Leadership?",metaTitle:"What Are the Capabilities Influenced by Contextual Leadership?",metaDescription:"Contextual leadership builds adaptability, strategic thinking, sound decision making, collaboration, and resilience to lead effectively in changing environments.",url:"https://www.stuartandrews.me/blog/what-are-the-capabilities-influenced-by-contextual-leadership/"},{slug:"top-5-tough-questions-executive-leaders-are-being-asked",h1:"Top 5 Tough Questions Executive Leaders Are Being Asked",metaTitle:"Top 5 Tough Questions Executive Leaders Face Today",metaDescription:"Discover the top five tough questions that executive leaders face today, with Stuart Andrews providing expert guidance on how to address them.",url:"https://www.stuartandrews.me/blog/top-5-tough-questions-executive-leaders-are-being-asked/"},{slug:"how-nursing-teams-can-improve-leadership-capability-skills",h1:"How Nursing Teams Can Improve Leadership Capability Skills",metaTitle:"How Nursing Teams Can Improve Leadership Capability Skills",metaDescription:"Learn how nursing teams can build leadership capability skills through daily practice, structured frameworks, coaching, and real-world clinical leadership.",url:"https://www.stuartandrews.me/blog/how-nursing-teams-can-improve-leadership-capability-skills/"},{slug:"a-guide-on-how-you-can-succeed-as-a-c-level-executive",h1:"A Guide on How You Can Succeed as a C-Level Executive",metaTitle:"A Guide to Succeeding as a C-Level Executive",metaDescription:"Unlock proven strategies to succeed as a C-level executive, enhance leadership capability, drive performance and lead high-impact teams with expert insights and clarity.",url:"https://www.stuartandrews.me/blog/a-guide-on-how-you-can-succeed-as-a-c-level-executive/"},{slug:"what-is-a-leadership-capability-framework",h1:"What Is A Leadership Capability Framework",metaTitle:"What Is a Leadership Capability Framework in Organisations",metaDescription:"Learn what a leadership capability framework is, why it matters, and how it enables consistent, scalable leadership across organisations.",url:"https://www.stuartandrews.me/blog/what-is-a-leadership-capability-framework/"},{slug:"strategies-for-successful-leadership-succession-planning",h1:"Strategies for Successful Leadership Succession Planning",metaTitle:"Strategies for Successful Leadership Succession Planning",metaDescription:"Learn how to build a robust leadership succession plan using capability frameworks, evidence-based assessment, and structured leadership handovers.",url:"https://www.stuartandrews.me/blog/strategies-for-successful-leadership-succession-planning/"},{slug:"what-is-executive-leadership-in-business",h1:"What Is Executive Leadership in Business?",metaTitle:"What Is Executive Leadership in Business?",metaDescription:"Learn what executive leadership in business means, why it matters, and how strong executive leaders drive strategy, performance, and long term success.",url:"https://www.stuartandrews.me/blog/what-is-executive-leadership-in-business/"},{slug:"the-importance-of-training-new-leaders-and-how-to-do-so",h1:"The Importance of Training New Leaders and How to Do So",metaTitle:"The Importance of Training New Leaders in Organizations",metaDescription:"Training new leaders builds confidence, improves decision making, strengthens teams, and ensures long term organisational growth and leadership continuity.",url:"https://www.stuartandrews.me/blog/the-importance-of-training-new-leaders-and-how-to-do-so/"}
1,{slug:"a-comprehensive-guide-to-leadership-capability-architecture",h1:"A Comprehensive Guide to Leadership Capability Architecture",metaTitle:"Comprehensive Guide to Leadership Capability Framework",metaDescription:"Complete guide to leadership capability architecture covering components, benefits, and implementation to build future ready leaders and performance.",url:"https://www.stuartandrews.me/blog/a-comprehensive-guide-to-leadership-capability-architecture/"},{slug:"everything-you-need-to-know-about-executive-leadership-coaching",h1:"Everything You Need to Know About Executive Leadership Coaching",metaTitle:"Executive Leadership Coaching | All You Need to Know",metaDescription:"Get all the essential information on executive leadership coaching with Stuart Andrews, tailored to help leaders reach their full potential.",url:"https://www.stuartandrews.me/blog/everything-you-need-to-know-about-executive-leadership-coaching/"},{slug:"corporate-wellness-coaching-programs-for-workplace-performance",h1:"Corporate Wellness Coaching Programs for Workplace Performance",metaTitle:"Corporate Wellness Coaching Programs for Workplace Performance",metaDescription:"Explore corporate wellness coaching programs designed to enhance workplace performance, boost employee well-being, and foster a positive organizational culture.",url:"https://www.stuartandrews.me/blog/corporate-wellness-coaching-programs-for-workplace-performance/"},{slug:"leadership-capabilities-vs-competencies",h1:"Leadership Capabilities vs Competencies: Know the Difference",metaTitle:"Leadership Capabilities vs Competencies: Know the Difference",metaDescription:"Understand leadership capabilities versus competencies and how capability frameworks strengthen promotion decisions succession planning and execution at scales.",url:"https://www.stuartandrews.me/blog/leadership-capabilities-vs-competencies/"},{slug:"executive-coaching-advantages-that-surprise-most-leaders",h1:"Executive Coaching: Advantages That Surprise Most Leaders",metaTitle:"Surprising Advantages of Executive Coaching for Leaders",metaDescription:"Uncover the surprising advantages of executive coaching for leaders, with Stuart Andrews' insights on how it boosts performance and growth.",url:"https://www.stuartandrews.me/blog/executive-coaching-advantages-that-surprise-most-leaders/"},{slug:"10-essential-characteristics-for-successful-leaders",h1:"10 Essential Characteristics for Successful Leaders",metaTitle:"10 Essential Characteristics for Successful Leaders",metaDescription:"Discover the 10 essential characteristics for successful leaders to enhance leadership capability, drive performance, and build high-impact teams in every organisation.",url:"https://www.stuartandrews.me/blog/10-essential-characteristics-for-successful-leaders/"},{slug:"the-differences-between-helpful-feedback-and-harmful-critique",h1:"The Differences between Helpful Feedback and Harmful Critique",metaTitle:"Helpful Feedback vs. Harmful Critique: Key Differences",metaDescription:"Learn the key differences between helpful feedback and harmful critique with Stuart Andrews' tips for improving communication and growth.",url:"https://www.stuartandrews.me/blog/the-differences-between-helpful-feedback-and-harmful-critique/"},{slug:"executive-coaching-vs-leadership-coaching-know-the-difference",h1:"Executive Coaching Vs Leadership Coaching: Know the Difference",metaTitle:"Executive Coaching Vs Leadership Coaching: Know the Difference",metaDescription:"Understand the key differences between executive coaching and leadership coaching to choose the right approach for career growth and organizational success.",url:"https://www.stuartandrews.me/blog/executive-coaching-vs-leadership-coaching-know-the-difference/"},{slug:"the-importance-of-sense-of-purpose-for-an-organisation",h1:"The Importance of Sense of Purpose for an Organisation",metaTitle:"The Importance of Sense of Purpose for an Organisation",metaDescription:"A clear sense of purpose helps organisations align teams, inspire engagement, improve decision making, and drive sustainable long term performance",url:"https://www.stuartandrews.me/blog/the-importance-of-sense-of-purpose-for-an-organisation/"},{slug:"why-is-trust-essential-in-organisations-and-how-can-leaders-build-trust",h1:"Why is trust essential in organisations and how can leaders build trust?",metaTitle:"Building Trust in Organizations: A Leader's Guide",metaDescription:"Learn how to build trust in organizations with Stuart Andrews' leadership guide, essential for fostering collaboration and growth.",url:"https://www.stuartandrews.me/blog/why-is-trust-essential-in-organisations-and-how-can-leaders-build-trust/"},{slug:"effective-tips-for-fostering-and-enhancing-employee-loyalty",h1:"Effective Tips for Fostering and Enhancing Employee Loyalty",metaTitle:"Tips for Fostering and Enhancing Employee Loyalty",metaDescription:"Discover practical leadership insights from Stuart Andrews to strengthen employee loyalty and retention while building trust engagement and long term commitment",url:"https://www.stuartandrews.me/blog/effective-tips-for-fostering-and-enhancing-employee-loyalty/"},{slug:"list-of-10-executive-leadership-coaching-programs-in-london",h1:"List of 10 Executive Leadership Coaching Programs in London",metaTitle:"List of 10 Executive Leadership Coaching Programs in London",metaDescription:"Explore ten executive leadership coaching programs in London designed to develop strategic leadership skills, decision making, and executive performance.",url:"https://www.stuartandrews.me/blog/list-of-10-executive-leadership-coaching-programs-in-london/"},{slug:"how-you-can-align-your-employees-with-your-company-goals",h1:"How You Can Align Your Employees WIth Your Company Goals",metaTitle:"Aligning Employees with Company Goals | A Guide",metaDescription:"Align employees with company goals using Stuart Andrews' guide, filled with actionable strategies for better collaboration and direction.",url:"https://www.stuartandrews.me/blog/how-you-can-align-your-employees-with-your-company-goals/"},{slug:"how-to-develop-leadership-capability-skills-in-students",h1:"How to Develop Leadership Capability Skills in Students",metaTitle:"How to Develop Leadership Capability Skills in Students",metaDescription:"Learn how to develop leadership capability skills in students through strategies, mindset development, and structured frameworks that support long term growth.",url:"https://www.stuartandrews.me/blog/how-to-develop-leadership-capability-skills-in-students/"},{slug:"boost-your-personal-effectiveness-through-time-management",h1:"Boost Your Personal Effectiveness Through Time Management",metaTitle:"Boost Your Personal Effectiveness with Time Management",metaDescription:"Boost your personal effectiveness through time management with practical strategies to prioritise tasks, eliminate distractions, and achieve peak productivity.",url:"https://www.stuartandrews.me/blog/boost-your-personal-effectiveness-through-time-management/"},{slug:"safety-leadership-training-for-supervisors-a-complete-guide",h1:"Safety Leadership Training for Supervisors: A Complete Guide",metaTitle:"Safety Leadership Training for Supervisors: A Complete Guide",metaDescription:"Safety Leadership Training for Supervisors equips leaders to strengthen safety culture, improve accountability, reduce risk, and drive consistent compliance.",url:"https://www.stuartandrews.me/blog/safety-leadership-training-for-supervisors-a-complete-guide/"},{slug:"what-are-the-behavioral-competencies-of-leadership-capabilities",h1:"What Are the Behavioral Competencies of Leadership Capabilities?",metaTitle:"What Are the Behavioral Competencies of Leadership Capabilities?",metaDescription:"Discover the competencies shaping leadership capability including communication, accountability, adaptability, emotional intelligence, and ethical decision making today.",url:"https://www.stuartandrews.me/blog/what-are-the-behavioral-competencies-of-leadership-capabilities/"},{slug:"10-common-ethical-challenges-in-the-medical-workplace",h1:"10 Common Ethical Challenges in the Medical Workplace",metaTitle:"10 Common Ethical Challenges in the Medical Workplace",metaDescription:"Explore 10 common ethical challenges in the medical workplace and learn how healthcare professionals can address them to ensure trust, safety, and compliance.",url:"https://www.stuartandrews.me/blog/10-common-ethical-challenges-in-the-medical-workplace/"},{slug:"handling-leadership-stress-without-losing-efficiency",h1:"Handling Leadership Stress Without Losing Efficiency",metaTitle:"Handling Leadership Stress Without Losing Efficiency",metaDescription:"Learn how leaders manage stress effectively without sacrificing performance, decision quality, or focus, while maintaining resilience, clarity, and long term edge.",url:"https://www.stuartandrews.me/blog/handling-leadership-stress-without-losing-efficiency/"},{slug:"how-to-develop-leadership-capabilities-in-employees",h1:"How to Help Workers Develop Their Leadership Capabilities",metaTitle:"How to Develop Leadership Capabilities in 
1Employees",metaDescription:"Learn practical, evidence-based ways to help employees develop leadership capabilities through real work, coaching, feedback, and culture.",url:"https://www.stuartandrews.me/blog/how-to-develop-leadership-capabilities-in-employees/"},{slug:"business-coaching-a-pathway-to-success-for-business-owners",h1:"Business Coaching: A Pathway to Success for Business Owners",metaTitle:"Business Coaching: A Pathway to Success for Business Owners",metaDescription:"Discover how business coaching helps business owners improve strategy, leadership, and growth while overcoming challenges to achieve lasting success.",url:"https://www.stuartandrews.me/blog/business-coaching-a-pathway-to-success-for-business-owners/"},{slug:"10-benefits-of-safety-leadership-training-for-frontline-managers",h1:"10 Benefits of Safety Leadership Training for Frontline Managers",metaTitle:"10 Benefits of Safety Leadership Training for Frontline Managers",metaDescription:"Discover 10 key benefits of safety leadership training for frontline managers to improve accountability, reduce risk, and strengthen workplace safety culture.",url:"https://www.stuartandrews.me/blog/10-benefits-of-safety-leadership-training-for-frontline-managers/"},{slug:"10-vital-cross-functional-leadership-skills-every-manager-needs",h1:"10 Vital Cross-Functional Leadership Skills Every Manager Needs",metaTitle:"10 Vital Cross-Functional Leadership Skills Every Manager Needs",metaDescription:"Discover 10 vital cross-functional leadership skills every manager needs to improve alignment, collaboration, execution, and long-term organizational performances.",url:"https://www.stuartandrews.me/blog/10-vital-cross-functional-leadership-skills-every-manager-needs/"},{slug:"team-collaboration-and-effectiveness-framework",h1:"Team Collaboration & Effectiveness Framework",metaTitle:"Team Collaboration & Effectiveness Framework",metaDescription:"Explore a practical team collaboration and effectiveness framework to improve alignment communication accountability and performance across organisations scale.",url:"https://www.stuartandrews.me/blog/team-collaboration-and-effectiveness-framework/"},{slug:"5-ways-on-how-to-increase-performance-on-a-tight-budget-for-companies",h1:"5 Ways on How to Increase Performance on a Tight Budget for Companies",metaTitle:"5 Ways on How to Increase Performance on a Tight Budget for Companies",metaDescription:"Increase company performance on a tight budget with proven strategies, smart resource allocation, and practical leadership capability insights to boost efficiency.",url:"https://www.stuartandrews.me/blog/5-ways-on-how-to-increase-performance-on-a-tight-budget-for-companies/"},{slug:"the-roi-of-executive-coaching-real-numbers-real-impact",h1:"The ROI of Executive Coaching: Real Numbers, Real Impact",metaTitle:"The ROI of Executive Coaching: Real Numbers, Real Impact",metaDescription:"Explore how executive coaching delivers measurable ROI through improved decision making, leadership capability, team performance and retention.",url:"https://www.stuartandrews.me/blog/the-roi-of-executive-coaching-real-numbers-real-impact/"},{slug:"list-of-10-executive-leadership-coaching-programs-in-new-york",h1:"List of 10 Executive Leadership Coaching Programs in New York",metaTitle:"List of 10 Executive Leadership Coaching Programs in New York",metaDescription:"Explore 10 executive leadership coaching programs in New York helping senior leaders strengthen decision making capability succession planning and performance!",url:"https://www.stuartandrews.me/blog/list-of-10-executive-leadership-coaching-programs-in-new-york/"},{slug:"unlocking-problem-solving-potential-strategies-for-leaders",h1:"Unlocking Problem Solving Potential: Strategies For Leaders",metaTitle:"Unlocking Problem-Solving Potential: Strategies for Leaders",metaDescription:"Unleash your problem-solving potential with Stuart Andrews' proven leadership strategies to tackle challenges and foster innovation.",url:"https://www.stuartandrews.me/blog/unlocking-problem-solving-potential-strategies-for-leaders/"},{slug:"how-can-corporate-coaching-improve-leadership-in-fintech",h1:"How Can Corporate Coaching Improve Leadership in Fintech",metaTitle:"How Can Corporate Coaching Improve Leadership in Fintech",metaDescription:"Corporate coaching strengthens fintech leadership by improving decision making, agility, ethical judgment and executive resilience in digital environments now.",url:"https://www.stuartandrews.me/blog/how-can-corporate-coaching-improve-leadership-in-fintech/"},{slug:"list-of-10-executive-leadership-coaching-programs-in-sydney",h1:"List of 10 Executive Leadership Coaching Programs in Sydney",metaTitle:"List of 10 Executive Leadership Coaching Programs in Sydney",metaDescription:"Discover 10 executive leadership coaching programs in Sydney, outlining approaches, governance focus, leadership depth, and value for senior executives.",url:"https://www.stuartandrews.me/blog/list-of-10-executive-leadership-coaching-programs-in-sydney/"},{slug:"digital-transformation-3-critical-actions-for-success",h1:"Digital Transformation - 3 Critical Actions for success",metaTitle:"Digital Transformation: 3 Critical Actions for Success",metaDescription:"Achieve digital transformation success through three critical actions from Stuart Andrews, helping leaders accelerate innovation, clarity, and sustainable growth.",url:"https://www.stuartandrews.me/blog/digital-transformation-3-critical-actions-for-success/"},{slug:"what-is-executive-leadership-coaching-for-financial-firms",h1:"What Is Executive Leadership Coaching for Financial Firms?",metaTitle:"What Is Executive Leadership Coaching for Financial Firms?",metaDescription:"Executive leadership coaching for financial firms strengthens judgement, governance, and decision making, helping leaders manage risk, complexity, performance.",url:"https://www.stuartandrews.me/blog/what-is-executive-leadership-coaching-for-financial-firms/"},{slug:"10-benefits-of-corporate-coaching-programs",h1:"10 Benefits of Corporate Coaching Programs",metaTitle:"10 Benefits of Corporate Coaching Programs",metaDescription:"Explore 10 benefits of corporate coaching programs that build leadership capability, improve performance, strengthen culture and drive business growth results.",url:"https://www.stuartandrews.me/blog/10-benefits-of-corporate-coaching-programs/"},{slug:"six-key-practices-to-be-a-better-listener",h1:"Six Key Practices To Be A Better Listener",metaTitle:"Six Key Practices to Enhance Your Listening Skills",metaDescription:"Improve your listening skills with Stuart Andrews' six key practices, essential for effective leadership and communication.",url:"https://www.stuartandrews.me/blog/six-key-practices-to-be-a-better-listener/"},{slug:"cultivating-a-culture-of-employee-wellbeing-tips-for-leaders",h1:"Cultivating A Culture Of Employee Wellbeing: Tips For Leaders",metaTitle:"Tips for Leaders | Cultivating Employee Wellbeing Culture",metaDescription:"Cultivate a culture of employee wellbeing with Stuart Andrews leadership tips for building a supportive resilient and thriving workplace culture today",url:"https://www.stuartandrews.me/blog/cultivating-a-culture-of-employee-wellbeing-tips-for-leaders/"},{slug:"strategic-handbook-for-executive-leadership-coaching",h1:"Strategic Handbook For Executive Leadership Coaching",metaTitle:"Strategic Handbook For Executive Leadership Coaching",metaDescription:"A practical strategic handbook on executive leadership coaching, covering benefits, frameworks, and how coaching strengthens senior leadership performance.",url:"https://www.stuartandrews.me/blog/strategic-handbook-for-executive-leadership-coaching/"},{slug:"future-proofing-the-next-generation-hr-through-executive-coaching",h1:"Future-Proofing the Next-Generation HR through Executive Coaching",metaTitle:"Future-Proofing HR | The Role of Executive Coaching",metaDescription:"Learn how executive coaching c
1an future-proof HR by fostering leadership skills and preparing organizations for long-term success.",url:"https://www.stuartandrews.me/blog/future-proofing-the-next-generation-hr-through-executive-coaching/"},{slug:"what-is-cross-functional-team-alignment",h1:"What Is Cross-Functional Team Alignment?",metaTitle:"What Is Cross-Functional Team Alignment?",metaDescription:"Learn what cross-functional team alignment is, why it matters, and how it improves collaboration, strategy execution, and organizational performance success.",url:"https://www.stuartandrews.me/blog/what-is-cross-functional-team-alignment/"},{slug:"10-leadership-skills-and-capabilities",h1:"10 List of Skills and Capabilities for Effective Leadership",metaTitle:"10 List of Skills and Capabilities for Effective Leadership",metaDescription:"Discover 10 essential characteristics of successful leaders, with actionable insights to build leadership capability, influence teams, and drive business performance.",url:"https://www.stuartandrews.me/blog/10-leadership-skills-and-capabilities/"},{slug:"employee-well-being-and-how-to-prevent-turnover-and-significant-loss-of-intellectual-property",h1:"Employee Well-Being and How To Prevent Turnover And Significant Loss Of Intellectual Property",metaTitle:"Employee Well-Being That Reduces Turnover & IP Loss",metaDescription:"Employee well-being has evolved from a human resources checkbox into a strategic imperative that directly impacts organizational resilience.",url:"https://www.stuartandrews.me/blog/employee-well-being-and-how-to-prevent-turnover-and-significant-loss-of-intellectual-property/"},{slug:"best-10-ai-coaching-services-for-corporate-use",h1:"Best 10 AI Coaching Services for Corporate Use",metaTitle:"Best 10 AI Coaching Services for Corporate Use",metaDescription:"Explore the best 10 AI coaching services for corporate use in 2026, helping leaders improve decisions, performance, scalability, and future-ready leadership.",url:"https://www.stuartandrews.me/blog/best-10-ai-coaching-services-for-corporate-use/"},{slug:"do-we-really-need-so-many-meetings",h1:"Do we really need so many meetings?",metaTitle:"The Need for Meetings | Are They Truly Necessary?",metaDescription:"Explore when meetings really matter with Stuart Andrews insights helping leaders decide when to meet how to stay focused and run productive discussions efficient",url:"https://www.stuartandrews.me/blog/do-we-really-need-so-many-meetings/"},{slug:"how-to-train-and-align-emerging-leaders-across-departments",h1:"How to Train and Align Emerging Leaders Across Departments",metaTitle:"How to Train and Align Emerging Leaders Across Departments",metaDescription:"Learn how to train and align emerging leaders across departments to improve collaboration, leadership consistency, and long-term organisational performance.",url:"https://www.stuartandrews.me/blog/how-to-train-and-align-emerging-leaders-across-departments/"},{slug:"overcoming-six-big-challenges-of-hybrid-working",h1:"Overcoming Six Big Challenges Of Hybrid Working",metaTitle:"Overcoming Six Key Challenges of Hybrid Working",metaDescription:"Navigate hybrid work challenges with Stuart Andrews' guide to overcoming six key obstacles for a more effective leadership approach.",url:"https://www.stuartandrews.me/blog/overcoming-six-big-challenges-of-hybrid-working/"},{slug:"how-leaders-can-transform-workplace-culture",h1:"How Leaders Can Transform Workplace Culture",metaTitle:"Transforming Workplace Culture | Leader's Role",metaDescription:"Discover the pivotal role of leaders in transforming workplace culture with Stuart Andrews' actionable strategies for lasting change.",url:"https://www.stuartandrews.me/blog/how-leaders-can-transform-workplace-culture/"},{slug:"how-do-companies-inspire-unity-to-drive-high-performance",h1:"How do companies inspire unity to drive high performance?",metaTitle:"How Companies Inspire Unity to Drive High Performance",metaDescription:"Discover how organisations foster unity and drive high performance using Stuart Andrews proven leadership strategies built for modern business leaders today now",url:"https://www.stuartandrews.me/blog/how-do-companies-inspire-unity-to-drive-high-performance/"},{slug:"what-is-a-reciprocal-approach-to-leadership",h1:"What Is a Reciprocal Ap
1proach to Leadership?",metaTitle:"What Is a Reciprocal Approach to Leadership?",metaDescription:"Learn what a reciprocal approach to leadership means, how it builds trust, shared accountability, and stronger performance across teams at work today now fast.",url:"https://www.stuartandrews.me/blog/what-is-a-reciprocal-approach-to-leadership/"},{slug:"the-founders-guide-to-expanding-your-leadership-role",h1:"The Founder’s Guide to Expanding Your Leadership Role",metaTitle:"The Founder’s Guide to Expanding Leadership Beyond Yourself",metaDescription:"Learn how founders can expand their leadership role, build leadership capability, reduce dependency, and scale organisations with clarity and accountability.",url:"https://www.stuartandrews.me/blog/the-founders-guide-to-expanding-your-leadership-role/"},{slug:"generativity-versus-stagnation-whats-the-difference",h1:"Generativity Versus Stagnation: What’s the Difference",metaTitle:"Generativity Versus Stagnation: What’s the Difference",metaDescription:"Understand generativity versus stagnation, how they differ, why it matters for leadership effectiveness, and how coaching supports long term growth at work now.",url:"https://www.stuartandrews.me/blog/generativity-versus-stagnation-whats-the-difference/"},{slug:"the-reasons-behind-the-failure-of-conventional-leadership-training",h1:"The Reasons Behind the Failure of Conventional Leadership Training",metaTitle:"The Reasons Behind the Failure of Conventional Leadership Training",metaDescription:"Discover why conventional leadership training fails and learn modern, behavioural methods that build real, lasting leadership capability.",url:"https://www.stuartandrews.me/blog/the-reasons-behind-the-failure-of-conventional-leadership-training/"},{slug:"what-is-core-leadership-capability",h1:"What Is Core Leadership Capability?",metaTitle:"What Is Core Leadership Capability?",metaDescription:"Core leadership capability refers to the essential skills, behaviours, and judgement leaders need to influence people and deliver results.",url:"https://www.stuartandrews.me/blog/what-is-core-leadership-capability/"},{slug:"5-creative-managerial-strategies-to-solve-poor-performance",h1:"5 Creative Managerial Strategies to Solve Poor Performance",metaTitle:"5 Creative Managerial Strategies to Solve Poor Performance",metaDescription:"Learn 5 creative managerial strategies to solve poor performance, improve leadership capability, boost team productivity, and build a high-performing workplace culture.",url:"https://www.stuartandrews.me/blog/5-creative-managerial-strategies-to-solve-poor-performance/"},{slug:"leadership-capacity-vs-capability-how-to-build",h1:"Leadership Capacity Vs Capability: How to Build",metaTitle:"Leadership Capacity Vs Capability: How to Build",metaDescription:"Learn how to develop leadership capability and capacity by balancing skills, mindset, and systems to build strong leaders and sustainable business performance.",url:"https://www.stuartandrews.me/blog/leadership-capacity-vs-capability-how-to-build/"},{slug:"10-best-online-platforms-for-employee-coaching",h1:"10 Best Online Platforms for Employee Coaching",metaTitle:"10 Best Online Platforms for Employee Coaching",metaDescription:"Discover the 10 best online platforms for employee coaching to improve skills, engagement, performance, and leadership development across modern workplaces.",url:"https://www.stuartandrews.me/blog/10-best-online-platforms-for-employee-coaching/"},{slug:"what-is-coaching-leadership-style",h1:"What is Coaching Leadership Style​",metaTitle:"What is Coaching Leadership Style​",metaDescription:"Learn about the Coaching Leadership Style, its benefits, and how it helps leaders develop teams, foster growth, and drive success in today's dynamic business world.",url:"https://www.stuartandrews.me/blog/what-is-coaching-leadership-style/"},{slug:"integrate-leadership-development-into-everyday-activities",h1:"Integrate Leadership Development Into Everyday Activities",metaTitle:"Integrate Leadership Development Into Everyday Activities",metaDescription:"Explore practical ways to integrate leadership development into everyday activities and build sustainable leadership capability over time.",url:"https://www.stuartandrews.me/blog/integrate-leadership-development-into-everyday-activities/"},{slug:"how-to-build-a-leadership-development-plan-for-your-msp",h1:"How to Build a Leadership Development Plan for Your MSP",metaTitle:"How to Build a Leadership Development Plan for Your MSP",metaDescription:"Learn how to build a leadership development plan for your MSP. Enhance leadership skills, foster growth, and drive success with a strategic development approach.",url:"https://www.stuartandrews.me/blog/how-to-build-a-leadership-development-plan-for-your-msp/"},{slug:"why-leadership-coaching-is-important-for-executives",h1:"Why Leadership Coaching is Important for Executives?",metaTitle:"Why Leadership Coaching is Vital for Executives",metaDescription:"Explore why leadership coaching is essential for executives, helping them enhance performance, strategy, and long-term success.",url:"https://www.stuartandrews.me/blog/why-leadership-coaching-is-important-for-executives/"},{slug:"executive-coaching-must-have-great-culture-in-its-teachings",h1:"Executive Coaching Must Have Great Culture in Its Teachings",metaTitle:"Great Culture in Executive Coaching for Hybrid Work",metaDescription:"Create a great culture through executive coaching for hybrid work with Stuart Andrews' insights on fostering collaboration and success.",url:"https://www.stuartandrews.me/blog/executive-coaching-must-have-great-culture-in-its-teachings/"},{slug:"best-20-tips-to-improve-your-coaching-for-customer-service",h1:"Best 20 Tips to Improve Your Coaching for Customer Service",metaTitle:"Best 20 Tips to Improve Your Coaching for Customer Service",metaDescription:"Discover 20 practical tips to improve c
1oaching for customer service, build confident teams, enhance communication, and deliver consistent customer experiences.",url:"https://www.stuartandrews.me/blog/best-20-tips-to-improve-your-coaching-for-customer-service/"},{slug:"what-is-executive-leadership-coaching-for-team-managers",h1:"What Is Executive Leadership Coaching for Team Managers",metaTitle:"What Is Executive Leadership Coaching for Team Managers",metaDescription:"Executive leadership coaching helps team managers build strategic judgment, lead beyond operations, and strengthen decision making within complex organisations.",url:"https://www.stuartandrews.me/blog/what-is-executive-leadership-coaching-for-team-managers/"},{slug:"10-best-executive-coaches-for-startups-and-scaleups",h1:"10 Best Executive Coaches for Startups and Scaleups",metaTitle:"10 Best Executive Coaches for Startups and Scaleups",metaDescription:"Discover the 10 best executive coaches for startups and scaleups, selected for leadership impact, proven methods, and experience in high growth environments.",url:"https://www.stuartandrews.me/blog/10-best-executive-coaches-for-startups-and-scaleups/"},{slug:"how-to-encourage-expanding-roles-within-the-company",h1:"How to Encourage Expanding Roles within the Company",metaTitle:"How to Encourage Expanding Roles within the Company",metaDescription:"Encouraging expanding roles within a company helps employees grow skills, take ownership, and support business growth through structured development and trust.",url:"https://www.stuartandrews.me/blog/how-to-encourage-expanding-roles-within-the-company/"},{slug:"pessimistic-vs-optimistic-know-the-difference",h1:"Pessimistic vs Optimistic: Know the Difference",metaTitle:"Pessimistic vs Optimistic: Know the Difference",metaDescription:"Learn the key differences between pessimistic and optimistic mindsets, how they shape decisions, behavior, and overall life outcomes for personal growth success",url:"https://www.stuartandrews.me/blog/pessimistic-vs-optimistic-know-the-difference/"},{slug:"how-to-spot-leadership-deficits-before-they-cause-obstacles",h1:"How to Spot Leadership Deficits Before They Cause Obstacles",metaTitle:"How to Spot Leadership Deficits Early",metaDescription:"Discover early signs of leadership deficits and how proactive assessment helps prevent bottlenecks and build stronger organisational capability.",url:"https://www.stuartandrews.me/blog/how-to-spot-leadership-deficits-before-they-cause-obstacles/"},{slug:"a-ceo-a-calendar-and-three-red-items",h1:"A CEO, a calendar, and three red items",metaTitle:"A CEO, a calendar, and three red items",metaDescription:"Discover how a CEO uses a calendar and three red items to truly boost leadership focus, productivity, decision making, and strategic impact with practical insights",url:"https://www.stuartandrews.me/blog/a-ceo-a-calendar-and-three-red-items/"},{slug:"using-leadership-to-build-an-accountability-culture",h1:"Using Leadership to Build an Accountability Culture",metaTitle:"Using Leadership to Build Accountability Culture",metaDescription:"Learn how effective leadership builds a strong accountability culture through clear expectations, trust, feedback, and systems that drive ownership and performance.",url:"https://www.stuartandrews.me/blog/using-leadership-to-build-an-accountability-culture/"},{slug:"ten-advantages-of-executive-leadership-coaching-for-women",h1:"Ten Advantages of Executive Leadership Coaching for Women",metaTitle:"Ten Advantages of Executive Leadership Coaching for Women",metaDescription:"Explore ten key advantages of executive leadership coaching for women, from stronger confidence and decision making to long term career and leadership growth.",url:"https://www.stuartandrews.me/blog/ten-advantages-of-executive-leadership-coaching-for-women/"},{slug:"a-quick-guide-to-maintaining-motivation-in-a-hybrid-workplace",h1:"A Quick Guide to Maintaining Motivation in a Hybrid Workplace",metaTitle:"Maintaining Motivation in a Hybrid Workplace | A Guide",metaDescription:"Stay motivated in a hybrid workplace with practical tips on engagement, routines, communication, performance focus and leadership support for teams. Start now!!",url:"https://www.stuartandrews.me/blog/a-quick-guide-to-maintaining-motivation-in-a-hybrid-workplace/"},{slug:"the-best-corporate-training-company-for-leadership-coaching",h1:"The Best Corporate Training Company for Leadership Coaching",metaTitle:"The Best Corporate Training Company for Leadership Coaching",metaDescription:"Discover the best corporate training company for leadership coaching and learn how expert programs strengthen leaders, boost performance, and drive success.",url:"https://www.stuartandrews.me/blog/the-best-corporate-training-company-for-leadership-coaching/"},{slug:"best-10-corporate-business-coaching-in-sydney",h1:"Best 10 Corporate Business Coaching in Sydney",metaTitle:"Best 10 Corporate Business Coaching in Sydney",metaDescription:"Discover the best 10 corporate business coaching in Sydney for leaders seeking strategic growth, decision making and sustainable organisational performance ROI.",url:"https://www.stuartandrews.me/blog/best-10-corporate-business-coaching-in-sydney/"},{slug:"emotional-intelligence-for-executives",h1:"Emotional Intelligence for Executives, Your Competitive Edge",metaTitle:"Emotional Intelligence for Executives: Your Competitive Edge",metaDescription:"Emotional intelligence is a performance multiplier for executives. Learn how it improves decision quality, trust, execution speed, and leadership capability at scale.",url:"https://www.stuartandrews.me/blog/emotional-intelligence-for-executives/"},{slug:"what-is-executive-leadership-coaching-for-nonprofit-leaders",h1:"What Is Executive Leadership Coaching for Nonprofit Leaders?",metaTitle:"What Is Executive Leadership Coaching for Nonprofit Leaders?",metaDescription:"Executive leadership coaching for nonprofit leaders strengthens judgement, governance, and mission focus while improving decision making, accountability, impact",url:"https://www.stuartandrews.me/blog/what-is-executive-leadership-coaching-for-nonprofit-leaders/"},{slug:"executive-coaching-vs-leadership-consulting",h1:"Executive Coaching vs Leadership Consulting",metaTitle:"Executive Coaching vs Leadership Consulting",metaDescription:"Explore executive coaching and leadership consulting, the
1ir benefits, key differences, and when each approach is best for leadership development.",url:"https://www.stuartandrews.me/blog/executive-coaching-vs-leadership-consulting/"},{slug:"7-indications-that-your-executive-team-is-not-aligned",h1:"7 Indications That Your Executive Team Is Not Aligned",metaTitle:"7 Indications That Your Executive Team Is Not Aligned",metaDescription:"Discover 7 key signs your executive team lacks alignment. Learn how misalignment impacts performance, communication, and strategy to improve leadership success.",url:"https://www.stuartandrews.me/blog/7-indications-that-your-executive-team-is-not-aligned/"},{slug:"how-to-build-workplace-trust-in-a-remote-or-hybrid-setting",h1:"How To Build Workplace Trust in A Remote or Hybrid Setting",metaTitle:"Building Workplace Trust in Remote and Hybrid Settings",metaDescription:"Strengthen workplace trust in remote and hybrid environments with Stuart Andrews' strategies for building effective, cohesive teams.",url:"https://www.stuartandrews.me/blog/how-to-build-workplace-trust-in-a-remote-or-hybrid-setting/"},{slug:"why-your-company-works-twice-as-hard-for-10percent-more-output",h1:"Why Your Company Works Twice as Hard for 10% More Output",metaTitle:"Why Your Company Works Twice as Hard for 10% More Output",metaDescription:"There's a painful paradox at the heart of business growth. The very success that should propel you forward often becomes the anchor dragging you down.",url:"https://www.stuartandrews.me/blog/why-your-company-works-twice-as-hard-for-10percent-more-output/"},{slug:"how-to-evolve-your-workplace-culture-while-scaling-fast",h1:"How to Evolve Your Workplace Culture While Scaling Fast",metaTitle:"How to Evolve Your Workplace Culture While Scaling Fast",metaDescription:"Learn how to evolve workplace culture while scaling fast using leadership clarity systems and behaviours that protect alignment performance and trust.",url:"https://www.stuartandrews.me/blog/how-to-evolve-your-workplace-culture-while-scaling-fast/"},{slug:"develop-leadership-capability-skills-workplace",h1:"How to Develop Leadership Capability Skills at Workplace",metaTitle:"How to Develop Leadership Capability Skills at Workplace",metaDescription:"Develop leadership capability at work through self awareness emotional intelligence and practical leadership development that drives clarity trust performance.",url:"https://www.stuartandrews.me/blog/develop-leadership-capability-skills-workplace/"},{slug:"from-founder-to-ceo-transition-leadership-coaching",h1:"From Founder to CEO Transition Leadership Coaching",metaTitle:"From Founder to CEO Transition Leadership Coaching",metaDescription:"Learn how From Founder to CEO Transition Leadership Coaching helps leaders build executive presence, improve decision-making, and align leadership with growth.",url:"https://www.stuartandrews.me/blog/from-founder-to-ceo-transition-leadership-coaching/"},{slug:"what-is-corporate-coaching",h1:"What Is Corporate Coaching? Why it matters for Businesses",metaTitle:"What Is Corporate Coaching? Why it matters for Businesses",metaDescription:"Corporate coaching develops leadership capability, decision making, accountability by aligning individual performance with organisational strategy long term",url:"https://www.stuartandrews.me/blog/what-is-corporate-coaching/"},{slug:"how-today-s-leaders-can-make-the-best-decisions",h1:"How Today's Leaders Can Make the Best Decisions",metaTitle:"How Today's Leaders Can Make the Best Decisions",metaDescription:"Find out how today’s leaders can make the best decisions with Stuart Andrews' expert insights on strategic thinking and problem-solving.",url:"https://www.stuartandrews.me/blog/how-today-s-leaders-can-make-the-best-decisions/"},{slug:"why-employee-development-should-be-a-top-priority-for-msp-owners",h1:"Why Employee Development Should Be a Top Priority for MSP Owners",metaTitle:"Why Employee Development Should Be a Top Priority for MSP Owners",metaDescription:"Why Employee Development Should Be a Top Priority for MSP Owners: Boosting Skills, Performance, and Business Growth for Managed Service Providers.",url:"https://www.stuartandrews.me/blog/why-employee-development-sh
1ould-be-a-top-priority-for-msp-owners/"},{slug:"leadership-operating-system-for-business",h1:"Significance of a Leadership Operating System for Business",metaTitle:"Why a Leadership Operating System Matters for Business",metaDescription:"Discover why a leadership operating system is essential for consistent decision-making, execution, and scalable leadership in modern businesses.",url:"https://www.stuartandrews.me/blog/leadership-operating-system-for-business/"},{slug:"creating-a-succession-plan-and-leadership-pipeline-for-expanding-businesses",h1:"Creating a Succession Plan and Leadership Pipeline for Expanding Businesses",metaTitle:"Succession Planning & Leadership Pipeline Guide",metaDescription:"Build future leaders with a practical guide to succession planning and leadership pipelines that strengthen talent, resilience, growth and competitive advantage",url:"https://www.stuartandrews.me/blog/creating-a-succession-plan-and-leadership-pipeline-for-expanding-businesses/"},{slug:"what-is-an-executive-program-in-business-finance",h1:"What Is an Executive Program in Business Finance?",metaTitle:"What Is an Executive Program in Business Finance?",metaDescription:"Discover what an executive program in business finance is, how it builds strategic financial leadership skills, and why it matters for senior decision managers.",url:"https://www.stuartandrews.me/blog/what-is-an-executive-program-in-business-finance/"},{slug:"how-mental-health-coaching-services-supports-workplace",h1:"How Mental Health Coaching Services Supports Workplace",metaTitle:"How Mental Health Coaching Services Supports Workplace",metaDescription:"Learn how mental health coaching services support workplace wellbeing, leadership resilience, employee engagement, and sustainable organisational performance.",url:"https://www.stuartandrews.me/blog/how-mental-health-coaching-services-supports-workplace/"},{slug:"five-leadership-errors-that-prevent-organisational-development",h1:"Five Leadership Errors That Prevent Organisational Development",metaTitle:"5 Leadership Errors That Hinder Organisational Growth",metaDescription:"Explore 5 common leadership mistakes that restrict organisational growth and performance, with practical evidence based solutions to build resilient leadership",url:"https://www.stuartandrews.me/blog/five-leadership-errors-that-prevent-organisational-development/"},{slug:"proactivity-vs-reactivity-management",h1:"Proactivity Vs Reactivity Management: What's the Difference",metaTitle:"Proactivity Vs Reactivity Management: What's the Difference",metaDescription:"Learn the difference between proactive and reactive management and how each approach impacts leadership decisions, team performance, and business results today",url:"https://www.stuartandrews.me/blog/proactivity-vs-reactivity-management/"},{slug:"future-of-work-lessons-learned-from-covid-19",h1:"Future of Work - Lessons Learned From COVID-19",metaTitle:"Future of Work | Key Lessons from COVID-19 for Businesses",metaDescription:"Discover key lessons from COVID-19 that are shaping the future of work, helping businesses adapt and thrive in the new landscape.",url:"https://www.stuartandrews.me/blog/future-of-work-lessons-learned-from-covid-19/"}];async function Kt(t,s,a){const n=await fetch(t,{...a,headers:{"Content-Type":"application/json",...oe(),...a?.headers||{}}});if(!n.ok){const i=await n.json().catch(()=>({error:"Request failed"}));throw new Error(i.error||"Request failed")}return n.json()}function jn({token:t,onClose:s,onImportComplete:a}){const[n,i]=h.useState(Fe.map(o=>({slug:o.slug,h1:o.h1,metaTitle:o.metaTitle,status:"pending"}))),[m,j]=h.useState(!1),[k,p]=h.useState(!1),[u,N]=h.useState({created:0,skipped:0,errors:0}),[P,x]=h.useState(!0),[H,T]=h.useState(!1),[A,L]=h.useState(null),E=5;h.useEffect(()=>{async function o(){try{const S=await Kt("/api/admin/articles",t),l=new Set(S.map(M=>M.slug));i(M=>M.map(W=>l.has(W.slug)?{...W,status:"skipped"}:W));const b=Fe.filter(M=>l.has(M.slug)).length;b>0&&(N(M=>({...M,skipped:b})),b===Fe.length&&p(!0))}catch{}finally{x(!1)}}o()},[t]);async function B(){j(!0),p(!1),N({created:0,skipped:0,errors:0});let o=0,S=0,l=0;const b=Fe.filter(M=>n.find(W=>W.slug===M.slug)?.status==="pending");for(let M=0;M<b.length;M+=E){const W=b.slice(M,M+E),te=W.map(V=>V.slug);i(V=>V.map(ne=>te.includes(ne.slug)?{...ne,status:"importing"}:ne));try{const V=await Kt("/api/admin/import/bulk-blogs",t,{method:"POST",body:JSON.stringify({entries:W})}
1),ne=new Set(V.createdSlugs||[]),Y=new Set(V.skippedSlugs||[]),we={};for(const w of V.errors||[])we[w.slug]=w.error;o+=V.created||0,S+=V.skipped||0,l+=(V.errors||[]).length,i(w=>w.map(R=>te.includes(R.slug)?we[R.slug]?{...R,status:"error",error:we[R.slug]}:Y.has(R.slug)?{...R,status:"skipped"}:ne.has(R.slug)?{...R,status:"created"}:{...R,status:"error",error:"No status returned"}:R)),N(w=>({created:w.created+o,skipped:w.skipped+S,errors:w.errors+l}))}catch(V){i(ne=>ne.map(Y=>te.includes(Y.slug)?{...Y,status:"error",error:V.message}:Y)),l+=W.length}await new Promise(V=>setTimeout(V,300))}j(!1),p(!0),a()}async function U(){T(!0),L(null);try{const o=await Kt("/api/admin/articles/bulk-recategorize",t,{method:"POST"});L({updated:o.updated,total:o.total}),a()}catch{L({updated:-1,total:0})}finally{T(!1)}}const c=n.filter(o=>o.status==="pending").length,D=n.filter(o=>o.status==="created").length,$=n.filter(o=>o.status==="skipped").length,F=n.filter(o=>o.status==="error").length,J=n.filter(o=>o.status==="importing").length,re=D+$+F+J,I=!P&&c===0&&$>0&&D===0;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between bg-card border border-border rounded-xl px-4 py-3 sticky top-0 z-10",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{onClick:s,className:"text-muted-foreground hover:text-foreground","data-testid":"bulk-import-back",children:e.jsx(pt,{className:"w-4 h-4"})}),e.jsx("span",{className:"text-sm font-medium text-foreground",children:"Bulk Blog Import"}),e.jsxs(ve,{variant:"outline",className:"text-xs border-info/40 text-info",children:[Fe.length," posts"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[m&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:[e.jsx(ie,{className:"w-3 h-3 inline animate-spin mr-1"}),re," / ",Fe.length]}),!k&&!m&&!P&&c>0&&e.jsxs(ee,{size:"sm",onClick:B,className:"bg-accent-gold hover:bg-accent-gold-light text-navy-deep font-semibold","data-testid":"bulk-import-start",children:[e.jsx(za,{className:"w-3.5 h-3.5 mr-1.5"}),"Import ",c," Remaining"]}),!m&&e.jsx(ee,{size:"sm",variant:"outline",onClick:U,disabled:H,className:"border-purple-700/60 text-purple-300 hover:text-white hover:border-purple-500","data-testid":"bulk-recategorize",children:H?e.jsxs(e.Fragment,{children:[e.jsx(ie,{className:"w-3.5 h-3.5 mr-1.5 animate-spin"})," Re-categorising…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ue,{className:"w-3.5 h-3.5 mr-1.5"})," Re-categorise All"]})}),I&&!m&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Te,{className:"w-4 h-4 text-success"}),e.jsxs("span",{className:"text-success font-medium",children:["All ",Fe.length," already imported"]})]}),k&&D>0&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Te,{className:"w-4 h-4 text-success"}),e.jsxs("span",{className:"text-success font-medium",children:["Done — ",D," imported, ",$," skipped"]})]})]})]}),A&&e.jsx("div",{className:`rounded-lg px-4 py-3 text-sm flex items-center gap-2 ${A.updated>=0?"bg-purple-950/40 border border-purple-500/30 text-purple-300":"bg-destructive/10 border border-destructive/30 text-destructive-ink"}`,children:A.updated>=0?e.jsxs(e.Fragment,{children:[e.jsx(Te,{className:"w-4 h-4 text-purple-400 shrink-0"})," Re-categorised ",A.updated," of ",A.total," articles successfully. Reload the article list to see updated categories."]}):e.jsxs(e.Fragment,{children:[e.jsx(gs,{className:"w-4 h-4 shrink-0"})," Re-categorisation failed. Please try again."]})}),(P||$>0||D>0||F>0)&&e.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[e.jsxs("div",{className:"bg-card border border-border rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-muted-foreground",children:P?"…":c}),e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:"Pending"})]}),e.jsxs("div",{className:"bg-card border border-border rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-success",children:D}),e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:"Imported"})]}),e.jsxs("div",{className:"bg-card border border-border rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-warning",children:P?"…":$}),e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:"Already Exists"})]}),e.jsxs("div",{className:"bg-card border border-border rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-destructive",children:F}),e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:"Errors"})]})]}),!m&&!k&&!P&&c>0&&e.jsxs("div",{className:"bg-info/10 border border-info/30 rounded-xl p-4 text-sm text-info-ink",children:[c<Fe.length?`${$} articles already imported. ${c} remaining to import from stuartandrews.me.`:`This will crawl all ${Fe.length} blog posts from stuartandrews.me to import their content, images, and SEO metadata.`," Processing in batches of ",E," — expect a few minutes."]}),P&&e.jsxs("div",{className:"flex items-center gap-2 py-3 text-sm text-muted-foreground",children:[e.jsx(ie,{className:"w-4 h-4 animate-spin"})," Checking which articles are already imported…"]}),e.jsx(_a,{className:"h-[480px]",children:e.jsx("div",{className:"space-y-1 pr-2",children:n.map(o=>e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 rounded-lg bg-muted/60 border border-border/60 gap-3","data-testid":`bulk-entry-${o.slug}`,children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[o.status==="importing"&&e.jsx(ie,{className:"w-3.5 h-3.5 animate-spin text-info flex-shrink-0"}),o.status==="created"&&e.jsx(Te,{className:"w-3.5 h-3.5 text-success flex-shrink-0"}),o.status==="skipped"&&e.jsx(Te,{className:"w-3.5 h-3.5 text-warning/70 flex-shrink-0"}),o.status==="error"&&e.jsx(gs,{className:"w-3.5 h-3.5 text-destructive flex-shrink-0"}),o.status==="pending"&&e.jsx("div",{className:"w-3.5 h-3.5 rounded-full border border-border flex-shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs text-foreground truncate",children:o.h1||o.metaTitle}),e.jsx("p",{className:"text-xs text-muted-foreground truncate font-mono",children:o.slug}),o.error&&e.jsx("p",{className:"text-xs text-destructive truncate",children:o.error})]})]}),e.jsx(Nn,{status:o.status})]},o.slug))})})]})}function Nn({status:t}){return t==="pending"?e.jsx(ve,{variant:"outline",className:"text-xs border-border text-muted-foreground flex-shrink-0",children:"Pending"}):t==="importing"?e.jsx(ve,{variant:"outline",className:"text-xs border-info/50 text-info flex-shrink-0",children:"Importing…"}):t==="created"?e.jsx(ve,{variant:"outline",className:"text-xs border-success/50 text-success flex-shrink-0",children:"Imported"}):t==="skipped"?e.jsx(ve,{variant:"outline",className:"text-xs border-warning/30 text-warning-ink flex-shrink-0",children:"Exists"}):t==="error"?e.jsx(ve,{variant:"outline",className:"text-xs border-destructive/50 text-destructive flex-shrink-0",children:"Error"}):null}function Ft(t){return t==="left"||t==="right"||t==="center"?t:null}function kn(t){const s=(t.style.textAlign||"").trim().toLowerCase(),a=(t.getAttribute("align")||"").trim().toLowerCase();return Ft(s||a)}function Cn(t){return Ft(t?.align)}function Zs(){return{default:null,parseHTML:t=>kn(t),renderHTML:t=>t.align?{style:`text-align: ${t.align}`}:{}}}function Sn(t){var s;const a=t.parentElement,n=t.closest("table");if(!a||!n)return null;const i=Array.from(a.children).indexOf(t),m=(s=n.querySelectorAll("colgroup > col")[i])===null||s===void 0?void 0:s.getAttribute("width");return m?[parseInt(m,10)]:null}function ea(t){const s=t.getAttribute("colwidth");return s?s.split(",").map(a=>parseInt(a,10)):Sn(t)}const Tn=/[ \t\r\n\f]+/g;function ta(t){var s;return t.children.length>0?!1:((s=t.textContent)!==null&&s!==void 0?s:"").replace(Tn,"")===""}function sa(t){const s=t.createAndFill();if(!s)throw new Error(`[tiptap error]: "${t.name}" has no default content to backfill.`);return s.content}const aa=Rt.create({name:"tableCell",addOptions(){return{HTMLAttributes:{}}},content:"block+",addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:ea},align:Zs()}},tableRole:"cell",isolating:!0,parseHTML(){return[{tag:"td",getAttrs:t=>ta(t)?{}:!1,getContent:(t,s)=>sa(s.nodes[this.name])},{tag:"td"}]},renderHTML({HTMLAttributes:t}){return["td",Ke(this.options.HTMLAttributes,t),0]}}),ra=Rt.create({name:"tableHeader",addOptions(){return{HTMLAttributes:{}}},content:"block+",addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:ea},align:Zs()}},tableRole:"header_cell",isolating:!0,parseHTML(){return[{tag:"th",getAttrs:t=>ta(t)?{}:!1,getContent:(t,s)=>sa(s.nodes[this.name])},{tag:"th"}]},renderHTML({HTMLAttributes:t}){return["th",Ke(this.options.HTMLAttributes,t),0]}}),na=Rt.create({name:"tableRow",addOptions(){return{HTMLAttributes:{}}},content:"(tableCell | tableHeader)*",tableRole:"row",parseHTML(){return[{tag:"tr"}]},renderHTML({HTMLAttributes:t}){return["tr",Ke(this.options.HTMLAttributes,t),0]}});function ts(t,s){return s?["width",`${Math.max(s,t)}px`]:["min-width",`${t}px`]}function Hs(t,s,a,n,i,m){let j=0,k=!0,p=s.firstChild;const u=t.firstChild;if(u!==null)for(let x=0,H=0;x<u.childCount;x+=1){const{colspan:T,colwidth:A}=u.child(x).attrs;for(let L=0;L<T;L+=1,H+=1){const E=i===H?m:A&&A[L],B=E?`${E}px`:"";
1if(j+=E||n,E||(k=!1),p){if(p.style.width!==B){const[U,c]=ts(n,E);p.style.setProperty(U,c)}p=p.nextSibling}else{const U=document.createElement("col"),[c,D]=ts(n,E);U.style.setProperty(c,D),s.appendChild(U)}}}for(;p;){var N;const x=p.nextSibling;(N=p.parentNode)===null||N===void 0||N.removeChild(p),p=x}const P=t.attrs.style&&typeof t.attrs.style=="string"&&/\bwidth\s*:/i.test(t.attrs.style);k&&!P?(a.style.width=`${j}px`,a.style.minWidth=""):(a.style.width="",a.style.minWidth=`${j}px`)}var An=class{constructor(t,s,a,n={}){this.node=t,this.cellMinWidth=s,this.dom=document.createElement("div"),this.dom.className="tableWrapper",this.table=this.dom.appendChild(document.createElement("table"));for(const[i,m]of Object.entries(n))m!=null&&(i==="style"?this.table.style.cssText=String(m):this.table.setAttribute(i,String(m)));t.attrs.style&&(this.table.style.cssText=t.attrs.style),this.colgroup=this.table.appendChild(document.createElement("colgroup")),Hs(t,this.colgroup,this.table,s),this.contentDOM=this.table.appendChild(document.createElement("tbody"))}update(t){return t.type!==this.node.type?!1:(this.node=t,Hs(t,this.colgroup,this.table,this.cellMinWidth),!0)}ignoreMutation(t){const s=t.target,a=this.dom.contains(s),n=this.contentDOM.contains(s);return!!(a&&!n&&(t.type==="attributes"||t.type==="childList"||t.type==="characterData"))}};function Ln(t,s,a,n){let i=0,m=!0;const j=[],k=t.firstChild;if(!k)return{};for(let N=0,P=0;N<k.childCount;N+=1){const{colspan:x,colwidth:H}=k.child(N).attrs;for(let T=0;T<x;T+=1,P+=1){const A=a===P?n:H&&H[T];i+=A||s,A||(m=!1);const[L,E]=ts(s,A);j.push(["col",{style:`${L}: ${E}`}])}}const p=m?`${i}px`:"",u=m?"":`${i}px`;return{colgroup:["colgroup",{},...j],tableWidth:p,tableMinWidth:u}}function Bs(t,s){return t.createAndFill()}function Dn(t){if(t.cached.tableNodeTypes)return t.cached.tableNodeTypes;const s={};return Object.keys(t.nodes).forEach(a=>{const n=t.nodes[a];n.spec.tableRole&&(s[n.spec.tableRole]=n)}),t.cached.tableNodeTypes=s,s}function In(t,s,a,n,i){const m=Dn(t),j=[],k=[];for(let u=0;u<a;u+=1){const N=Bs(m.cell);if(N&&k.push(N),n){const P=Bs(m.header_cell);P&&j.push(P)}}const p=[];for(let u=0;u<s;u+=1)p.push(m.row.createChecked(null,n&&u===0?j:k));return m.table.createChecked(null,p)}function En(t){return t instanceof Js}const St=({editor:t})=>{const{selection:s}=t.state;if(!En(s))return!1;let a=0;const n=Et(s.ranges[0].$from,i=>i.type.name==="table");return n?.node.descendants(i=>{if(i.type.name==="table")return!1;["tableCell","tableHeader"].includes(i.type.name)&&(a+=1)}),a!==s.ranges.length?!1:(t.commands.deleteTable(),!0)};function _s(t,s){const a=t.mapping.map(s),n=Et(t.selection.$from,j=>j.type.name==="table");if(n?.pos===a)return;const i=t.doc.nodeAt(a);if(!i)return;const m=a+i.nodeSize-1;t.setSelection(as.near(t.doc.resolve(m),-1))}function $n(t){let s="",a=0;for(;a<t.length;){if(t[a]==="\\"&&a+1<t.length){s+=t[a]+t[a+1],a+=2;continue}if(t[a]!=="`"){s+=t[a++];continue}let n=0;for(;a+n<t.length&&t[a+n]==="`";)n+=1;let i=a+n,m=!1;for(;i<t.length;){if(t[i]!=="`"){i+=1;continue}let j=0;for(;i+j<t.length&&t[i+j]==="`";)j+=1;if(j===n){const k=t.slice(a+n,i);s+=t.slice(a,a+n)+k.replace(/\\\||\|/g,p=>p==="|"?"\\|":p)+t.slice(i,i+n),a=i+n,m=!0;break}i+=j}m||(s+=t.slice(a,a+n),a+=n)}return s}function Pn(t){return t.split(`
2`).map(s=>!s.includes("|")||!s.includes("`")?s:$n(s)).join(`
3`)}function Mn(t){return(t||"").replace(/\s+/g," ").trim()}function Fn(t,s,a={}){var n;const i=(n=a.cellLineSeparator)!==null&&n!==void 0?n:"�";if(!t||!t.content||t.content.length===0)return"";const m=[];t.content.forEach(T=>{const A=[];T.content&&T.content.forEach(L=>{let E="";L.content&&Array.isArray(L.content)&&L.content.length>1?E=L.content.map(D=>s.renderChildren(D)).join(i):E=L.content?s.renderChildren(L.content):"";const B=Mn(E.split(i).join(`
4`).replace(/[ \t]*\r?\n[ \t]*/g,"<br>")),U=L.type==="tableHeader",c=Cn(L.attrs);A.push({text:B,isHeader:U,align:c})}),m.push(A)});const j=m.reduce((T,A)=>Math.max(T,A.length),0);if(j===0)return"";const k=Array.from({length:j}).fill(0);m.forEach(T=>{for(let L=0;L<j;L+=1){var A;const E=(((A=T[L])===null||A===void 0?void 0:A.text)||"").length;E>k[L]&&(k[L]=E),k[L]<3&&(k[L]=3)}});const p=(T,A)=>
4T+" ".repeat(Math.max(0,A-T.length)),u=m[0],N=u.some(T=>T.isHeader),P=Array.from({length:j}).fill(null);m.forEach(T=>{for(let L=0;L<j;L+=1){var A;!P[L]&&(!((A=T[L])===null||A===void 0)&&A.align)&&(P[L]=T[L].align)}});let x=`
5`;const H=Array.from({length:j}).map((T,A)=>N&&u[A]&&u[A].text||"");return x+=`| ${H.map((T,A)=>p(T,k[A])).join(" | ")} |
6`,x+=`| ${k.map((T,A)=>{const L=Math.max(3,T),E=P[A];return E==="left"?`:${"-".repeat(L)}`:E==="right"?`${"-".repeat(L)}:`:E==="center"?`:${"-".repeat(L)}:`:"-".repeat(L)}).join(" | ")} |
7`,(N?m.slice(1):m).forEach(T=>{x+=`| ${Array.from({length:j}).fill(0).map((A,L)=>p(T[L]&&T[L].text||"",k[L])).join(" | ")} |
8`}),x}const ia=Rt.create({name:"table",addOptions(){return{HTMLAttributes:{},resizable:!1,renderWrapper:!1,handleWidth:5,cellMinWidth:25,View:An,lastColumnResizable:!0,allowTableNodeSelection:!1}},content:"tableRow+",tableRole:"table",isolating:!0,group:"block",parseHTML(){return[{tag:"table"}]},renderHTML({node:t,HTMLAttributes:s}){const{colgroup:a,tableWidth:n,tableMinWidth:i}=Ln(t,this.options.cellMinWidth),m=s.style;function j(){return m||(n?`width: ${n}`:`min-width: ${i}`)}const k=["table",Ke(this.options.HTMLAttributes,s,{style:j()}),a,["tbody",0]];return this.options.renderWrapper?["div",{class:"tableWrapper"},k]:k},parseMarkdown:(t,s)=>{const a=[],n=Array.isArray(t.align)?t.align:[];if(t.header){const i=[];t.header.forEach((m,j)=>{var k;const p=Ft((k=n[j])!==null&&k!==void 0?k:m.align),u=p?{align:p}:{};i.push(s.createNode("tableHeader",u,[{type:"paragraph",content:s.parseInline(m.tokens)}]))}),a.push(s.createNode("tableRow",{},i))}return t.rows&&t.rows.forEach(i=>{const m=[];i.forEach((j,k)=>{var p;const u=Ft((p=n[k])!==null&&p!==void 0?p:j.align),N=u?{align:u}:{};m.push(s.createNode("tableCell",N,[{type:"paragraph",content:s.parseInline(j.tokens)}]))}),a.push(s.createNode("tableRow",{},m))}),s.createNode("table",void 0,a)},renderMarkdown:(t,s)=>Fn(t,s),markdownTokenizer:{name:"table",level:"block",start:t=>{const s=t.split(`
9`);if(s.length<2)return-1;const a=s[1];return!/^[ \t|:]*-[ \t|:-]*$/.test(a)||!a.includes("|")?-1:s[0].includes("|")?0:-1},tokenize(t,s,a){const n=t.indexOf(`
10
11`),i=n>=0?t.slice(0,n):t,m=i.split(`
12`);if(m.length<2)return;const j=m[1];if(!/^[ \t|:]*-[ \t|:-]*$/.test(j)||!j.includes("|"))return;const k=Pn(i);if(k===i)return;const p=a.blockTokens(k)[0];if(p?.type!=="table"||!p.raw)return;const u=p.raw.split(`
13`).length,N=t.split(`
14`).slice(0,u).join(`
15`);return{...p,raw:N}}},addCommands(){return{insertTable:({rows:t=3,cols:s=3,withHeaderRow:a=!0}={})=>({tr:n,dispatch:i,editor:m})=>{const j=In(m.schema,t,s,a);if(i){const k=n.selection.from+1;n.replaceSelectionWith(j).scrollIntoView().setSelection(as.near(n.doc.resolve(k)))}return!0},addColumnBefore:()=>({state:t,dispatch:s})=>Nr(t,s),addColumnAfter:()=>({state:t,dispatch:s})=>jr(t,s),deleteColumn:()=>({state:t,dispatch:s})=>{const a=Et(t.selection.$from,n=>n.type.name==="table");return vr(t,s&&(n=>{a&&_s(n,a.pos),s(n)}))},addRowBefore:()=>({state:t,dispatch:s})=>yr(t,s),addRowAfter:()=>({state:t,dispatch:s})=>wr(t,s),deleteRow:()=>({state:t,dispatch:s})=>{const a=Et(t.selection.$from,n=>n.type.name==="table");return br(t,s&&(n=>{a&&_s(n,a.pos),s(n)}))},deleteTable:()=>({state:t,dispatch:s})=>fr(t,s),mergeCells:()=>({state:t,dispatch:s})=>ws(t,s),splitCell:()=>({state:t,dispatch:s})=>ys(t,s),toggleHeaderColumn:()=>({state:t,dispatch:s})=>vs("column")(t,s),toggleHeaderRow:()=>({state:t,dispatch:s})=>vs("row")(t,s),toggleHeaderCell:()=>({state:t,dispatch:s})=>xr(t,s),mergeOrSplit:()=>({state:t,dispatch:s})=>ws(t,s)?!0:ys(t,s),setCellAttribute:(t,s)=>({state:a,dispatch:n})=>gr(t,s)(a,n),goToNextCell:()=>({state:t,dispatch:s})=>bs(1)(t,s),goToPreviousCell:()=>({state:t,dispatch:s})=>bs(-1)(t,s),fixTables:()=>({state:t,dispatch:s})=>(s&&pr(t),!0),setCellSelection:t=>({tr:s,dispatch:a})=>{if(a){const n=Js.create(s.doc,t.anchorCell,t.headCell);s.setSelection(n)}return!0}}},addKeyboardShortcuts(){return{Tab:()=>this.editor.commands.goToNextCell()?!0:this.editor.can().addRowAfter()?this.editor.chain().addRowAfter().goToNextCell().run():!1,"Shift-Tab":()=>this.editor.commands.goToPreviousCell(),Backspace:St,"Mod-Backspace":St,Delete:St,"Mod-Delete":St}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[hr({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:this.options.View,lastColumnResizable:this.options.lastColumnResizable})]:[],mr({allowTableNodeSelection:this.options.allowTableNodeSelection})]},addNodeView(){const t=this.options.resizable&&this.editor.isEditable,s=this.options.View;return t||!s?null:({node:a,view:n,HTMLAttributes:i})=>{const m=Ke(this.options.HTMLAttributes,i);return new s(a,this.options.cellMinWidth,n,m)}},extendNodeSchema(t){const s={name:t.name,options:t.options,storage:t.storage};return{tableRole:Xa(Za(t,"tableRole",s))}}});Pe.create({name:"tableKit",addExtensions(){const t=[];return this.options.table!==!1&&t.push(ia.configure(this.options.table)),this.options.tableCell!==!1&&t.push(aa.configure(this.options.tableCell)),this.options.tableHeader!==!1&&t.push(ra.configure(this.options.tableHeader)),this.options.tableRow!==!1&&t.push(na.configure(this.options.tableRow)),t}});function Rn(){try{return bn}catch{return null}}function On(t,s){if(t&&typeof t.serializeForClipboard=="function")return t.serializeForClipboard(s);const a=Rn();if(a&&typeof a?.__serializeForClipboard=="function")return a.__serializeForClipboard(t,s);throw new Error("No supported clipboard serialization method found.")}function Hn(t){const s=t.getBoundingClientRect(),a=t.closest('[role="dialog"]');if(a&&window.getComputedStyle(a).transform!=="none"){const n=a.getBoundingClientRect();
15return{top:s.top-n.top,left:s.left-n.left,width:s.width}}return{top:s.top,left:s.left,width:s.width}}function zs(t,s){const a=["li","p:not(:first-child)","pre","blockquote","h1","h2","h3","h4","h5","h6",...s.customNodes.map(n=>`[data-type=${n}]`)].join(", ");return document.elementsFromPoint(t.x,t.y).find(n=>n.parentElement?.matches?.(".ProseMirror")||n.matches(a))}function Bn(t,s,a){const n=t.getBoundingClientRect();return s.posAtCoords({left:n.left+50+a.dragHandleWidth,top:n.top+1})?.inside}function Ws(t,s){const a=s.state.doc.resolve(t);return a.depth>1?a.before(a.depth):t}function _n(t){let s="";function a(k,p){if(p.focus(),!k.dataTransfer)return;const u=zs({x:k.clientX+50+t.dragHandleWidth,y:k.clientY},t);if(!(u instanceof Element))return;let N=Bn(u,p,t);if(N==null||N<0)return;N=Ws(N,p);const{from:P,to:x}=p.state.selection,H=P-x,T=Ws(P,p);let A=!1;const L=p.state.doc.resolve(T);if(L.node().type.name==="doc")A=!0;else{const D=Be.create(p.state.doc,L.before());A=!(N+1>=D.$from.pos&&N<=D.$to.pos)}let E=p.state.selection;if(!A&&H!==0&&!(p.state.selection instanceof Be)){const D=Be.create(p.state.doc,x-1);E=as.create(p.state.doc,N,D.$to.pos)}else if(E=Be.create(p.state.doc,N),E.node.type.isInline||E.node.type.name==="tableRow"){let D=p.state.doc.resolve(E.from);E=Be.create(p.state.doc,D.before())}p.dispatch(p.state.tr.setSelection(E)),p.state.selection instanceof Be&&p.state.selection.node.type.name==="listItem"&&(s=u.parentElement.tagName);const B=p.state.selection.content(),{dom:U,text:c}=On(p,B);k.dataTransfer.clearData(),k.dataTransfer.setData("text/html",U.innerHTML),k.dataTransfer.setData("text/plain",c),k.dataTransfer.effectAllowed="copyMove",k.dataTransfer.setDragImage(u,0,0),p.dragging={slice:B,move:k.ctrlKey}}let n=null;function i(){n&&n.classList.add("hide")}function m(){n&&n.classList.remove("hide")}function j(k){if(k.target instanceof Element){const p=k.relatedTarget;if(p?.classList.contains("tiptap")||p?.classList.contains("drag-handle"))return}i()}return new er({key:new tr(t.pluginKey),view:k=>{const p=t.dragHandleSelector?document.querySelector(t.dragHandleSelector):null;n=p??document.createElement("div"),n.draggable=!0,n.dataset.dragHandle="",n.classList.add("drag-handle");function u(P){a(P,k)}n.addEventListener("dragstart",u);function N(P){i();let x=window.scrollY;P.clientY<t.scrollTreshold?window.scrollTo({top:x-30,behavior:"smooth"}):window.innerHeight-P.clientY<t.scrollTreshold&&window.scrollTo({top:x+30,behavior:"smooth"})}return n.addEventListener("drag",N),i(),p||k?.dom?.parentElement?.appendChild(n),k?.dom?.parentElement?.addEventListener("mouseout",j),{destroy:()=>{p||n?.remove?.(),n?.removeEventListener("drag",N),n?.removeEventListener("dragstart",u),n=null,k?.dom?.parentElement?.removeEventListener("mouseout",j)}}},props:{handleDOMEvents:{mousemove:(k,p)=>{if(!k.editable)return;const u=zs({x:p.clientX+50+t.dragHandleWidth,y:p.clientY}
15,t),N=u?.closest(".not-draggable"),P=t.excludedTags.concat(["ol","ul"]).join(", ");if(!(u instanceof Element)||u.matches(P)||N){i();return}const x=window.getComputedStyle(u),H=parseInt(x.lineHeight,10),T=isNaN(H)?parseInt(x.fontSize)*1.2:H,A=parseInt(x.paddingTop,10),L=Hn(u);L.top+=(T-24)/2,L.top+=A,u.matches("ul:not([data-type=taskList]) li, ol li")&&(L.left-=t.dragHandleWidth),L.width=t.dragHandleWidth,n&&(n.style.left=`${L.left-L.width}px`,n.style.top=`${L.top}px`,m())},keydown:()=>{i()},mousewheel:()=>{i()},dragstart:k=>{k.dom.classList.add("dragging")},drop:(k,p)=>{k.dom.classList.remove("dragging"),i();let u=null;const N=k.posAtCoords({left:p.clientX,top:p.clientY});if(!N||(k.state.selection instanceof Be&&(u=k.state.selection.node),!u))return;const x=k.state.doc.resolve(N.pos).parent.type.name==="listItem";if(k.state.selection instanceof Be&&k.state.selection.node.type.name==="listItem"&&!x&&s=="OL"){const H=k.state.schema.nodes.orderedList?.createAndFill(null,u),T=new sr(ar.from(H),0,0);k.dragging={slice:T,move:p.ctrlKey}}},dragend:k=>{k.dom.classList.remove("dragging")}}}})}const zn=Pe.create({name:"globalDragHandle",addOptions(){return{dragHandleWidth:20,scrollTreshold:100,excludedTags:[],customNodes:[]}},addProseMirrorPlugins(){return[_n({pluginKey:"globalDragHandle",dragHandleWidth:this.options.dragHandleWidth,scrollTreshold:this.options.scrollTreshold,dragHandleSelector:this.options.dragHandleSelector,excludedTags:this.options.excludedTags,customNodes:this.options.customNodes})]}}),Wn=20,oa=(t,s=0)=>{const a=[];return!t.children.length||s>Wn||Array.from(t.children).forEach(n=>{n.tagName==="SPAN"?a.push(n):n.children.length&&a.push(...oa(n,s+1))}),a},qn=t=>{if(!t.children.length)return;const s=oa(t);s&&s.forEach(a=>{var n;const i=a.getAttribute("style"),m=(n=a.parentElement)===null||n===void 0||(n=n.closest("span"))===null||n===void 0?void 0:n.getAttribute("style");a.setAttribute("style",`${m};${i}`)})},la=Vs.create({name:"textStyle",priority:101,addOptions(){return{HTMLAttributes:{},mergeNestedSpanStyles:!0}},parseHTML(){return[{tag:"span",consuming:!1,getAttrs:t=>t.hasAttribute("style")?(this.options.mergeNestedSpanStyles&&qn(t),{}):!1}]},renderHTML({HTMLAttributes:t}){return["span",Ke(this.options.HTMLAttributes,t),0]},addCommands(){return{toggleTextStyle:t=>({commands:s})=>s.toggleMark(this.name,t),removeEmptyTextStyle:()=>({tr:t})=>{const{selection:s}=t;return t.doc.nodesBetween(s.from,s.to,(a,n)=>{if(!a.isInline)return!0;a.marks.filter(i=>i.type===this.type).some(i=>Object.values(i.attrs).some(m=>!!m))||t.removeMark(n,n+a.nodeSize,this.type)}),!0}}}}),Un=Pe.create({name:"backgroundColor",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{backgroundColor:{default:null,parseHTML:t=>{var s;const a=(s=it(t,"background-color"))!==null&&s!==void 0?s:t.style.backgroundColor;return a?.replace(/['"]+/g,"")},renderHTML:t=>t.backgroundColor?{style:`background-color: ${t.backgroundColor}`}:{}}}}]},addCommands(){return{setBackgroundColor:t=>({chain:s})=>s().setMark("textStyle",{backgroundColor:t}).run(),unsetBackgroundColor:()=>({chain:t})=>t().setMark("textStyle",{backgroundColor:null}).removeEmptyTextStyle().run()}}}),ca=Pe.create({name:"color",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{color:{default:null,parseHTML:t=>{var s;const a=(s=it(t,"color"))!==null&&s!==void 0?s:t.style.color;return a?.replace(/['"]+/g,"")},renderHTML:t=>t.color?{style:`color: ${t.color}`}:{}}}}]},addCommands(){return{setColor:t=>({chain:s})=>s().setMark("textStyle",{color:t}).run(),unsetColor:()=>({chain:t})=>t().setMark("textStyle",{color:null}).removeEmptyTextStyle().run()}}}),da=Pe.create({name:"fontFamily",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{fontFamily:{default:null,parseHTML:t=>{var s;return(s=it(t,"font-family"))!==null&&s!==void 0?s:t.style.fontFamily},renderHTML:t=>t.fontFamily?{style:`font-family: ${t.fontFamily}`}:{}}}}]},addCommands(){return{setFontFamily:t=>({chain:s})=>s().setMark("textStyle",{fontFamily:t}).run(),unsetFontFamily:()=>({chain:t})=>t().setMark("textStyle",{fontFamily:null}).removeEmptyTextStyle().run()}}}),Kn=Pe.create({name:"fontSize",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{fontSize:{default:null,parseHTML:t=>{var s;return(s=it(t,"font-size"))!==null&&s!==void 0?s:t.style.fontSize},renderHTML:t=>t.fontSize?{style:`font-size: ${t.fontSize}`}:{}}}}]},addCommands(){return{setFontSize:t=>({chain:s})=>s().setMark("textStyle",{fontSize:t}).run(),unsetFontSize:()=>({chain:t})=>t().setMark("textStyle",{fontSize:null}).removeEmptyTextStyle().run()}}}),Gn=Pe.create({name:"lineHeight",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{lineHeight:{default:null,parseHTML:t=>{var s;return(s=it(t,"line-height"))!==null&&s!==void 0?s:t.style.lineHeight},renderHTML:t=>t.lineHeight?{style:`line-height: ${t.lineHeight}`}:{}}}}]},addCommands(){return{setLineHeight:t=>({chain:s})=>s().setMark("textStyle",{lineHeight:t}).run(),unsetLineHeight:()=>({chain:t})=>t().setMark("textStyle",{lineHeight:null}).removeEmptyTextStyle().run()}}});Pe.create({name:"textStyleKit",addExtensions(){const t=[];return this.options.backgroundColor!==!1&&t.push(Un.configure(this.options.backgroundColor)),this.options.color!==!1&&t.push(ca.configure(this.options.color)),this.options.fontFamily!==!1&&t.push(da.configure(this.options.fontFamily)),this.options.fontSize!==!1&&t.push(Kn.configure(this.options.fontSize)),this.options.lineHeight!==!1&&t.push(Gn.configure(this.options.lineHeight)),this.options.textStyle!==!1&&t.push(la.configure(this.options.textStyle)),t}});var Vn=da,Jn=ca;const Yn=/(?:^|\s)(==(?!\s+==)((?:[^=]+))==(?!\s+==))$/,Qn=/(?:^|\s)(==(?!\s+==)((?:[^=]+))==(?!\s+==))/g,Xn=Vs.create({name:"highlight",addOptions(){return{multicolor:!1,HTMLAttributes:{}}},addAttributes(){return this.options.multicolor?{color:{default:null,parseHTML:t=>t.getAttribute("data-color")||it(t,"background-color")||t.style.backgroundColor,renderHTML:t=>t.color?{"data-color":t.color,style:`background-color: ${t.color}; color: inherit`}:{}}}:{}},parseHTML(){return[{tag:"mark"}]},renderHTML({HTMLAttributes:t}){return["mark",Ke(this.options.HTMLAttributes,t),0]},renderMarkdown:(t,s)=>`==${s.renderChildren(t)}==`,parseMarkdown:(t,s)=>s.applyMark("highlight",s.parseInline(t.tokens||[])),markdownTokenizer:{name:"highlight",level:"inline",start:t=>t.indexOf("=="),tokenize(t,s,a){const n=/^(==)([^=]+)(==)/.exec(t);if(n){const i=n[2].trim(),m=a.inlineTokens(i);return{type:"highlight",raw:n[0],text:i,tokens:m}}}},addCommands(){return{setHighlight:t=>({commands:s})=>s.setMark(this.name,t),toggleHighlight:t=>({commands:s})=>s.toggleMark(this.name,t),unsetHighlight:()=>({commands:t})=>t.unsetMark(this.name)}}
15,addKeyboardShortcuts(){return{"Mod-Shift-h":()=>this.editor.commands.toggleHighlight()}},addInputRules(){return[nr({find:Yn,type:this.type})]},addPasteRules(){return[rr({find:Qn,type:this.type})]}});var Zn=Xn;const ei=Pe.create({name:"textAlign",addOptions(){return{types:[],alignments:["left","center","right","justify"],defaultAlignment:null}},addGlobalAttributes(){return[{types:this.options.types,attributes:{textAlign:{default:this.options.defaultAlignment,parseHTML:t=>{const s=t.style.textAlign;return this.options.alignments.includes(s)?s:this.options.defaultAlignment},renderHTML:t=>t.textAlign?{style:`text-align: ${t.textAlign}`}:{}}}}]},addCommands(){return{setTextAlign:t=>({commands:s})=>this.options.alignments.includes(t)?this.options.types.map(a=>s.updateAttributes(a,{textAlign:t})).some(a=>a):!1,unsetTextAlign:()=>({commands:t})=>this.options.types.map(s=>t.resetAttributes(s,"textAlign")).some(s=>s),toggleTextAlign:t=>({editor:s,commands:a})=>this.options.alignments.includes(t)?s.isActive({textAlign:t})?a.unsetTextAlign():a.setTextAlign(t):!1}},addKeyboardShortcuts(){return{"Mod-Shift-l":()=>this.editor.commands.setTextAlign("left"),"Mod-Shift-e":()=>this.editor.commands.setTextAlign("center"),"Mod-Shift-r":()=>this.editor.commands.setTextAlign("right"),"Mod-Shift-j":()=>this.editor.commands.setTextAlign("justify")}}});var ti=ei;function qe(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function qs(t){return JSON.stringify(t).replace(/'/g,"&#39;")}function ua(t){switch(t.type){case"paragraph":return`<p>${t.content||""}</p>`;case"heading":return`<h${t.level}>${t.content||""}</h${t.level}>`;case"blockquote":return t.attribution?`<div data-custom-block='${qs(t)}'></div>`:`<blockquote><p>${t.content||""}</p></blockquote>`;case"bulletList":return`<ul>${(t.items||[]).map(s=>typeof s=="string"?`<li>${s}</li>`:s&&typeof s=="object"?`<li>${s.content||s.text||s.title||""}</li>`:"").join("")}</ul>`;case"numberedList":return`<ol>${(t.items||[]).map(s=>{if(typeof s=="string")return`<li>${s}</li>`;if(s&&typeof s=="object"){const a=s;return a.title?`<li><strong>${qe(String(a.title))}</strong>: ${a.content||""}</li>`:`<li>${a.content||a.text||""}</li>`}return""}).join("")}</ol>`;case"divider":return"<hr>";case"image":{const s=t.width?` width="${t.width}"`:"",a=t.height?` height="${t.height}"`:"",n=t.align?` data-align="${t.align}"`:"",i=t.linkUrl?` data-href="${qe(t.linkUrl)}"`:"",m=`<img src="${t.url}" alt="${qe(t.alt||"")}" title="${qe(t.caption||"")}"${s}${a}${n}${i}>`;return t.linkUrl?`<a href="${qe(t.linkUrl)}" target="_blank" rel="noopener noreferrer">${m}</a>`:m}case"columnLayout":{const s=t.columns??2,a=(t.columnBlocks||[]).map(n=>`<div data-column-item="">${n.map(m=>ua(m)).join("")}</div>`).join("");return`<div data-column-layout="${s}">${a}</div>`}case"spacer":return`<div data-spacer="${t.height??40}" style="height:${t.height??40}px"></div>`;case"codeBlock":return`<pre><code>${qe(t.content||"")}</code></pre>`;case"tableBlock":{const s=t.headers&&t.headers.length>0?`<thead><tr>${t.headers.map(n=>`<th>${n}</th>`).join("")}</tr></thead>`:"",a=(t.rows||[]).map(n=>`<tr>${n.map(i=>`<td>${i}</td>`).join("")}</tr>`).join("");return`<table>${s}<tbody>${a}</tbody></table>`}default:return`<div data-custom-block='${qs(t)}'></div>`}}function si(t){return!t||t.length===0?"<p></p>":t.map(ua).join("")}function et(t){return t?t.map(s=>{if(s.type==="hardBreak")return"<br>";if(s.type!=="text")return"";let a=qe(s.text||"");const n=s.marks||[];for(const i of n)switch(i.type){case"bold":a=`<strong>${a}</strong>`;break;case"italic":a=`<em>${a}</em>`;break;case"strike":a=`<s>${a}</s>`;break;case"code":a=`<code>${a}</code>`;break;case"link":a=`<a href="${i.attrs?.href||""}" target="_blank" rel="noopener noreferrer">${a}</a>`;break}return a}).join(""):""}function ha(t){switch(t.type){case"paragraph":return[{type:"paragraph",content:et(t.content)}];case"heading":{const s=t.attrs?.level===3?3:2,a=et(t.content);return[{type:"heading",level:s,content:a}]}case"blockquote":{const s=t.content||[];return[{type:"blockquote",content:s[0]?et(s[0].content):""}]}case"bulletList":return[{type:"bulletList",items:(t.content||[]).map(a=>{const n=a.content?.[0];return n?et(n.content):""})}];case"orderedList":return[{type:"numberedList",items:(t.content||[]).map(a=>{const n=a.content?.[0];if(!n)return{title:"",content:""};const i=et(n.content),m=i.indexOf(": ");return m>0?{title:i.slice(0,m).replace(/<[^>]+>/g,""),content:i.slice(m+2)}:{title:"",content:i}})}];case"horizontalRule":return[{type:"divider"}];case"image":return[{type:"image",url:t.attrs?.src||"",alt:t.attrs?.alt||"",caption:t.attrs?.title||void 0,width:t.attrs?.width||void 0,height:t.attrs?.height||void 0,align:t.attrs?.["data-align"]||void 0,linkUrl:t.attrs?.href||void 0}];case"codeBlock":return[{type:"codeBlock",content:(t.content||[]).map(a=>a.text||"").join("")}];case"columnLayout":{const s=t.attrs?.columns??2,a=(t.content||[]).map(n=>(n.content||[]).flatMap(i=>ha(i)));return[{type:"columnLayout",columns:s,columnBlocks:a}]}case"spacer":return[{type:"spacer",height:t.attrs?.height??40}];case"table":{const s=[];let a=[],n=!1;
15return(t.content||[]).forEach(i=>{const m=i.content?.some(k=>k.type==="tableHeader"),j=(i.content||[]).map(k=>et(k.content?.[0]?.content));m&&!n?(a=j,n=!0):s.push(j)}),[{type:"tableBlock",headers:a,rows:s}]}case"customBlock":try{return[JSON.parse(t.attrs?.data||"{}")]}catch{return[]}default:return[]}}function ai(t){if(!t.content)return[];const s=t.content.flatMap(ha),a=s.findIndex(i=>i.type!=="paragraph"||i.content?.trim()!==""),n=[...s].reverse().findIndex(i=>i.type!=="paragraph"||i.content?.trim()!=="");return a===-1?[]:s.slice(a,s.length-n)}function ri({open:t,onClose:s,onInsert:a,token:n}){const{toast:i}=De(),m=h.useRef(null),[j,k]=h.useState(!1),[p,u]=h.useState("");if(!t)return null;const N=async x=>{if(!x.type.startsWith("image/")){i({title:"Invalid file",description:"Please select an image file.",variant:"destructive"});return}k(!0);try{const H=new FormData;H.append("file",x);const T=await fetch("/api/admin/blog/upload-image",{method:"POST",headers:{...oe()},body:H});if(!T.ok){const L=await T.json().catch(()=>({}));throw new Error(L.error||"Upload failed")}const{url:A}=await T.json();a(A),u(""),s()}catch(H){i({title:"Upload failed",description:H instanceof Error?H.message:"Could not upload image.",variant:"destructive"})}finally{k(!1),m.current&&(m.current.value="")}},P=()=>{const x=p.trim();x&&(a(x),u(""),s())};return e.jsxs("div",{className:"fixed inset-0 z-[10001] flex items-center justify-center p-4",onClick:s,children:[e.jsx("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-sm"}),e.jsxs("div",{className:"relative bg-card rounded-2xl shadow-2xl w-full max-w-sm",onClick:x=>x.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-4 border-b border-border",children:[e.jsx("h3",{className:"font-semibold text-foreground",children:"Insert Image"}),e.jsx("button",{onClick:s,className:"p-1.5 rounded-lg hover:bg-secondary text-muted-foreground hover:text-foreground","data-testid":"button-image-dialog-close",children:e.jsx(Ae,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:"px-5 py-5 space-y-4",children:[e.jsxs("div",{children:[e.jsx("button",{type:"button",disabled:j,onClick:()=>m.current?.click(),className:"w-full border-2 border-dashed border-border rounded-xl py-6 flex flex-col items-center gap-2 text-muted-foreground hover:border-accent-gold hover:text-accent-gold-ink hover:bg-accent-gold/10 transition-colors disabled:opacity-50 disabled:cursor-not-allowed","data-testid":"button-upload-image",children:j?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"w-6 h-6 border-2 border-border border-t-accent-gold rounded-full animate-spin"}),e.jsx("span",{className:"text-sm font-medium",children:"Uploading…"})]}):e.jsxs(e.Fragment,{children:[e.jsx($t,{className:"w-6 h-6"}),e.jsx("span",{className:"text-sm font-medium",children:"Upload from device"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"JPG, PNG, GIF, WebP, SVG"})]})}),e.jsx("input",{ref:m,type:"file",accept:"image/*",className:"hidden",onChange:x=>{const H=x.target.files?.[0];H&&N(H)},"data-testid":"input-image-file"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex-1 h-px bg-border"}),e.jsx("span",{className:"text-xs text-muted-foreground font-medium",children:"or"}),e.jsx("div",{className:"flex-1 h-px bg-border"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-xs font-medium text-muted-foreground",children:"Paste image URL"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(rs,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground pointer-events-none"}),e.jsx("input",{type:"text",value:p,onChange:x=>u(x.target.value),onKeyDown:x=>{x.key==="Enter"&&(x.preventDefault(),P())},placeholder:"https://…",className:"w-full pl-9 pr-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:border-accent-gold text-foreground","data-testid":"input-image-url"})]}),e.jsx("button",{type:"button",onClick:P,disabled:!p.trim(),className:"px-4 py-2 rounded-lg bg-accent-gold hover:bg-accent-gold-light text-navy-deep text-sm font-semibold transition-colors disabled:opacity-40 disabled:cursor-not-allowed","data-testid":"button-insert-image-url",children:"Insert"})]})]})]})]})]})}const ni=Pe.create({name:"fontSize",addGlobalAttributes(){return[{types:["textStyle"],attributes:{fontSize:{default:null,parseHTML:t=>t.style.fontSize||null,renderHTML:t=>t.fontSize?{style:`font-size: ${t.fontSize}`}:{}}}}]},addCommands(){return{setFontSize:t=>({chain:s})=>s().setMark("textStyle",{fontSize:t}).run(),unsetFontSize:()=>({chain:t})=>t().setMark("textStyle",{fontSize:null}).removeEmptyTextStyle().run()}}}),ii=[{label:"Inter (Default)",value:""},{label:"Playfair Display",value:"'Playfair Display', serif"},{label:"Georgia",value:"Georgia, serif"},{label:"Times New Roman",value:"'Times New Roman', serif"},{label:"Arial",value:"Arial, sans-serif"},{label:"Courier New",value:"'Courier New', monospace"}],oi=["10px","11px","12px","13px","14px","15px","16px","18px","20px","22px","24px","28px","32px","36px","42px","48px","56px","64px","72px"];function li({blocks:t,onChange:s,articleTitle:a,onTitleChange:n,token:i}){const[m,j]=h.useState(!1),[k,p]=h.useState({top:0,left:0}),[u,N]=h.useState(""),[P,x]=h.useState(0),[H,T]=h.useState(null),[A,L]=h.useState(!1),[E,B]=h.useState({top:0,left:0}),[U,c]=h.useState({visible:!1,top:0,left:0}),[D,$]=h.useState({visible:!1,top:0,left:0}),[F,J]=h.useState({visible:!1,top:0,left:0}),[re,I]=h.useState(!1),[o,S]=h.useState({visible:!1,top:0,left:0,src:"",nodePos:-1}),[l,b]=h.useState(null),M=h.useRef(null),W=h.useRef(null),te=h.useRef(null),V=h.useRef(!1),ne=h.useRef(!1),Y=h.useRef(null),we=h.useRef(null),w=h.useCallback((d,G)=>{T({data:d,save:G})},[]),R=js.filter(d=>!u||d.label.toLowerCase().includes(u)||d.key.includes(u)),f=h.useCallback(d=>{const G=d.editor;if(!G)return;const{selection:le}=G.state,{empty:de,from:se,to:ye}=le;
15if((le.$from.nodeAfter||le.$anchor.parent)?.type.name==="image"){S({visible:!1,top:0,left:0,src:"",nodePos:-1}),c({visible:!1,top:0,left:0}),$({visible:!1,top:0,left:0});return}if(de)c({visible:!1,top:0,left:0});else try{const ue=G.view.coordsAtPos(se),Me=G.view.coordsAtPos(ye),Le=(ue.left+Me.left)/2;c({visible:!0,top:ue.top-44,left:Le-160})}catch{c({visible:!1,top:0,left:0})}if(de)try{const ue=le.$from.node();if(ue.type.name==="paragraph"&&ue.textContent===""){const Le=G.view.coordsAtPos(se);$({visible:!0,top:Le.top+(Le.bottom-Le.top)/2-14,left:Le.left-44})}else $({visible:!1,top:0,left:0})}catch{$({visible:!1,top:0,left:0})}else $({visible:!1,top:0,left:0});try{if(G.isActive("table")){const Me=G.view.coordsAtPos(se);J({visible:!0,top:Me.top-44,left:Math.max(8,Me.left)})}else J({visible:!1,top:0,left:0})}catch{J({visible:!1,top:0,left:0})}},[]),r=ir({extensions:[cr.configure({heading:{levels:[1,2,3]},hardBreak:{keepMarks:!1}}),ur.configure({placeholder:"Start writing your article…"}),dr.configure({openOnClick:!1,autolink:!0}),Dr.configure({inline:!1,allowBase64:!1}),lr,kr,la,Vn,Jn,ni,Zn.configure({multicolor:!0}),ti.configure({types:["heading","paragraph"]}),Cr,Sr,Tr,Ar,ia.configure({resizable:!1}),na,aa,ra,zn.configure({dragHandleWidth:20}),Lr],onUpdate({editor:d}){const{$from:G}=d.state.selection,le=G.node();if(le.type.name==="paragraph"){const de=le.textContent;if(de==="/"){const se=d.view.coordsAtPos(G.pos);p({top:se.bottom+4,left:se.left}),j(!0),V.current=!0,N(""),x(0)}else V.current&&de.startsWith("/")?(N(de.slice(1).toLowerCase()),x(0)):V.current&&!de.startsWith("/")&&(j(!1),V.current=!1,N(""))}else V.current&&(j(!1),V.current=!1,N(""));s(ai(d.getJSON())),f({editor:d})},onSelectionUpdate({editor:d}){f({editor:d});const{selection:G}=d.state,le=G.$anchor.nodeAfter||G.$anchor.parent;if(le?.type.name==="image")try{const de=d.view.coordsAtPos(G.$anchor.pos),se=G.$anchor.pos;S({visible:!0,top:de.top-44,left:de.left,src:le.attrs.src||"",nodePos:se}),c({visible:!1,top:0,left:0})}catch{S({visible:!1,top:0,left:0,src:"",nodePos:-1})}else S({visible:!1,top:0,left:0,src:"",nodePos:-1})},onBlur(){setTimeout(()=>{c({visible:!1,top:0,left:0}),$({visible:!1,top:0,left:0}),S({visible:!1,top:0,left:0,src:"",nodePos:-1})},150)}});h.useEffect(()=>{r&&(r.storage.dropToken=i)},[r,i]),h.useEffect(()=>{V.current=m},[m]),h.useEffect(()=>{if(r&&!ne.current){ne.current=!0;const d=si(t);r.commands.setContent(d)}},[r]),h.useEffect(()=>{Y.current&&(Y.current.style.height="auto",Y.current.style.height=`${Y.current.scrollHeight}px`)},[a]);const v=h.useCallback(d=>{if(j(!1),V.current=!1,N(""),L(!1),!r)return;const{$from:G}=r.state.selection,le=G.start(),de=G.end(),se=r.chain().focus().deleteRange({from:le,to:de});switch(d){case"paragraph":se.run();break;case"heading2":se.setNode("heading",{level:2}).run();break;case"heading3":se.setNode("heading",{level:3}).run();break;case"bulletList":se.toggleBulletList().run();break;case"numberedList":se.toggleOrderedList().run();break;case"blockquote":se.setBlockquote().run();break;case"divider":se.setHorizontalRule().run();break;case"image":{se.run(),M.current=ye=>{r.chain().focus().setImage({src:ye}).run()},I(!0);break}case"twoColumns":{se.run(),r.chain().focus().insertContent({type:"columnLayout",attrs:{columns:2},content:[{type:"columnItem",content:[{type:"paragraph",content:[]}]},{type:"columnItem",content:[{type:"paragraph",content:[]}]}]}).run();break}case"threeColumns":{se.run(),r.chain().focus().insertContent({type:"columnLayout",attrs:{columns:3},content:[{type:"columnItem",content:[{type:"paragraph",content:[]}]},{type:"columnItem",content:[{type:"paragraph",content:[]}]},{type:"columnItem",content:[{type:"paragraph",content:[]}]}]}).run();break}case"spacer":{se.run(),r.chain().focus().insertContent({type:"spacer",attrs:{height:40}}).run();break}case"table":{se.run(),r.chain().focus().insertTable({rows:3,cols:3,withHeaderRow:!0}).run();break}case"codeBlock":{se.toggleCodeBlock().run();break}default:{const ye=Ir[d];ye&&(se.run(),r.chain().focus().insertContent({type:"customBlock",attrs:{data:JSON.stringify(ye)}}).run());break}}},[r]),_=h.useCallback(d=>
15{if(!m)return;const G=R;d.key==="ArrowDown"?(d.preventDefault(),x(le=>(le+1)%G.length)):d.key==="ArrowUp"?(d.preventDefault(),x(le=>(le-1+G.length)%G.length)):d.key==="Enter"?(d.preventDefault(),G[P]&&v(G[P].key)):d.key==="Escape"&&(d.preventDefault(),j(!1),V.current=!1,N(""))},[m,R,P,v]),K=d=>{if(!r||o.nodePos<0)return;const{state:G,view:le}=r;G.doc.nodesBetween(o.nodePos,o.nodePos+1,(de,se)=>{if(de.type.name==="image"){const ye=G.tr.setNodeMarkup(se,void 0,{...de.attrs,"data-align":d});le.dispatch(ye)}})},g=()=>{if(!r||o.nodePos<0)return;const{state:d,view:G}=r;d.doc.nodesBetween(o.nodePos,o.nodePos+1,(le,de)=>{if(le.type.name==="image"){const se=d.tr.delete(de,de+le.nodeSize);G.dispatch(se),S({visible:!1,top:0,left:0,src:"",nodePos:-1})}})},C=r?.isActive("heading",{level:1}),X=r?.isActive("heading",{level:2}),Q=r?.isActive("heading",{level:3}),ae=r?.storage.characterCount?.words()??0,O=r?.storage.characterCount?.characters()??0,pe=Math.max(1,Math.ceil(ae/200)),ce=r?.getAttributes("textStyle")?.fontSize??"",be=r?.getAttributes("textStyle")?.fontFamily??"",fe=r?.getAttributes("textStyle")?.color??"#000000",ke=r?.getAttributes("highlight")?.color??"#fef08a",Ne=d=>`p-1.5 rounded transition-colors ${d?"bg-accent-gold text-navy-deep":"text-white/80 hover:bg-white/10"}`,xe=d=>`p-1.5 rounded transition-colors ${d?"bg-accent-gold/15 text-accent-gold-ink":"text-muted-foreground hover:bg-muted hover:text-foreground"}`,je=e.jsx("div",{className:"w-px h-5 bg-border mx-0.5 shrink-0"});return e.jsx(Er.Provider,{value:{openEdit:w},children:e.jsxs("div",{className:"prose-editor-root",onKeyDown:_,children:[e.jsxs("div",{ref:we,className:"bg-card rounded-xl shadow-sm border border-border overflow-visible",children:[r&&e.jsxs("div",{className:"sticky top-0 z-20 flex flex-wrap items-center gap-0.5 px-3 py-1.5 border-b border-border bg-card rounded-t-xl",children:[e.jsx("select",{value:be,onChange:d=>{const G=d.target.value;G?r.chain().focus().setFontFamily(G).run():r.chain().focus().unsetFontFamily().run()},className:"text-xs text-foreground bg-transparent border border-border rounded px-1.5 py-1 h-7 cursor-pointer hover:border-muted-foreground focus:outline-none focus:border-accent-gold max-w-[130px]",title:"Font family",children:ii.map(d=>e.jsx("option",{value:d.value,style:{fontFamily:d.value||void 0},children:d.label},d.value))}),e.jsxs("select",{value:ce,onChange:d=>{const G=d.target.value;G?r.chain().focus().setFontSize(G).run():r.chain().focus().unsetFontSize().run()},className:"text-xs text-foreground bg-transparent border border-border rounded px-1.5 py-1 h-7 w-[68px] cursor-pointer hover:border-muted-foreground focus:outline-none focus:border-accent-gold",title:"Font size",children:[e.jsx("option",{value:"",children:"Size"}),oi.map(d=>e.jsx("option",{value:d,children:d.replace("px","")},d))]}),je,e.jsx("button",{onMouseDown:d=>{d.preventDefault(),r.chain().focus().toggleHeading({level:1}).run()},className:`px-2 py-0.5 rounded text-xs font-bold h-7 transition-colors ${C?"bg-accent-gold/15 text-accent-gold-ink":"text-muted-foreground hover:bg-muted"}`,title:"Heading 1",children:"H1"}),e.jsx("button",{onMouseDown:d=>{d.preventDefault(),r.chain().focus().toggleHeading({level:2}).run()},className:`px-2 py-0.5 rounded text-xs font-bold h-7 transition-colors ${X?"bg-accent-gold/15 text-accent-gold-ink":"text-muted-foreground hover:bg-muted"}`,title:"Heading 2",children:"H2"}),e.jsx("button",{onMouseDown:d=>{d.preventDefault(),r.chain().focus().toggleHeading({level:3}).run()},className:`px-2 py-0.5 rounded text-xs font-bold h-7 transition-colors ${Q?"bg-accent-gold/15 text-accent-gold-ink":"text-muted-foreground hover:bg-muted"}`,title:"Heading 3",children:"H3"}),je,e.jsx("button",{onMouseDown:d=>{d.preventDefault(),r.chain().focus().toggleBold().run()},className:xe(r.isActive("bold")),title:"Bold",children:e.jsx(Ns,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onMouseDown:d=>{d.preventDefault(),r.chain().focus().toggleItalic().run()},className:xe(r.isActive("italic")),title:"Italic",children:e.jsx(ks,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onMouseDown:d=>{d.preventDefault(),r.chain().focus().toggleUnderline().run()},className:xe(r.isActive("underline")),title:"Underline",children:e.jsx(Cs,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onMouseDown:d=>{d.preventDefault(),r.chain().focus().toggleStrike().run()}
15,className:xe(r.isActive("strike")),title:"Strikethrough",children:e.jsx(Ss,{className:"w-3.5 h-3.5"})}),je,e.jsx("button",{onMouseDown:d=>{d.preventDefault(),r.chain().focus().setTextAlign("left").run()},className:xe(r.isActive({textAlign:"left"})),title:"Align left",children:e.jsx(Ts,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onMouseDown:d=>{d.preventDefault(),r.chain().focus().setTextAlign("center").run()},className:xe(r.isActive({textAlign:"center"})),title:"Align center",children:e.jsx(Ps,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onMouseDown:d=>{d.preventDefault(),r.chain().focus().setTextAlign("right").run()},className:xe(r.isActive({textAlign:"right"})),title:"Align right",children:e.jsx(Ms,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onMouseDown:d=>{d.preventDefault(),r.chain().focus().setTextAlign("justify").run()},className:xe(r.isActive({textAlign:"justify"})),title:"Justify",children:e.jsx(fn,{className:"w-3.5 h-3.5"})}),je,e.jsx("button",{onMouseDown:d=>{d.preventDefault(),r.chain().focus().toggleBulletList().run()},className:xe(r.isActive("bulletList")),title:"Bullet list",children:e.jsx(Vt,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onMouseDown:d=>{d.preventDefault(),r.chain().focus().toggleOrderedList().run()},className:xe(r.isActive("orderedList")),title:"Numbered list",children:e.jsx(As,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onMouseDown:d=>{d.preventDefault(),r.chain().focus().toggleBlockquote().run()},className:xe(r.isActive("blockquote")),title:"Blockquote",children:e.jsx(Ls,{className:"w-3.5 h-3.5"})}),je,e.jsxs("button",{onMouseDown:d=>{d.preventDefault(),W.current?.click()},className:"relative p-1.5 rounded text-muted-foreground hover:bg-muted transition-colors h-7 w-7 flex items-center justify-center",title:"Text color",children:[e.jsx(rn,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"absolute bottom-0.5 left-1 right-1 h-[3px] rounded-full",style:{background:fe}})]}),e.jsx("input",{ref:W,type:"color",className:"sr-only",value:fe,onChange:d=>r.chain().focus().setColor(d.target.value).run()}),e.jsxs("button",{onMouseDown:d=>{d.preventDefault(),te.current?.click()},className:"relative p-1.5 rounded text-muted-foreground hover:bg-muted transition-colors h-7 w-7 flex items-center justify-center",title:"Highlight color",children:[e.jsx(ln,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"absolute bottom-0.5 left-1 right-1 h-[3px] rounded-full",style:{background:ke}})]}),e.jsx("input",{ref:te,type:"color",className:"sr-only",value:ke,onChange:d=>r.chain().focus().setHighlight({color:d.target.value}).run()}),je,e.jsx("button",{onMouseDown:d=>{if(d.preventDefault(),r.isActive("link"))r.chain().focus().unsetLink().run();else{const G=window.prompt("URL:");G&&r.chain().focus().setLink({href:G,target:"_blank"}).run()}},className:xe(r.isActive("link")),title:"Link",children:e.jsx(Tt,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onMouseDown:d=>{d.preventDefault(),r.chain().focus().toggleCode().run()},className:xe(r.isActive("code")),title:"Inline code",children:e.jsx(Xt,{className:"w-3.5 h-3.5"})}),je,e.jsx("button",{onMouseDown:d=>{d.preventDefault(),r.chain().focus().clearNodes().unsetAllMarks().run()},className:"p-1.5 rounded text-muted-foreground hover:bg-muted hover:text-foreground transition-colors h-7",title:"Clear formatting",children:e.jsx(un,{className:"w-3.5 h-3.5"})}),je,e.jsx("button",{onMouseDown:d=>{d.preventDefault(),r.chain().focus().undo().run()},disabled:!r.can().undo(),className:"p-1.5 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors disabled:opacity-30 h-7",title:"Undo","data-testid":"button-undo-prose",children:e.jsx(Rr,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onMouseDown:d=>{d.preventDefault(),r.chain().focus().redo().run()},disabled:!r.can().redo(),className:"p-1.5 rounded text-muted-foreground hover:text-foreground hover:bg-muted transition-colors disabled:opacity-30 h-7",title:"Redo","data-testid":"button-redo-prose",children:e.jsx(Or,{className:"w-3.5 h-3.5"})})]}),e.jsx("div",{className:"px-10 pt-8 pb-4",children:e.jsx("textarea",{ref:Y,value:a,onChange:d=>{n(d.target.value),d.target.style.height="auto",d.target.style.height=`${d.target.scrollHeight}px`},placeholder:"Article title…",rows:1,className:"w-full resize-none overflow-hidden bg-transparent border-0 outline-none text-foreground font-bold text-4xl leading-tight placeholder:text-muted-foreground
15/60 font-display","data-testid":"input-article-title-prose"})}),e.jsx("div",{className:"mx-10 border-t border-border"}),e.jsx("div",{className:"px-10 py-6",children:e.jsx(or,{editor:r,className:"prose-editor-content min-h-[400px]"})}),e.jsxs("div",{className:"px-10 pb-4 flex items-center justify-between border-t border-border pt-3",children:[e.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-muted-foreground font-mono select-none","data-testid":"text-prose-editor-stats",children:[e.jsxs("span",{children:[ae.toLocaleString()," words"]}),e.jsx("span",{className:"text-muted-foreground/60",children:"·"}),e.jsxs("span",{children:[O.toLocaleString()," chars"]}),e.jsx("span",{className:"text-muted-foreground/60",children:"·"}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Qt,{className:"w-3 h-3"}),pe," min read"]})]}),r&&e.jsxs("button",{onMouseDown:d=>{d.preventDefault(),M.current=G=>{r.chain().focus().setImage({src:G}).run()},I(!0)},className:"flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground hover:bg-muted px-2 py-1 rounded transition-colors",title:"Insert image",children:[e.jsx(Pt,{className:"w-3.5 h-3.5"})," Insert image"]})]})]}),o.visible&&r&&e.jsxs("div",{style:{top:Math.max(8,o.top),left:Math.max(8,o.left)},className:"fixed z-[9999] flex items-center bg-navy-deep rounded-lg shadow-xl border border-white/10 p-1 gap-0.5",onMouseDown:d=>d.preventDefault(),"data-testid":"image-toolbar",children:[e.jsx("button",{onMouseDown:d=>{d.preventDefault(),K("left")},className:"p-1.5 rounded text-white/80 hover:bg-white/10 transition-colors",title:"Align left",children:e.jsx(Ts,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onMouseDown:d=>{d.preventDefault(),K("center")},className:"p-1.5 rounded text-white/80 hover:bg-white/10 transition-colors",title:"Align center",children:e.jsx(Ps,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onMouseDown:d=>{d.preventDefault(),K("right")},className:"p-1.5 rounded text-white/80 hover:bg-white/10 transition-colors",title:"Align right",children:e.jsx(Ms,{className:"w-3.5 h-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-white/10 mx-0.5"}),e.jsx("button",{onMouseDown:d=>{d.preventDefault(),o.src&&b({src:o.src,nodePos:o.nodePos})},className:"p-1.5 rounded text-white/80 hover:bg-white/10 transition-colors",title:"Crop image",children:e.jsx($r,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onMouseDown:d=>{d.preventDefault();const G=window.prompt("Image link URL:","");if(G!==null&&r){const{state:le,view:de}=r;le.doc.nodesBetween(o.nodePos,o.nodePos+1,(se,ye)=>{if(se.type.name==="image"){const y=le.tr.setNodeMarkup(ye,void 0,{...se.attrs,href:G});de.dispatch(y)}})}},className:"p-1.5 rounded text-white/80 hover:bg-white/10 transition-colors",title:"Edit link",children:e.jsx(Tt,{className:"w-3.5 h-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-white/10 mx-0.5"}),e.jsx("button",{onMouseDown:d=>{d.preventDefault(),g()},className:"p-1.5 rounded text-destructive hover:bg-destructive/30 transition-colors",title:"Delete image",children:e.jsx(Ys,{className:"w-3.5 h-3.5"})})]}
15),U.visible&&r&&e.jsxs("div",{style:{top:U.top,left:Math.max(8,U.left)},className:"fixed z-[9998] flex items-center bg-navy-deep rounded-lg shadow-xl border border-white/10 p-1 gap-0.5",onMouseDown:d=>d.preventDefault(),children:[e.jsx("button",{onMouseDown:d=>{d.preventDefault(),r.chain().focus().toggleBold().run()},className:Ne(r.isActive("bold")),title:"Bold",children:e.jsx(Ns,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onMouseDown:d=>{d.preventDefault(),r.chain().focus().toggleItalic().run()},className:Ne(r.isActive("italic")),title:"Italic",children:e.jsx(ks,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onMouseDown:d=>{d.preventDefault(),r.chain().focus().toggleUnderline().run()},className:Ne(r.isActive("underline")),title:"Underline",children:e.jsx(Cs,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onMouseDown:d=>{d.preventDefault(),r.chain().focus().toggleStrike().run()},className:Ne(r.isActive("strike")),title:"Strikethrough",children:e.jsx(Ss,{className:"w-3.5 h-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-white/10 mx-0.5"}),e.jsx("button",{onMouseDown:d=>{d.preventDefault(),r.chain().focus().toggleHeading({level:2}).run()},className:`px-2 py-1 rounded text-xs font-bold transition-colors ${X?"bg-accent-gold text-navy-deep":"text-white/80 hover:bg-white/10"}`,title:"Heading 2",children:"H2"}),e.jsx("button",{onMouseDown:d=>{d.preventDefault(),r.chain().focus().toggleHeading({level:3}).run()},className:`px-2 py-1 rounded text-xs font-bold transition-colors ${Q?"bg-accent-gold text-navy-deep":"text-white/80 hover:bg-white/10"}`,title:"Heading 3",children:"H3"}),e.jsx("div",{className:"w-px h-5 bg-white/10 mx-0.5"}),e.jsx("button",{onMouseDown:d=>{d.preventDefault(),r.chain().focus().toggleBulletList().run()},className:Ne(r.isActive("bulletList")),title:"Bullet list",children:e.jsx(Vt,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onMouseDown:d=>{d.preventDefault(),r.chain().focus().toggleOrderedList().run()},className:Ne(r.isActive("orderedList")),title:"Numbered list",children:e.jsx(As,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onMouseDown:d=>{d.preventDefault(),r.chain().focus().toggleBlockquote().run()},className:Ne(r.isActive("blockquote")),title:"Blockquote",children:e.jsx(Ls,{className:"w-3.5 h-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-white/10 mx-0.5"}),e.jsx("button",{onMouseDown:d=>{if(d.preventDefault(),r.isActive("link"))r.chain().focus().unsetLink().run();else{const G=window.prompt("URL:");G&&r.chain().focus().setLink({href:G,target:"_blank"}).run()}},className:Ne(r.isActive("link")),title:"Link",children:e.jsx(Tt,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onMouseDown:d=>{d.preventDefault(),r.chain().focus().toggleCode().run()},className:Ne(r.isActive("code")),title:"Inline code",children:e.jsx(Xt,{className:"w-3.5 h-3.5"})})]}),D.visible&&e.jsx("button",{style:{top:D.top,left:D.left},onMouseDown:d=>{d.preventDefault(),d.stopPropagation();const G=d.currentTarget.getBoundingClientRect();B({top:G.bottom+6,left:G.left}),L(!0),x(0),N("")},className:"fixed z-[9997] w-7 h-7 rounded-full border border-border bg-card text-muted-foreground hover:border-accent-gold hover:text-accent-gold-ink hover:bg-accent-gold/10 transition-colors flex items-center justify-center shadow-sm",title:"Insert block (or type /)","data-testid":"button-insert-block",children:e.jsx(gt,{className:"w-3.5 h-3.5"})}),F.visible&&r&&e.jsxs("div",{style:{top:F.top,left:F.left},className:"fixed z-[9998] flex items-center bg-navy-deep rounded-lg shadow-xl border border-white/10 p-1 gap-0.5",onMouseDown:d=>d.preventDefault(),"data-testid":"table-toolbar",children:[e.jsx("span",{className:"text-xs text-white/50 px-1 font-medium",children:"Table"}),e.jsx("div",{className:"w-px h-4 bg-white/10 mx-0.5"}),e.jsx("button",{onMouseDown:d=>{d.preventDefault(),r.chain().focus().addRowBefore().run()},className:"px-2 py-1 rounded text-xs text-white/80 hover:bg-white/10 transition-colors",title:"Add row above",children:"+ Row ↑"}),e.jsx("button",{onMouseDown:d=>{d.preventDefault(),r.chain().focus().addRowAfter().run()},className:"px-2 py-1 rounded text-xs text-white/80 hover:bg-white/10 transition-colors",title:"Add row below",children:"+ Row ↓"}),e.jsx("button",{onMouseDown:d=>{d.preventDefault(),r.chain().focus().deleteRow().run()},className:"px-2 py-1 rounded text-xs text-white/80 hover:bg-destructive/40 hover:text-destructive transition-colors",title:"Delete row",children:"- Row"}),e.jsx("div",{className:"w-px h-4 bg-white/10 mx-0.5"}),e.jsx("button",{onMouseDown:d=>{d.preventDefault(),r.chain().focus().addColumnBefore().run()},className:"px-2 py-1 rounded text-xs text-white/80 hover:bg-white/10 transition-colors",title:"Add column left",children:"+ Col ←"}),e.jsx("button",{onMouseDown:d=>{d.preventDefault(),r.chain().focus().addColumnAfter().run()},className:"px-2 py-1 rounded text-xs text-white/80 hover:bg-white/10 transition-colors",title:"Add column right",children:"+ Col →"}),e.jsx("button",{onMouseDown:d=>{d.preventDefault(),r.chain().focus().deleteColumn().run()},className:"px-2 py-1 rounded text-xs text-white/80 hover:bg-destructive/40 hover:text-destructive transition-colors",title:"Delete column",children:"- Col"}),e.jsx("div",{className:"w-px h-4 bg-white/10 mx-0.5"}),e.jsx("button",{onMouseDown:d=>{d.preventDefault(),r.chain().focus().deleteTable().run()},className:"px-2 py-1 rounded text-xs text-destructive hover:bg-destructive/40 transition-colors",title:"Delete table",children:"Del Table"})]}),(m||A)&&e.jsx(Pr,{items:A&&!m?js:R,pos:m?k:E,activeIdx:P,onSelect:d=>{L(!1),v(d)},onClose:()=>{j(!1),V.current=!1,L(!1),N("")}}),e.jsx(Mr,{editState:H,onClose:()=>T(null)}),e.jsx(ri,{open:re,onClose:()=>I(!1),onInsert:d=>{M.current?.(d),I(!1)},token:i}),l&&e.jsx(Fr,{src:l.src,token:i,onConfirm:d=>{if(!r)return;const{state:G,view:le}=r;
15G.doc.nodesBetween(l.nodePos,l.nodePos+1,(de,se)=>{if(de.type.name==="image"){const ye=G.tr.setNodeMarkup(se,void 0,{...de.attrs,src:d});le.dispatch(ye)}}),b(null)},onClose:()=>b(null)})]})})}function ci({value:t,onChange:s,token:a}){const{toast:n}=De(),i=h.useRef(null),[m,j]=h.useState(!1),k=async p=>{if(!p.type.startsWith("image/")){n({title:"Invalid file",description:"Please select an image file.",variant:"destructive"});return}j(!0);try{const u=new FormData;u.append("file",p);const N=await fetch("/api/admin/blog/upload-image",{method:"POST",headers:{...oe()},body:u});if(!N.ok){const x=await N.json().catch(()=>({}));throw new Error(x.error||"Upload failed")}const{url:P}=await N.json();s(P)}catch(u){n({title:"Upload failed",description:u instanceof Error?u.message:"Could not upload image.",variant:"destructive"})}finally{j(!1),i.current&&(i.current.value="")}};return e.jsxs("div",{className:"space-y-2",children:[t&&e.jsxs("div",{className:"relative inline-block",children:[e.jsx("img",{src:t,alt:"Cover preview",className:"max-h-20 rounded-lg border border-border object-cover","data-testid":"img-cover-preview"}),e.jsx("button",{type:"button",onClick:()=>s(""),className:"absolute -top-1.5 -right-1.5 w-5 h-5 rounded-full bg-secondary border border-border text-muted-foreground hover:text-foreground flex items-center justify-center",title:"Remove image","data-testid":"button-remove-cover",children:e.jsx(Ae,{className:"w-3 h-3"})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{type:"button",disabled:m,onClick:()=>i.current?.click(),className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-border text-muted-foreground hover:text-foreground hover:border-muted-foreground text-xs font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed","data-testid":"button-upload-cover",children:m?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"w-3.5 h-3.5 border-2 border-border border-t-foreground rounded-full animate-spin"}),"Uploading…"]}):e.jsxs(e.Fragment,{children:[e.jsx($t,{className:"w-3.5 h-3.5"}),"Upload image"]})}),e.jsx("input",{ref:i,type:"file",accept:"image/*",className:"hidden",onChange:p=>{const u=p.target.files?.[0];u&&k(u)},"data-testid":"input-cover-file"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rs,{className:"w-3.5 h-3.5 text-muted-foreground shrink-0"}),e.jsx("input",{type:"text",value:t,onChange:p=>s(p.target.value),placeholder:"Or paste an image URL…",className:"flex-1 bg-secondary border border-border text-foreground text-sm rounded-lg px-3 py-2 focus:outline-none focus:border-accent-gold placeholder:text-muted-foreground","data-testid":"input-cover-url"})]})]})}function di({editor:t,setEditor:s,token:a,onSave:n,onSectionChange:i,loading:m,fixAllStatus:j,setFixAllStatus:k}){const{toast:p}=De();return e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Runs all publish-readiness steps: reformat long paragraphs, SEO meta, keyword injection, content expansion to 1800+ words, block variety, voice & grammar polish, keyword heading & paragraph, takeaways, FAQs, ",e.jsx("strong",{className:"text-foreground",children:"takeaway & FAQ alignment check"}),", ",e.jsx("strong",{className:"text-foreground",children:"stat source coverage check"})," (flags stat blocks with no matching source entry or homepage-only URLs), and cover image. Auto-saves when complete."]}),j?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-foreground",children:[j.step!=="Complete"&&j.step!=="Failed"&&e.jsx(ie,{className:"w-4 h-4 animate-spin text-success-ink"}),j.step==="Complete"&&e.jsx(lt,{className:"w-4 h-4 text-success-ink"}),j.step==="Failed"&&e.jsx(Ae,{className:"w-4 h-4 text-destructive-ink"}),e.jsx("span",{className:"text-sm",children:j.step})]}),j.done.length>0&&e.jsx("div",{className:"space-y-1",children:j.done.map((u,N)=>e.jsxs("div",{className:"flex items-center gap-2 text-xs text-success-ink",children:[e.jsx(lt,{className:"w-3 h-3"})," ",u]},N))}),j.warnings?.length>0&&e.jsx("div",{className:"space-y-1",children:j.warnings.map((u,N)=>e.jsxs("div",{className:"flex items-center gap-2 text-xs text-warning-ink",children:[e.jsx(es,{className:"w-3 h-3"})," ",u]},N))}),j.errors.length>0&&e.jsx("div",{className:"space-y-1",children:j.errors.map((u,N)=>e.jsx("div",{className:"text-xs text-destructive-ink",children:u},N))}),(j.step==="Complete"||j.step==="Failed")&&e.jsxs("button",{onClick:()=>k(null),className:"w-full py-1.5 text-xs text-muted-foreground hover:text-foreground border border-border rounded-lg flex items-center justify-center gap-1",children:[e.jsx(Ue,{className:"w-3 h-3"})," Run Again"]})]}):e.jsxs("button",{onClick:async()=>{const u=[],N=[],P=[],x={},H=()=>({...t,...x}),T=A=>k({step:A,done:[...u],warnings:[...N],errors:[...P]});try{if(T("Checking content format…"),(x.blocks??t.blocks).some(c=>c.type!=="paragraph"?!1:(c.content||c.text||"").replace(/<[^>]*>
15/g," ").split(/\s+/).filter(Boolean).length>80)){T("Reformatting content…");try{const c=x.blocks??t.blocks,D=await me("/api/admin/articles/ai-assist",a,{method:"POST",body:JSON.stringify({action:"reformat_content",title:t.title,blocks:c})});D?.blocks?.length?(x.blocks=D.blocks,u.push("Reformatted content")):u.push("Reformat (no changes returned)")}catch(c){P.push(`Reformat: ${c.message}`)}}else u.push("Content format (already ok)");T("Checking SEO meta…");const L=x.metaTitle??t.metaTitle??"",E=x.metaDescription??t.metaDescription??"",B=(t.focusKeyword||"").toLowerCase();if(L.length>=50&&L.length<=60&&E.length>=120&&E.length<=155&&(!B||L.toLowerCase().includes(B)&&E.toLowerCase().includes(B)))u.push("SEO meta (already ok)");else{T("Generating SEO meta…");try{const c=H(),D=(x.blocks??t.blocks).map(F=>F.content||F.text||"").join(`
16`).slice(0,4e3),$=await me("/api/admin/articles/ai-assist",a,{method:"POST",body:JSON.stringify({action:"generate_meta",title:c.title,content:D,tone:"authoritative",focusKeyword:c.focusKeyword||""})});$?.metaTitle&&(x.metaTitle=$.metaTitle,x.metaDescription=$.metaDescription,u.push("SEO meta title & description"))}catch(c){P.push(`Meta: ${c.message}`)}}if(t.focusKeyword?.trim()){const c=x.title??t.title,D=t.focusKeyword.toLowerCase();c.toLowerCase().includes(D)?u.push("Title (already has keyword)"):(N.push(`Title doesn't contain focus keyword "${t.focusKeyword}" — consider updating it manually via the Chat`),u.push("Title (keyword not in title — see warning)"))}if(T("Checking subtitle…"),t.subtitle?.trim())u.push("Subtitle (kept existing)");else try{const c=(x.blocks??t.blocks).map($=>$.content||$.text||"").join(`
17`).slice(0,2e3),D=await me("/api/admin/articles/ai-assist",a,{method:"POST",body:JSON.stringify({action:"generate_subtitle",title:t.title,content:c})});D?.subtitle&&(x.subtitle=D.subtitle,u.push("Subtitle generated"))}catch(c){P.push(`Subtitle: ${c.message}`)}if(T("Checking excerpt…"),t.excerpt?.trim())u.push("Excerpt (kept existing)");else try{const c=(x.blocks??t.blocks).map($=>$.content||$.text||"").join(`
18`).slice(0,2e3),D=await me("/api/admin/articles/ai-assist",a,{method:"POST",body:JSON.stringify({action:"generate_excerpt",title:t.title,content:c})});D?.excerpt&&(x.excerpt=D.excerpt,u.push("Excerpt generated"))}catch(c){P.push(`Excerpt: ${c.message}`)}T("Checking article length…");{const c=x.blocks??t.blocks,D=x.keyTakeaways??t.keyTakeaways,$=x.faqItems??t.faqItems,F=c.reduce((o,S)=>o+(S.content||S.text||"").replace(/<[^>]*>/g,"").split(/\s+/).filter(Boolean).length,0),J=D.join(" ").split(/\s+/).filter(Boolean).length,re=$.reduce((o,S)=>o+`${S.question} ${S.answer}`.split(/\s+/).filter(Boolean).length,0),I=F+J+re;if(I<1800)try{const o=await me("/api/admin/articles/ai-assist",a,{method:"POST",body:JSON.stringify({action:"expand_content",title:x.title??t.title,blocks:c,currentWordCount:F,focusKeyword:t.focusKeyword||""})}),S=Array.isArray(o?.blocks)&&o.blocks.length>c.length,l=S?o.blocks.reduce((b,M)=>b+(M.content||M.text||"").replace(/<[^>]*>/g,"").split(/\s+/).filter(Boolean).length,0):0;if(S&&l>=F){x.blocks=o.blocks;const b=l+J+re;if(u.push(`Article expanded to ~${b} words`),b<1800)try{const M=await me("/api/admin/articles/ai-assist",a,{method:"POST",body:JSON.stringify({action:"expand_content",title:x.title??t.title,blocks:o.blocks,currentWordCount:l,focusKeyword:t.focusKeyword||""})});if(Array.isArray(M?.blocks)&&M.blocks.length>o.blocks.length){x.blocks=M.blocks;const W=M.blocks.reduce((te,V)=>te+(V.content||V.text||"").replace(/<[^>]*>/g,"").split(/\s+/).filter(Boolean).length,0)+J+re;u.push(`Second expansion pass: ~${W} words total`)}}catch(M){N.push(`Second expansion pass: ${M.message}`)}}else N.push(`Expansion didn't add content (${l} vs ${F} words) — try Run Again or expand manually`)}catch(o){N.push(`Content expansion: ${o.message}`)}else u.push(`Article length ok (${I} words)`)}T("Checking content variety…");{const c=x.blocks??t.blocks,D=c.some(F=>F.type==="heading"),$=c.some(F=>["callout","numberedList","bulletList","blockquote","stat","framework"].includes(F.type));if(!D||!$)try{const F=c.map(o=>o.content||o.text||"").join(`
19`).slice(0,4e3),J=[...D?[]:["H2 subheadings before each major topic shift"],...$?[]:["one callout (insight or framework variant) or a numberedList that synthesises a key concept"]],I=(await me("/api/admin/articles/ai-assist",a,{method:"POST",body:JSON.stringify({action:"custom_instruction",instruction:`The article lacks structural variety. Insert ${J.join(" and ")}. CRITICAL RULES: (1) Keep ALL existing blocks exactly as they are — only INSERT new blocks, never rewrite existing ones. (2) H2 heading blocks go before each clear topic shift. (3) One callout or numberedList synthesises the most important concept. (4) Do NOT add content that repeats what already exists.`,title:x.title??t.title,content:F,blocks:c,focusKeyword:t.focusKeyword||""})}))?.updates?.find(o=>o.field==="blocks");I?.value?.length>c.length?(x.blocks=I.value,u.push("Content variety improved (headings & structured blocks added)")):u.push("Content variety (already structured)")}catch(F){N.push(`Variety: ${F.message}`)}else u.push("Content variety (already structured)")}T("Polishing voice & grammar…");try{const c=x.blocks??t.blocks,D=await me("/api/admin/articles/ai-assist",a,{method:"POST",body:JSON.stringify({action:"polish_voice_and_grammar",title:x.title??t.title,blocks:c})});if(Array.isArray(D?.blocks)&&D.blocks.length>0){x.blocks=D.blocks;const $=(Array.isArray(D.changes)?D.changes:[]).filter(F=>!/no change needed/i.test(F));$.length>0?(u.push(`Voice & grammar: ${$.length} fix${$.length===1?"":"es"}
19 applied`),$.slice(0,5).forEach(F=>N.push(`↳ ${F}`)),$.length>5&&N.push(`↳ …and ${$.length-5} more`)):u.push("Voice & grammar (no issues found)")}else u.push("Voice & grammar (no changes)")}catch(c){N.push(`Voice polish: ${c.message}`)}if(t.focusKeyword?.trim()){T("Injecting keyword into first paragraph…");try{const c=(x.blocks??t.blocks).map($=>$.content||$.text||"").join(`
20`).slice(0,4e3),D=await me("/api/admin/articles/ai-assist",a,{method:"POST",body:JSON.stringify({action:"inject_keyword_paragraph",title:t.title,content:c,blocks:x.blocks??t.blocks,focusKeyword:t.focusKeyword})});if(D?.changed){x.blocks=D.blocks;const $=t.focusKeyword.toLowerCase(),F=D.blocks.find(re=>re.type==="paragraph");(F?.content||F?.text||"").replace(/<[^>]*>/g,"").toLowerCase().includes($)?u.push("Keyword in first paragraph"):N.push("Keyword injection attempted but may not be fully applied — check the first paragraph manually")}else u.push("First paragraph (already has keyword)")}catch(c){P.push(`Paragraph keyword: ${c.message}`)}T("Checking keyword heading…");try{const c=(x.blocks??t.blocks).map($=>$.content||$.text||"").join(`
21`).slice(0,4e3),D=await me("/api/admin/articles/ai-assist",a,{method:"POST",body:JSON.stringify({action:"inject_keyword_heading",title:t.title,content:c,blocks:x.blocks??t.blocks,focusKeyword:t.focusKeyword})});D?.changed?(x.blocks=D.blocks,u.push("Keyword heading injected")):u.push("Heading (already has keyword)")}catch(c){P.push(`Heading keyword: ${c.message}`)}}else u.push("Keyword steps skipped (no focus keyword set)");T("Checking takeaways…");{const c=x.keyTakeaways??t.keyTakeaways;if(c.length<5)try{const D=(x.blocks??t.blocks).map(F=>F.content||F.text||"").join(`
22`).slice(0,4e3),$=await me("/api/admin/articles/ai-assist",a,{method:"POST",body:JSON.stringify({action:"generate_takeaways",title:t.title,content:D,tone:"authoritative"})});$?.takeaways?.length>=c.length?(x.keyTakeaways=$.takeaways,u.push(`Takeaways expanded to ${$.takeaways.length} items`)):u.push(`Takeaways (${c.length} items — kept existing)`)}catch(D){P.push(`Takeaways: ${D.message}`)}else u.push(`Takeaways (${c.length} items — ok)`)}T("Checking FAQs…");{const c=x.faqItems??t.faqItems;if(c.length<5)try{const D=(x.blocks??t.blocks).map(F=>F.content||F.text||"").join(`
23`).slice(0,4e3),$=await me("/api/admin/articles/ai-assist",a,{method:"POST",body:JSON.stringify({action:"generate_faqs",title:t.title,content:D,tone:"authoritative"})});$?.faqs?.length>=c.length?(x.faqItems=$.faqs,u.push(`FAQs expanded to ${$.faqs.length} items`)):u.push(`FAQs (${c.length} items — kept existing)`)}catch(D){P.push(`FAQs: ${D.message}`)}else u.push(`FAQs (${c.length} items — ok)`)}T("Checking takeaways & FAQs alignment…");{const c=x.keyTakeaways??t.keyTakeaways,D=x.faqItems??t.faqItems;if(c.length>0||D.length>0)try{const $=await me("/api/admin/articles/ai-assist",a,{method:"POST",body:JSON.stringify({action:"align_takeaways_and_faqs",title:x.title??t.title,blocks:x.blocks??t.blocks,takeaways:c,faqs:D})}),F=(Array.isArray($?.changes)?$.changes:[]).filter(J=>!/no change needed/i.test(J));F.length>0?(Array.isArray($?.takeaways)&&$.takeaways.length===c.length&&(x.keyTakeaways=$.takeaways),Array.isArray($?.faqs)&&$.faqs.length===D.length&&(x.faqItems=$.faqs),u.push(`Takeaways & FAQs aligned — ${F.length} correction${F.length===1?"":"s"}`),F.slice(0,5).forEach(J=>N.push(`↳ ${J}`)),F.length>5&&N.push(`↳ …and ${F.length-5} more`)):u.push("Takeaways & FAQs (already consistent with article)")}
23catch($){N.push(`Takeaway/FAQ alignment: ${$.message}`)}else u.push("Takeaways & FAQs (none to check)")}T("Checking stat source coverage…");{const c=x.blocks??t.blocks,D=x.sources??t.sources??[],$=D.map(re=>(re.organization||"").toLowerCase());let F=0,J=0;for(const re of c)if(!(re.type!=="stat"||!Array.isArray(re.items)))for(const I of re.items){if(!I.context)continue;const o=I.context.match(/^(.+?)\s+\d{4}$/),S=(o?o[1].trim():I.context.trim()).toLowerCase();$.some(b=>b.includes(S)||S.includes(b))||(F++,N.push(`↳ Stat "${I.value} ${I.label}" (${I.context}) has no matching source entry — add it in the Sources tab`))}for(const re of D){const I=re.url||"";if(I){const o=I.replace(/^https?:\/\/[^/]+/,"");(!o||o==="/"||o==="")&&(J++,N.push(`↳ ${re.organization}: URL is a homepage — consider linking the specific report`))}}F===0&&J===0?u.push("Stat sources (all stats have source entries)"):u.push(`Stat sources — ${F} uncovered${J?`, ${J} homepage-only URL${J!==1?"s":""}`:""}`)}if(T("Checking cover image…"),t.coverImage?.trim())u.push("Cover image (kept existing)");else try{const c=await me("/api/admin/articles/ai-assist",a,{method:"POST",body:JSON.stringify({action:"generate_cover_image",title:t.title,content:x.excerpt??t.excerpt??"",focusKeyword:t.focusKeyword||"",slug:t.slug||""})});c?.coverImage?(x.coverImage=c.coverImage,x.coverImageAlt=c.coverImageAlt||t.title,u.push("Cover image generated")):N.push("Cover image: generation returned no image")}catch(c){N.push(`Cover image: ${c.message}`)}s(c=>{if(!c)return c;const D={...c,...x};return x.blocks&&(D._blockVersion=(c._blockVersion||0)+1),D}),x.blocks&&i&&setTimeout(()=>i("content"),50),T("Saving…"),n&&(await n(x),u.push("Auto-saved")),k({step:"Complete",done:[...u],warnings:[...N],errors:[...P]}),p({title:`Publish Ready complete — ${u.length} steps done${N.length?`, ${N.length} warnings`:""}${P.length?`, ${P.length} errors`:""}`})}catch(A){p({title:"Publish Ready failed",description:A.message,variant:"destructive"}),k({step:"Failed",done:[...u],warnings:[...N],errors:[...P,A.message]})}},disabled:m,className:"w-full py-2.5 rounded-lg bg-success hover:bg-success/90 disabled:opacity-50 text-success-foreground text-sm font-semibold flex items-center justify-center gap-2","data-testid":"button-publish-ready",children:[e.jsx(Se,{className:"w-4 h-4"})," Publish Ready"]})]})}function ui({editor:t,setEditor:s,token:a,onClose:n,onSave:i,onSectionChange:m}){const[j,k]=h.useState("generate"),[p,u]=h.useState(!1),[N,P]=h.useState(""),[x,H]=h.useState("authoritative"),[T,A]=h.useState(null),[L,E]=h.useState(!1),[B,U]=h.useState(null),[c,D]=h.useState("gpt-5.4-mini"),[$,F]=h.useState(null),[J,re]=h.useState(""),[I,o]=h.useState(!1),[S,l]=h.useState(""),[b,M]=h.useState(!1),[W,te]=h.useState(!1),[V,ne]=h.useState(""),[Y,we]=h.useState(!1),[w,R]=h.useState(!1),{toast:f}=De();function r(g){const C=[];let X=!1;return s(Q=>{if(!Q)return Q;const ae={...Q};for(const O of g)switch(O.field){case"blocks":if(Array.isArray(O.value)&&O.value.length>0){const pe=O.value.filter(ce=>ce.type!=="paragraph"?!0:(ce.content||ce.text||"").replace(/<[^>]*>/g,"").replace(/&nbsp;/gi,"").replace(/&#160;/g,"").replace(/\u00a0/g,"").trim().length>0);ae.blocks=pe,ae._blockVersion=(Q._blockVersion||0)+1,C.push(`${pe.length} content blocks`),X=!0}break;case"title":typeof O.value=="string"&&(ae.title=O.value,C.push("Title"));break;case"subtitle":typeof O.value=="string"&&(ae.subtitle=O.value,C.push("Subtitle"));break;case"excerpt":typeof O.value=="string"&&(ae.excerpt=O.value,C.push("Excerpt"));break;case"metaTitle":typeof O.value=="string"&&(ae.metaTitle=O.value,C.push("Meta Title"));break;case"metaDescription":typeof O.value=="string"&&(ae.metaDescription=O.value,C.push("Meta Description"));break;case"focusKeyword":typeof O.value=="string"&&(ae.focusKeyword=O.value,C.push("Focus Keyword"));break;case"keyTakeaways":Array.isArray(O.value)&&(ae.keyTakeaways=O.value,C.push(`${O.value.length} takeaways`));break;case"faqItems":Array.isArray(O.value)&&(ae.faqItems=O.value,C.push(`${O.value.length} FAQs`));break;case"sources":Array.isArray(O.value)&&(ae.sources=O.value,C.push(`${O.value.length} sources`));break}return ae}),X&&m&&setTimeout(()=>m("content"),50),C}h.useEffect(()=>{fetch("/api/admin/settings/article_ai_model",{headers:{...oe()}}).then(g=>g.ok?g.json():null).then(g=>{g?.value&&D(g.value)}
23).catch(()=>{}),fetch("/api/admin/ai/provider-models",{headers:{...oe()}}).then(g=>g.ok?g.json():null).then(g=>{g&&F(g)}).catch(()=>{}),fetch("/api/admin/settings/article_style_prompt",{headers:{...oe()}}).then(g=>g.ok?g.json():null).then(g=>{g?.value&&re(g.value)}).catch(()=>{}),fetch("/api/admin/settings/article_voice_prompt",{headers:{...oe()}}).then(g=>g.ok?g.json():null).then(g=>{g?.value&&l(g.value)}).catch(()=>{}),fetch("/api/admin/settings/article_edit_prompt",{headers:{...oe()}}).then(g=>g.ok?g.json():null).then(g=>{g?.value&&ne(g.value)}).catch(()=>{})},[a]),h.useEffect(()=>{async function g(C){const X=C.detail,Q=X?.instruction,ae=X?.chatContext;if(!Q)return;u(!0);const O=new AbortController,pe=setTimeout(()=>O.abort(),12e4);try{const ce=await fetch("/api/admin/articles/ai-assist",{method:"POST",signal:O.signal,headers:{"Content-Type":"application/json",...oe()},body:JSON.stringify({action:"custom_instruction",instruction:Q,chatContext:ae,title:t.title,subtitle:t.subtitle,excerpt:t.excerpt,blocks:t.blocks,metaTitle:t.metaTitle,metaDescription:t.metaDescription,focusKeyword:t.focusKeyword,keyTakeaways:t.keyTakeaways,faqItems:t.faqItems,sources:t.sources,slug:t.slug,category:t.category,tags:t.tags,tone:x})});if(!ce.ok)throw new Error((await ce.json()).error||"AI error");const be=await ce.json();if(be.updates?.length>0){r(be.updates);const fe=be.updates.some(ke=>ke._truncationWarning);f(fe?{title:"Content preserved",description:"AI returned fewer blocks than expected — original content was restored. Try a more targeted instruction.",variant:"destructive"}:{title:"Changes applied",description:be.summary||"Article updated successfully"})}else f({title:"No changes returned",description:be.summary||"Try rephrasing your instruction with more specifics.",variant:"destructive"})}catch(ce){f({title:ce?.name==="AbortError"?"AI timed out — please try again":"Apply failed",description:ce?.name==="AbortError"?void 0:ce.message,variant:"destructive"})}finally{clearTimeout(pe),u(!1)}}return window.addEventListener("admin-ai-instruction:apply",g),()=>window.removeEventListener("admin-ai-instruction:apply",g)},[t,a,x]);async function v(g,C){u(!0),A(null);const X=new AbortController,ae=setTimeout(()=>X.abort(),g==="generate_article"?175e3:12e4);try{const O=t.blocks.map(be=>be.text||be.content||be.items?.join(" ")||"").join(" ").slice(0,4e3),pe=await fetch("/api/admin/articles/ai-assist",{method:"POST",signal:X.signal,headers:{"Content-Type":"application/json",...oe()},body:JSON.stringify({action:g,content:O,title:t.title,tone:x,brief:N,...C})});if(!pe.ok)throw new Error((await pe.json()).error||"AI error");const ce=await pe.json();return A(ce),ce}catch(O){f({title:O?.name==="AbortError"?"AI timed out — please try again":"AI error",description:O?.name==="AbortError"?void 0:O.message,variant:"destructive"})}finally{clearTimeout(ae),u(!1)}}const _=[{v:"authoritative",l:"Authoritative"},{v:"warm",l:"Warm"},{v:"conversational",l:"Conversational"},{v:"provocative",l:"Provocative"}];function K(){window.dispatchEvent(new CustomEvent("admin-ai-drawer:open",{detail:{type:"article",label:"Article Editor",contextData:{title:t.title,focusKeyword:t.focusKeyword,blocks:t.blocks,keyTakeaways:t.keyTakeaways,faqItems:t.faqItems}}}))}return e.jsxs("div",{className:"flex flex-col h-full bg-card border border-border rounded-xl overflow-hidden",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-border shrink-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($e,{className:"w-4 h-4 text-info"}),e.jsx("span",{className:"text-sm font-semibold text-foreground",children:"AI Writing Assistant"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:K,className:"flex items-center gap-1 px-2 py-1 rounded bg-info/20 hover:bg-info/30 text-info text-[11px] border border-info/30 transition-colors","data-testid":"button-open-article-ai-chat",title:"Open AI Chat for this article",children:[e.jsx($e,{className:"w-3 h-3"}),"Chat"]}),e.jsx("button",{onClick:n,className:"text-muted-foreground hover:text-foreground","data-testid":"button-close-ai-panel",children:e.jsx(Ae,{className:"w-4 h-4"})})]})]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground leading-tight",children:[e.jsx("span",{className:"text-info font-medium",children:"Chat:"}),' type an instruction (e.g. "add 3 further reading links with sources") → AI proposes changes → click ',e.jsx("span",{className:"text-info font-medium",children:"Apply to Article"})," → content updates automatically in the Content tab."]})]}),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-3 py-2.5 border-b border-border shrink-0",children:e.jsx("div",{className:"grid grid-cols-2 gap-1",children:[{id:"fixall",icon:Se,l:"Publish Ready"},{id:"generate",icon:ct,l:"Generate Content"},{id:"meta",icon:Mt,l:"SEO Meta"},{id:"headlines",icon:Ds,l:"Headlines"},{id:"faqs",icon:nt,l:"FAQs"},{id:"takeaways",icon:lt,l:"Takeaways"},{id:"linkedin",icon:xt,l:"LinkedIn Post"},{id:"image",icon:Pt,l:"Cover Image"},{id:"reformat",icon:Ue,l:"Reformat"}].map(({id:g,icon:C,l:X})=>e.jsxs("button",{onClick:()=>{k(g),A(null)},className:`flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs transition-colors text-left ${j===g?"bg-info/20 text-info border border-info/40":"text-muted-foreground hover:bg-secondary hover:text-foreground border border-transparent"}`,children:[e.jsx(C,{className:"w-3 h-3 shrink-0"}),e.jsx("span",{children:X})]},g))})}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Tone"}),e.jsx("div",{className:"flex gap-1 flex-wrap",children:_.map(g=>e.jsx("button",{onClick:()=>H(g.v),className:`px-2 py-1 rounded text-xs transition-colors ${x===g.v?"bg-info text-foreground":"bg-secondary text-muted-foreground hover:bg-secondary"}`,children:g.l},g.v))})]}),e.jsxs("div",{className:"w-44 shrink-0",children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"AI Model"}),e.jsxs(ft,{value:c,onValueChange:g=>{D(g),fetch("/api/admin/settings/article_ai_model",{method:"PUT",headers:{"Content-Type":"application/json",...oe()},body:JSON.stringify({value:g})}).catch(()=>{})},children:[e.jsx(bt,{className:"bg-secondary border-border text-foreground text-xs h-8","data-testid":"select-article-ai-model",children:e.jsx(wt,{})}),e.jsx(yt,{className:"bg-secondary border-border",children:[{key:"openai",label:"OpenAI",labelClass:"text-info",fallback:[{value:"gpt-4.1-mini",label:"GPT-4.1 Mini (Recommended)"},{value:"gpt-4.1",label:"GPT-4.1 (Most Capable)"},{value:"gpt-4o-mini",label:"GPT-4o Mini"},{value:"gpt-4o",label:"GPT-4o"}]},{key:"anthropic",label:"Anthropic",labelClass:"text-warning",fallback:[{value:"claude-opus-4-8",label:"Claude Opus 4.8 (Most Capable)"},{value:"claude-opus-4-7",label:"Claude Opus 4.7"},{value:"claude-sonnet-4-6",label:"Claude Sonnet 4.6 (Recommended)"},{value:"claude-haiku-4-5",label:"Claude Haiku 4.5 (Fast)"}]},{key:"deepseek",label:"DeepSeek",labelClass:"text-info",fallback:[{value:"deepseek-v4-flash",label:"DeepSeek V4 Flash (Recommended)"},{value:"deepseek-v4-pro",label:"DeepSeek V4 Pro (Most Capable)"}]},{key:"xai",label:"xAI (Grok)",labelClass:"text-info",fallback:[{value:"grok-4.5",label:"Grok 4.5 (Recommended)"},{value:"grok-4.3",label:"Grok 4.3"}]}].map(({key:g,label:C,labelClass:X,fallback:Q})=>{const ae=$?.[g]??Q;return ae.length?e.jsxs(Ia,{children:[e.jsx(Ea,{className:`${X} text-[10px] font-semibold px-2 py-0.5 mt-1`,children:C}),ae.map(O=>e.jsx(Ee,{value:O.value,className:"text-foreground text-xs focus:bg-secondary",children:O.label},O.value))]},g):null})})]}),e.jsx("div",{className:"mt-1",children:e.jsx(Hr,{pricing:Br($,c),testId:"select-article-ai-model"})})]})]}),e.jsxs("div",{className:"border border-border/60 rounded-lg p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("label",{className:"text-xs text-muted-foreground font-semibold uppercase tracking-wide",children:"Writing Style / Brand Voice"}),e.jsx("button",{onClick:async()=>{o(!0);try{await fetch("/api/admin/settings/article_style_prompt",{method:"PUT",headers:{"Content-Type":"application/json",...oe()},body:JSON.stringify({value:J})}),f({title:"Writing style saved"})}catch{f({title:"Save failed",variant:"destructive"})}finally{o(!1)}},disabled:I,"data-testid":"button-save-article-style-prompt",className:"text-xs bg-info hover:bg-info/90 text-foreground font-semibold px-2.5 py-1 rounded transition-colors disabled:opacity-50",children:I?"Saving…":"Save Style"})]}),e.jsx("textarea",{value:J,onChange:g=>re(g.target.value),placeholder:"Leave blank to use default Stuart Andrews brand voice…",rows:3,"data-testid":"textarea-article-style-prompt",className:"w-full bg-secondary/60 border border-border rounded text-xs text-foreground px-2.5 py-2 resize-y focus:outline-none focus:ring-1 focus:ring-info/50 placeholder-muted-foreground"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Instructs the AI on brand voice, audience, and writing tone for all article generation and improvement features."})]}),e.jsxs("div",{className:"border border-info/30 rounded-lg p-3 space-y-2 bg-info/10",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Se,{className:"w-3.5 h-3.5 text-info"}),e.jsx("label",{className:"text-xs text-info font-semibold uppercase tracking-wide",children:"Article Voice System Prompt"})]}),e.jsx("button",{onClick:()=>te(g=>!g),className:"text-xs text-muted-foreground hover:text-foreground","data-testid":"button-toggle-voice-prompt",children:W?"Hide ▲":"Show / Edit ▼"})]}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Controls who Stuart is, his global audience rule, voice rules, and forbidden phrases — used for ",e.jsx("strong",{children:"every"})," article generated on this platform. Leave blank to use the built-in default."]}),W&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("textarea",{value:S,onChange:g=>l(g.target.value),placeholder:"Leave blank to use the built-in Stuart Andrews voice fingerprint…",rows:14,"data-testid":"textarea-article-voice-prompt",className:"w-full bg-secondary/60 border border-info/40 rounded text-xs text-foreground px-2.5 py-2 resize-y focus:outline-none focus:ring-1 focus:ring-info/50 placeholder-muted-foreground font-mono leading-relaxed"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:async()=>{M(!0);try{await fetch("/api/admin/settings/article_voice_prompt",{method:"PUT",headers:{"Content-Type":"application/json",...oe()},body:JSON.stringify({value:S})}),f({title:"Voice prompt saved",description:"All new article generation will use this prompt."})}catch{f({title:"Save failed",variant:"destructive"})}finally{M(!1)}},disabled:b,"data-testid":"button-save-article-voice-prompt",className:"text-xs bg-info hover:bg-info/90 text-foreground font-semibold px-2.5 py-1 rounded transition-colors disabled:opacity-50",children:b?"Saving…":"Save Voice Prompt"}),e.jsx("button",{onClick:async()=>
23{if(await us({title:"Reset to the default voice prompt?",description:"This clears your custom prompt.",danger:!0})){l("");try{await fetch("/api/admin/settings/article_voice_prompt",{method:"PUT",headers:{"Content-Type":"application/json",...oe()},body:JSON.stringify({value:""})}),f({title:"Reset to default",description:"The built-in Stuart Andrews voice fingerprint will be used."})}catch{f({title:"Reset failed",variant:"destructive"})}}},"data-testid":"button-reset-voice-prompt",className:"text-xs text-muted-foreground hover:text-destructive border border-border px-2.5 py-1 rounded transition-colors",children:"Reset to Default"})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Tip: The default prompt includes the global audience rule (no ASX/country-specific references) and all forbidden phrases. Only edit this if you need a fundamentally different persona or audience."})]})]}),e.jsxs("div",{className:"border border-accent-gold/30 rounded-lg p-3 space-y-2 bg-accent-gold/10",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ct,{className:"w-3.5 h-3.5 text-accent-gold"}),e.jsx("label",{className:"text-xs text-accent-gold-ink font-semibold uppercase tracking-wide",children:"Editor Apply Prompt"})]}),e.jsx("button",{onClick:()=>R(g=>!g),className:"text-xs text-muted-foreground hover:text-foreground","data-testid":"button-toggle-edit-prompt",children:w?"Hide ▲":"Show / Edit ▼"})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Controls how Claude interprets and applies instructions typed in the Article Editor chat. Leave blank to use the built-in default which gives Claude full editorial authority."}),w&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("textarea",{value:V,onChange:g=>ne(g.target.value),placeholder:`You are Stuart Andrews' AI writing partner — with full authority to read, understand, and edit any part of this article.
24
25Stuart is "The Leadership Capability Architect™" — Forbes-featured, LinkedIn Top Voice. His voice is first-person, opinionated, direct, no corporate speak. Contractions throughout. Short punchy sentences mixed with longer exploratory ones. No forbidden phrases: leverage, delve, furthermore, crucial, essentially, empower, unlock, synergy, holistic, paradigm shift.
26
27You have complete awareness of this article. Apply the instruction intelligently. Return the full updated article as JSON.`,rows:10,"data-testid":"textarea-article-edit-prompt",className:"w-full bg-secondary/60 border border-accent-gold/40 rounded text-xs text-foreground px-2.5 py-2 resize-y focus:outline-none focus:ring-1 focus:ring-ring/50 placeholder-muted-foreground font-mono leading-relaxed"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:async()=>{we(!0);try{await fetch("/api/admin/settings/article_edit_prompt",{method:"PUT",headers:{"Content-Type":"application/json",...oe()},body:JSON.stringify({value:V})}),f({title:"Editor prompt saved",description:"New apply actions will use this prompt."})}catch{f({title:"Save failed",variant:"destructive"})}finally{we(!1)}},disabled:Y,"data-testid":"button-save-article-edit-prompt",className:"text-xs bg-accent-gold hover:bg-accent-gold-light text-navy-deep font-semibold px-2.5 py-1 rounded transition-colors disabled:opacity-50",children:Y?"Saving…":"Save Editor Prompt"}),e.jsx("button",{onClick:async()=>{if(await us({title:"Reset to the default editor prompt?",danger:!0})){ne("");try{await fetch("/api/admin/settings/article_edit_prompt",{method:"PUT",headers:{"Content-Type":"application/json",...oe()},body:JSON.stringify({value:""})}),f({title:"Reset to default",description:"The built-in editor prompt will be used."})}catch{f({title:"Reset failed",variant:"destructive"})}}},"data-testid":"button-reset-edit-prompt",className:"text-xs text-muted-foreground hover:text-destructive border border-border px-2.5 py-1 rounded transition-colors",children:"Reset to Default"})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Tip: This prompt is used when you type an instruction in the editor chat and hit Apply. It tells Claude who Stuart is and how to interpret editing requests. The placeholder text above shows the current built-in default."})]})]}),j==="generate"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Article brief"}),e.jsx(ze,{value:N,onChange:g=>P(g.target.value),className:"bg-secondary border-border text-foreground text-sm",rows:4,placeholder:"Describe the article topic, angle, target audience..."})]}),e.jsx("p",{className:"text-xs text-warning-ink/80",children:"⚠ This will replace your current article content."}),e.jsxs("button",{onClick:async()=>{const g=await v("generate_article");
27if(g?.blocks){const C=Array.isArray(g.sources)?g.sources.map(Q=>({organization:Q.organisation??Q.organization??"",title:"",year:Q.year??"",url:Q.url??null})):[];s(Q=>{if(!Q)return Q;const ae=new Set(Q.sources.map(pe=>pe.organization.toLowerCase())),O=C.filter(pe=>pe.organization&&!ae.has(pe.organization.toLowerCase()));return{...Q,blocks:g.blocks,_blockVersion:(Q._blockVersion||0)+1,sources:O.length>0?[...Q.sources,...O]:Q.sources}});const X=C.length;f({title:X>0?`Article generated — ${X} source${X!==1?"s":""} pre-populated in Sources tab`:"Article generated! Switched to Content tab."}),m&&setTimeout(()=>m(C.length>0?"sources":"content"),50)}},disabled:p||!N.trim(),className:"w-full py-2.5 rounded-lg bg-info hover:bg-info/90 disabled:opacity-50 text-foreground text-sm font-semibold flex items-center justify-center gap-2",children:[p?e.jsx(ie,{className:"w-4 h-4 animate-spin"}):e.jsx(ct,{className:"w-4 h-4"}),p?"Generating...":"Generate Article"]})]}),j==="headlines"&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Generate 5 compelling headline options based on your content."}),e.jsxs("button",{onClick:()=>v("generate_headlines"),disabled:p,className:"w-full py-2.5 rounded-lg bg-info hover:bg-info/90 disabled:opacity-50 text-foreground text-sm font-semibold flex items-center justify-center gap-2",children:[p?e.jsx(ie,{className:"w-4 h-4 animate-spin"}):e.jsx(Ds,{className:"w-4 h-4"}),p?"Generating...":"Generate 5 Headlines"]}),T?.suggestions&&e.jsx("div",{className:"space-y-2",children:T.suggestions.map((g,C)=>e.jsxs("button",{onClick:()=>{s(X=>X&&{...X,title:g}),f({title:"Title updated"})},className:"w-full text-left px-3 py-2 bg-secondary hover:bg-secondary rounded-lg border border-border text-xs text-foreground hover:text-foreground transition-colors",children:[e.jsxs("span",{className:"font-bold text-info mr-2",children:[C+1,"."]}),g]},C))})]}),j==="meta"&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Auto-generate SEO meta title (50-60 chars) and description (120-155 chars) from your content."}),e.jsxs("button",{onClick:async()=>{const g=await v("generate_meta");g?.metaTitle&&(s(C=>C&&{...C,metaTitle:g.metaTitle,metaDescription:g.metaDescription}),f({title:"SEO fields updated!"}))},disabled:p,className:"w-full py-2.5 rounded-lg bg-info hover:bg-info/90 disabled:opacity-50 text-foreground text-sm font-semibold flex items-center justify-center gap-2",children:[p?e.jsx(ie,{className:"w-4 h-4 animate-spin"}):e.jsx(Mt,{className:"w-4 h-4"}),p?"Generating...":"Auto-fill SEO Fields"]}),T?.metaTitle&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"p-3 bg-secondary rounded-lg border border-border",children:[e.jsxs("p",{className:"text-xs text-muted-foreground mb-1",children:["Meta Title (",T.metaTitle.length," chars)"]}),e.jsx("p",{className:"text-sm text-foreground",children:T.metaTitle})]}),e.jsxs("div",{className:"p-3 bg-secondary rounded-lg border border-border",children:[e.jsxs("p",{className:"text-xs text-muted-foreground mb-1",children:["Meta Description (",T.metaDescription?.length," chars)"]}),e.jsx("p",{className:"text-xs text-foreground",children:T.metaDescription})]})]})]}),j==="faqs"&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Generate FAQ pairs from your content to qualify for Google's People Also Ask."}),e.jsxs("button",{onClick:async()=>{const g=await v("generate_faqs");g?.faqs&&(s(C=>C&&{...C,faqItems:[...C.faqItems,...g.faqs]}),f({title:`${g.faqs.length} FAQs appended!`}))},disabled:p,className:"w-full py-2.5 rounded-lg bg-info hover:bg-info/90 disabled:opacity-50 text-foreground text-sm font-semibold flex items-center justify-center gap-2",children:[p?e.jsx(ie,{className:"w-4 h-4 animate-spin"}):e.jsx(nt,{className:"w-4 h-4"}),p?"Generating...":"Generate FAQs from Content"]}),T?.faqs&&e.jsx("div",{className:"space-y-2",children:T.faqs.map((g,C)=>e.jsxs("div",{className:"p-3 bg-secondary rounded-lg border border-border",children:[e.jsxs("p",{className:"text-xs font-semibold text-info mb-1",children:["Q: ",g.question]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["A: ",g.answer]})]},C))})]}),j==="takeaways"&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Extract key executive takeaways that help AI answer engines cite your content."}),e.jsxs("button",{onClick:async()=>{const g=await v("generate_takeaways");g?.takeaways&&(s(C=>C&&{...C,keyTakeaways:[...C.keyTakeaways,...g.takeaways]}),f({title:`${g.takeaways.length} takeaways appended!`}))},disabled:p,className:"w-full py-2.5 rounded-lg bg-info hover:bg-info/90 disabled:opacity-50 text-foreground text-sm font-semibold flex items-center justify-center gap-2",children:[p?e.jsx(ie,{className:"w-4 h-4 animate-spin"}):e.jsx(lt,{className:"w-4 h-4"}),p?"Generating...":"Generate Takeaways"]}),T?.takeaways&&e.jsx("div",{className:"space-y-1",children:T.takeaways.map((g,C)=>e.jsxs("div",{className:"flex items-start gap-2 p-2 bg-secondary rounded",children:[e.jsx("span",{className:"text-success text-xs mt-0.5",children:"✓"}),e.jsx("span",{className:"text-xs text-foreground",children:g})]},C))})]}),j==="linkedin"&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Repurpose this article as a LinkedIn post in Stuart's voice — hook, insights, engagement question, hashtags."}),e.jsxs("button",{onClick:()=>v("repurpose_linkedin"),disabled:p,className:"w-full py-2.5 rounded-lg bg-[#0077b5] hover:bg-[#006399] disabled:opacity-50 text-foreground text-sm font-semibold flex items-center justify-center gap-2",children:[p?e.jsx(ie,{className:"w-4 h-4 animate-spin"}):e.jsx(xt,{className:"w-4 h-4"}),p?"Generating...":"Repurpose as LinkedIn Post"]}),T?.post&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:`text-xs ${T.post.length>1300?"text-destructive":"text-muted-foreground"}`,children:[T.post.length,"/1300 chars"]}),e.jsx("button",{onClick:()=>{navigator.clipboard.writeText(T.post),E(!0),setTimeout(()=>E(!1),2e3)},className:"flex items-center gap-1 px-2 py-1 text-xs rounded bg-secondary hover:bg-secondary text-muted-foreground hover:text-foreground transition-colors",children:L?e.jsxs(e.Fragment,{children:[e.jsx(lt,{className:"w-3 h-3 text-success"})," Copied!"]}):e.jsxs(e.Fragment,{children:[e.jsx(_r,{className:"w-3 h-3"})," Copy"]})})]}),e.jsx("pre",{className:"text-xs text-foreground whitespace-pre-wrap bg-secondary border border-border rounded-lg p-3 leading-relaxed",children:T.post}),e.jsxs("button",{onClick:()=>v("repurpose_linkedin"),disabled:p,className:"w-full py-1.5 text-xs text-muted-foreground hover:text-foreground border border-border hover:border-border rounded-lg flex items-center justify-center gap-1 transition-colors",children:[e.jsx(Ue,{className:"w-3 h-3"})," Regenerate"]})]})]}),j==="image"&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Generate an AI cover image for this article using dark navy executive styling with cinematic lighting."}),t.coverImage&&e.jsxs("div",{className:"rounded-lg overflow-hidden border border-border",children:[e.jsx("img",{src:t.coverImage,alt:t.coverImageAlt||t.title,className:"w-full h-auto"}),e.jsx("p",{className:"text-xs text-muted-foreground p-2 truncate",children:t.coverImage})]}),e.jsxs("button",{onClick:async()=>{u(!0),A(null);try{const g=await me("/api/admin/articles/ai-assist",a,{method:"POST",body:JSON.stringify({action:"generate_cover_image",title:t.title,content:t.excerpt||"",focusKeyword:t.focusKeyword||"",slug:t.slug||""})});g?.coverImage&&(s(C=>C&&{...C,coverImage:g.coverImage,coverImageAlt:g.coverImageAlt||C.title}),f({title:"Cover image generated!"}),A({coverImage:g.coverImage}))}catch(g){f({title:"Image generation failed",description:g.message,variant:"destructive"})}finally{u(!1)}},disabled:p||!t.title.trim(),className:"w-full py-2.5 rounded-lg bg-info hover:bg-info/90 disabled:opacity-50 text-foreground text-sm font-semibold flex items-center justify-center gap-2","data-testid":"button-generate-cover-image",children:[p?e.jsx(ie,{className:"w-4 h-4 animate-spin"}):e.jsx(Pt,{className:"w-4 h-4"}),p?"Generating image...":t.coverImage?"Regenerate Cover Image":"Generate Cover Image"]}),T?.coverImage&&e.jsxs("div",{className:"rounded-lg overflow-hidden border border-success/50",children:[e.jsx("img",{src:T.coverImage,alt:t.title,className:"w-full h-auto"}),e.jsx("p",{className:"text-xs text-success p-2",children:"Image saved and applied to article."})]})]}),j==="fixall"&&e.jsx(di,{editor:t,setEditor:s,token:a,onSave:i,onSectionChange:m,loading:p,fixAllStatus:B,setFixAllStatus:U}),j==="reformat"&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Split long paragraphs into shorter, more readable blocks. Preserves all existing headings, callouts, and other block types."}),e.jsx("p",{className:"text-xs text-warning-ink/80",children:"⚠ This will replace your current content blocks with reformatted versions."}),e.jsxs("button",{onClick:async()=>{const g=await v("reformat_content",{blocks:t.blocks});g?.blocks?.length&&(s(C=>C&&{...C,blocks:g.blocks,_blockVersion:(C._blockVersion||0)+1}),f({title:`Content reformatted: ${g.blocks.length} blocks`}),m&&setTimeout(()=>m("content"),50))},disabled:p||t.blocks.length===0,className:"w-full py-2.5 rounded-lg bg-info hover:bg-info/90 disabled:opacity-50 text-foreground text-sm font-semibold flex items-center justify-center gap-2","data-testid":"button-reformat-content",children:[p?e.jsx(ie,{className:"w-4 h-4 animate-spin"}):e.jsx(Ue,{className:"w-4 h-4"}),p?"Reformatting...":"Reformat Content"]})]})]})]})]})}const hi=[{label:"Find real sources",text:"Search for specific reports and studies that back the statistics in this article. Find real URLs to actual reports, not just organization homepages. Suggest them for my review."},{label:"Find unverifiable stats",text:"Find all statistics in this article that cannot be backed by a real source URL. For each one, show me the original sentence, 2-3 replacement options using real verified sources with exact URLs, and 2-3 qualitative rewrites in Stuart's expert voice. Let me choose which version to keep — do not apply any changes automatically."},{label:"Verify source URLs",text:"Check each of my current sources and tell me which URLs are live and which need attention."},{label:"Make publish-ready",text:"Full publish-readiness check: find specific report URLs for all stat claims and suggest them for my review, then give me a clear YES/NO verdict on whether this article is ready to publish with a list of anything still needing attention."}];function mi({editor:t,setEditor:s,token:a,saveArticle:n}){const{toast:i}=De(),[m,j]=h.useState([]),[k,p]=h.useState(""),[u,N]=h.useState(!1),[P,x]=h.useState([]),[H,T]=h.useState([]),[A,L]=h.useState(!1),[E,B]=h.useState({organization:"",title:"",year:"",url:"",statistic:""}),U=h.useRef(null);h.useEffect(()=>{zr(U.current)},[m]);const c=async l=>{const b=(l??k).trim();if(!b||u)return;p("");const M={role:"user",content:b};j(W=>[...W,M]),N(!0);try{const W=await fetch("/api/admin/articles/ai-assist",{method:"POST",headers:{"Content-Type":"application/json",...oe()},body:JSON.stringify({action:"manage_sources",instruction:b,blocks:t.blocks,sources:t.sources,title:t.title})});if(!W.ok){const w=await W.json().catch(()=>({error:"Request failed"}));throw new Error(w.error||"Request failed")}const te=await W.json();j(w=>[...w,{role:"assistant",content:te.chatResponse||"Done."}]);const V=Array.isArray(te.blocks)&&te.blocks.length>0,ne=Array.isArray(te.sources),Y=Array.isArray(te.suggestions)&&te.suggestions.length>
270,we=Array.isArray(te.pendingFixes)&&te.pendingFixes.length>0;if(Y&&x(te.suggestions),we&&T(te.pendingFixes),(V||ne)&&(s(w=>w&&{...w,...ne?{sources:te.sources}:{},...V?{blocks:te.blocks}:{}}),V&&n)){try{await n(void 0,{blocks:te.blocks})}catch{}i({title:"Article updated",description:"Changes saved automatically."})}}catch(W){j(te=>[...te,{role:"assistant",content:`Sorry, I couldn't complete that. ${W.message}`}]),i({title:"Sources assistant error",description:W.message,variant:"destructive"})}finally{N(!1)}},D=l=>{const b=P[l],M={organization:b.organization,title:b.title||b.organization,year:b.year||void 0,url:b.url||null,...b.statistic?{statistic:b.statistic}:{}};s(W=>W&&{...W,sources:[...W.sources,M]}),x(W=>W.filter((te,V)=>V!==l)),i({title:"Source added",description:b.organization})},$=l=>{x(b=>b.filter((M,W)=>W!==l))},F=async(l,b)=>{const M=t.blocks.map(W=>{if(typeof W.content=="string"&&W.content.includes(l.original))return{...W,content:W.content.replace(l.original,b)};if(Array.isArray(W.items)){let te=!1;const V=W.items.map(ne=>typeof ne=="string"&&ne.includes(l.original)?(te=!0,ne.replace(l.original,b)):ne&&typeof ne=="object"&&typeof ne.content=="string"&&ne.content.includes(l.original)?(te=!0,{...ne,content:ne.content.replace(l.original,b)}):ne);return te?{...W,items:V}:W}return W});if(s(W=>W&&{...W,blocks:M}),T(W=>W.filter(te=>te.id!==l.id)),n)try{await n(void 0,{blocks:M}),i({title:"Stat updated",description:"Sentence replaced and saved."})}catch{}},J=l=>{T(b=>b.filter(M=>M.id!==l))},re=()=>{const l=P.map(b=>({organization:b.organization,title:b.title||b.organization,year:b.year||void 0,url:b.url||null,...b.statistic?{statistic:b.statistic}:{}}));s(b=>b&&{...b,sources:[...b.sources,...l]}),x([]),i({title:`${l.length} sources added`})},I=l=>{s(b=>b&&{...b,sources:b.sources.filter((M,W)=>W!==l)})},o=()=>{if(!E.organization.trim())return;const l={organization:E.organization.trim(),title:E.title.trim()||E.organization.trim(),year:E.year.trim()||void 0,url:E.url.trim()||null,...E.statistic.trim()?{statistic:E.statistic.trim()}:{}};s(b=>b&&{...b,sources:[...b.sources,l]}),B({organization:"",title:"",year:"",url:"",statistic:""}),L(!1),i({title:"Source added"})},S=m.length===0;return e.jsxs("div",{className:"flex flex-col gap-4 p-4 h-full",children:[e.jsxs("div",{className:"flex flex-col bg-card rounded-xl border border-border overflow-hidden",children:[e.jsxs("div",{className:"overflow-y-auto p-4 space-y-3",style:{minHeight:160,maxHeight:320},children:[m.length===0&&e.jsxs("div",{className:"flex flex-col items-center justify-center gap-2 py-4 text-center",children:[e.jsx($e,{className:"w-5 h-5 text-info/50"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Ask me to find, fix, or verify sources — or tap a quick action below."})]}),m.map((l,b)=>e.jsx("div",{className:`flex ${l.role==="user"?"justify-end":"justify-start"}`,children:e.jsx("div",{className:`max-w-[88%] rounded-lg px-3 py-2 text-xs leading-relaxed whitespace-pre-wrap ${l.role==="user"?"bg-info/25 text-info-foreground border border-info/30":"bg-secondary text-foreground border border-border"}`,children:l.content})},b)),u&&e.jsx("div",{className:"flex justify-start",children:e.jsx("div",{className:"bg-secondary border border-border rounded-lg px-3 py-2",children:e.jsx(ie,{className:"w-3 h-3 animate-spin text-info"})})}),e.jsx("div",{ref:U})]}),S&&e.jsx("div",{className:"px-3 pb-2 flex flex-wrap gap-1.5",children:hi.map(l=>e.jsx("button",{onClick:()=>c(l.text),disabled:u,className:"px-2.5 py-1 text-[10px] rounded-full bg-info/15 hover:bg-info/25 text-info border border-info/30 transition-colors disabled:opacity-50","data-testid":`button-sources-quick-${l.label.toLowerCase().replace(/\s+/g,"-")}`,children:l.label},l.label))}),e.jsxs("div",{className:"p-3 border-t border-border flex gap-2",children:[e.jsx("input",{type:"text",value:k,onChange:l=>p(l.target.value),onKeyDown:l=>l.key==="Enter"&&!l.shiftKey&&c(),placeholder:'e.g. "Fix all unverifiable stats" or "Find sources for the engagement data"',className:"flex-1 bg-secondary border border-border rounded-lg px-3 py-2 text-xs text-foreground placeholder-muted-foreground focus:outline-none focus:border-info transition-colors",disabled:u,"data-testid":"input-sources-chat"}),e.jsx("button",{onClick:()=>c(),disabled:u||!k.trim(),className:"px-3 py-2 bg-info hover:bg-info/90 disabled:opacity-40 rounded-lg text-foreground transition-colors","data-testid":"button-sources-send",children:e.jsx(xt,{className:"w-3.5 h-3.5"})})]})]}),H.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-xs font-semibold text-destructive uppercase tracking-wider",children:["Stats needing verification (",H.length,") — choose a replacement"]}),e.jsxs("button",{onClick:()=>T([]),className:"flex items-center gap-1 px-2 py-1 text-[10px] rounded bg-secondary hover:bg-secondary text-muted-foreground hover:text-foreground border border-border transition-colors","data-testid":"button-pending-fixes-dismiss-all",children:[e.jsx(Ae,{className:"w-3 h-3"})," Dismiss all"]})]}),e.jsx("div",{className:"space-y-3",children:H.map(l=>e.jsxs("div",{className:"bg-destructive/15 border border-destructive/30 rounded-xl p-3 space-y-2.5","data-testid":`pending-fix-${l.id}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"text-[10px] font-bold uppercase tracking-wider text-destructive-ink mb-0.5",children:["Unverifiable: ",l.claim]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground italic leading-relaxed line-clamp-2",children:['"',l.original,'"']})]}),e.jsx("button",{onClick:()=>J(l.id),className:"text-muted-foreground hover:text-muted-foreground shrink-0 mt-0.5 transition-colors","data-testid":`button-pending-fix-dismiss-${l.id}`,title:"Keep original",children:e.jsx(Ae,{className:"w-3.5 h-3.5"})})]}),l.quantitativeOptions.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-[10px] font-semibold text-success-ink uppercase tracking-wider",children:"Verified alternatives"}),l.quantitativeOptions.map((b,M)=>e.jsxs("div",{className:"bg-success/15 border border-success/20 rounded-lg p-2.5 space-y-1","data-testid":`pending-fix-quant-${l.id}-${M}`,children:[e.jsx("p",{className:"text-[11px] text-foreground leading-relaxed",children:b.text}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[e.jsxs("span",{className:"text-[10px] text-success-ink font-medium shrink-0",children:[b.organization,b.year?` (${b.year})`:""]}),b.url&&e.jsxs("a",{href:b.url,target:"_blank",rel:"noopener noreferrer",className:"text-[10px] text-info hover:text-info flex items-center gap-0.5 truncate transition-colors",title:b.url,children:[e.jsx(_e,{className:"w-2.5 h-2.5 shrink-0"}),e.jsx("span",{className:"truncate",children:b.url})]})]}),e.jsxs("button",{onClick:()=>F(l,b.text),className:"shrink-0 flex items-center gap-0.5 px-2 py-0.5 text-[10px] rounded bg-success/25 hover:bg-success/40 text-success-ink border border-success/30 transition-colors","data-testid":`button-apply-quant-${l.id}-${M}`,children:[e.jsx(Ct,{className:"w-2.5 h-2.5"})," Use this"]})]})]},M))]}),l.qualitativeOptions.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-[10px] font-semibold text-info uppercase tracking-wider",children:"Qualitative rewrites"}),l.qualitativeOptions.map((b,M)=>e.jsxs("div",{className:"bg-info/20 border border-info/20 rounded-lg p-2.5 flex items-start gap-2","data-testid":`pending-fix-qual-${l.id}-${M}`,children:[e.jsx("p",{className:"flex-1 text-[11px] text-foreground leading-relaxed",children:b}),e.jsxs("button",{onClick:()=>F(l,b),className:"shrink-0 flex items-center gap-0.5 px-2 py-0.5 text-[10px] rounded bg-info/25 hover:bg-info/40 text-info border border-info/30 transition-colors","data-testid":`button-apply-qual-${l.id}-${M}`,children:[e.jsx(Ct,{className:"w-2.5 h-2.5"})," Use this"]})]},M))]})]},l.id))})]}),P.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-xs font-semibold text-warning-ink uppercase tracking-wider",children:["Suggested sources (",P.length,") — review before adding"]}),e.jsxs("button",{onClick:re,className:"flex items-center gap-1 px-2 py-1 text-[10px] rounded bg-success/20 hover:bg-success/30 text-success-ink border border-success/30 transition-colors","data-testid":"button-sources-accept-all",children:[e.jsx(Ct,{className:"w-3 h-3"})," Accept all"]})]}),e.jsx("div",{className:"space-y-1.5",children:P.map((l,b)=>e.jsxs("div",{className:"flex items-start gap-2 bg-warning/10 border border-warning/30 rounded-lg px-3 py-2.5","data-testid":`suggestion-item-${b}`,children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"text-xs font-medium text-foreground",children:[l.organization,l.year?e.jsxs("span",{className:"text-muted-foreground font-normal",children:[" (",l.year,")"]}):null]}),l.title&&l.title!==l.organization&&e.jsx("p",{className:"text-[10px] text-muted-foreground truncate mt-0.5",children:l.title}),l.snippet&&e.jsx("p",{className:"text-[10px] text-warning-ink mt-0.5 italic",children:l.snippet}),l.url?e.jsxs("div",{className:"mt-1 flex items-start gap-1.5 flex-wrap",children:[l.urlStatus==="live"&&e.jsx("span",{className:"shrink-0 inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-[9px] font-semibold bg-success/20 text-success-ink border border-success/30",children:"✓ Live"}),l.urlStatus==="hub_fallback"&&e.jsx("span",{className:"shrink-0 inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded text-[9px] font-semibold bg-warning/20 text-warning-ink border border-warning/30",title:"Specific report URL didn't resolve — linked to this org's research hub instead",children:"↗ Insights hub"}),e.jsxs("a",{href:l.url,target:"_blank",rel:"noopener noreferrer",className:"text-[10px] text-info hover:text-info flex items-center gap-0.5 min-w-0 transition-colors",style:{wordBreak:"break-all"},children:[e.jsx(_e,{className:"w-2.5 h-2.5 shrink-0"}),e.jsx("span",{className:"truncate",children:l.url})]})]}):e.jsx("span",{className:"text-[10px] text-muted-foreground mt-0.5 block",children:"No URL — add manually if needed"})]}),e.jsxs("div",{className:"flex flex-col gap-1 shrink-0 mt-0.5",children:[e.jsxs("button",{onClick:()=>D(b),className:"flex items-center gap-0.5 px-2 py-0.5 text-[10px] rounded bg-success/20 hover:bg-success/35 text-success-ink border border-success/30 transition-colors","data-testid":`button-suggestion-accept-${b}`,title:"Add to sources",children:[e.jsx(Ct,{className:"w-2.5 h-2.5"})," Add"]}),e.jsxs("button",{onClick:()=>$(b),className:"flex items-center gap-0.5 px-2 py-0.5 text-[10px] rounded bg-secondary hover:bg-secondary text-muted-foreground hover:text-foreground border border-border transition-colors","data-testid":`button-suggestion-dismiss-${b}`,title:"Dismiss",children:[e.jsx(Ae,{className:"w-2.5 h-2.5"})," Skip"]})]})]},b))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-xs font-semibold text-foreground uppercase tracking-wider",children:["Sources (",t.sources.length,")"]}),e.jsxs("button",{onClick:()=>L(l=>!l),className:"flex items-center gap-1 px-2 py-1 text-[10px] rounded bg-secondary hover:bg-secondary text-muted-foreground hover:text-foreground border border-border transition-colors","data-testid":"button-sources-add-manual",children:[e.jsx(gt,{className:"w-3 h-3"})," Add manually"]})]}),A&&e.jsxs("div",{className:"bg-card border border-border rounded-lg p-3 space-y-2",children:[e.jsx("input",{type:"text",value:E.organization,onChange:l=>B(b=>({...b,organization:l.target.value})),placeholder:"Organization (e.g. McKinsey & Company)",className:"w-full bg-secondary border border-border rounded px-2 py-1.5 text-xs text-foreground placeholder-muted-foreground focus:outline-none focus:border-info","data-testid":"input-source-organization"}),e.jsx("input",{type:"text",value:E.title,onChange:l=>B(b=>({...b,title:l.target.value})),placeholder:"Report title (optional)",className:"w-full bg-secondary border border-border rounded px-2 py-1.5 text-xs text-foreground placeholder-muted-foreground focus:outline-none focus:border-info","data-testid":"input-source-title"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx("input",{type:"text",value:E.year,onChange:l=>B(b=>({...b,year:l.target.value})),placeholder:"Year (e.g. 2024)",className:"bg-secondary border border-border rounded px-2 py-1.5 text-xs text-foreground placeholder-muted-foreground focus:outline-none focus:border-info","data-testid":"input-source-year"}),e.jsx("input",{type:"url",value:E.url,onChange:l=>B(b=>({...b,url:l.target.value})),placeholder:"URL",className:"bg-secondary border border-border rounded px-2 py-1.5 text-xs text-foreground placeholder-muted-foreground focus:outline-none focus:border-info","data-testid":"input-source-url"})]}),e.jsx("input",{type:"text",value:E.statistic,onChange:l=>B(b=>({...b,statistic:l.target.value})),placeholder:"Statistic cited (e.g. 75% of leadership programs fail)",className:"w-full bg-secondary border border-border rounded px-2 py-1.5 text-xs text-foreground placeholder-muted-foreground focus:outline-none focus:border-info","data-testid":"input-source-statistic"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:o,disabled:!E.organization.trim(),className:"px-3 py-1 bg-info hover:bg-info/90 disabled:opacity-40 text-foreground text-xs rounded transition-colors","data-testid":"button-source-add-confirm",children:"Add"}),e.jsx("button",{onClick:()=>L(!1),className:"px-3 py-1 bg-secondary hover:bg-secondary text-muted-foreground text-xs rounded transition-colors","data-testid":"button-source-add-cancel",children:"Cancel"})]})]}),t.sources.length===0?e.jsx("p",{className:"text-xs text-muted-foreground text-center py-4",children:"No sources yet — use the chat above to find some, or add one manually."}):e.jsx("div",{className:"space-y-1.5",children:t.sources.map((l,b)=>e.jsxs("div",{className:"flex items-start gap-2 bg-card border border-border rounded-lg px-3 py-2.5","data-testid":`source-item-${b}`,children:[e.jsxs("span",{className:"text-[10px] text-muted-foreground font-mono shrink-0 mt-0.5 min-w-[1rem]",children:[b+1,"."]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"text-xs font-medium text-foreground truncate",children:[l.organization,l.year?e.jsxs("span",{className:"text-muted-foreground font-normal",children:[" (",l.year,")"]}):null]}),l.title&&l.title!==l.organization&&e.jsx("p",{className:"text-[10px] text-muted-foreground truncate mt-0.5",children:l.title}),l.statistic&&e.jsxs("p",{className:"text-[10px] text-success-ink truncate mt-0.5 italic",title:l.statistic,children:['"',l.statistic,'"']}),l.url?e.jsxs("a",{href:l.url,target:"_blank",rel:"noopener noreferrer",className:"mt-0.5 text-[10px] text-info hover:text-info flex items-center gap-0.5 max-w-full transition-colors",style:{wordBreak:"break-all"},children:[e.jsx(_e,{className:"w-2.5 h-2.5 shrink-0"}),e.jsx("span",{className:"truncate",children:l.url})]}):e.jsx("span",{className:"text-[10px] text-warning-ink mt-0.5 block",children:"No URL set"})]}),e.jsx("button",{onClick:()=>I(b),className:"text-muted-foreground hover:text-destructive transition-colors shrink-0 mt-0.5","data-testid":`button-source-remove-${b}`,title:"Remove source",children:e.jsx(Ae,{className:"w-3.5 h-3.5"})})]},b))})]})]})}function pi(t){const s=[],a=/<a\s+[^>]*href="([^"]+)"[^>]*>([^<]+)<\/a>/g;for(const n of t){const i=n.content||n.text||"";
27if(typeof i!="string")continue;a.lastIndex=0;let m;for(;(m=a.exec(i))!==null;)m[1].startsWith("/")&&s.push({path:m[1],anchorText:m[2]})}return s}const gi=t=>t==="high"?"bg-success/15 text-success-ink border-success/30":t==="medium"?"bg-warning/15 text-warning-ink border-warning/30":"bg-secondary text-muted-foreground border-border";function xi({editor:t,setEditor:s,token:a}){const{toast:n}=De(),[i,m]=h.useState(null),[j,k]=h.useState(!1),[p,u]=h.useState(!1),[N,P]=h.useState(new Set),[x,H]=h.useState({}),T=pi(t.blocks),A=async()=>{k(!0);try{const B=await fetch("/api/admin/articles/ai-assist",{method:"POST",headers:{"Content-Type":"application/json",...oe()},body:JSON.stringify({action:"suggest_internal_links",title:t.title,brief:t.focusKeyword||t.title,currentSlug:t.slug,blocks:t.blocks})});if(B.ok){const{suggestions:U}=await B.json(),c=U||[];m(c),P(new Set(c.map((D,$)=>$))),H({})}else n({title:"Failed to generate suggestions",variant:"destructive"})}catch{n({title:"Failed to generate suggestions",variant:"destructive"})}k(!1)},L=async()=>{if(!i||N.size===0)return;const B=Array.from(N).map(U=>({path:i[U].path,anchorText:x[U]??i[U].anchorText}));u(!0);try{const U=await fetch("/api/admin/articles/ai-assist",{method:"POST",headers:{"Content-Type":"application/json",...oe()},body:JSON.stringify({action:"apply_internal_links",blocks:t.blocks,links:B})});if(U.ok){const{blocks:c}=await U.json();Array.isArray(c)&&c.length>0&&(s({...t,blocks:c,_blockVersion:(t._blockVersion??0)+1}),m(null),P(new Set),H({}))}else n({title:"Failed to apply links",variant:"destructive"})}catch{n({title:"Failed to apply links",variant:"destructive"})}u(!1)},E=B=>{P(U=>{const c=new Set(U);return c.has(B)?c.delete(B):c.add(B),c})};return e.jsxs("div",{className:"space-y-6 max-w-3xl",children:[e.jsxs("div",{className:"bg-info/15 border border-info/25 rounded-lg p-3 text-xs text-info-ink space-y-1",children:[e.jsx("p",{className:"font-medium text-info-ink",children:"Internal Link Builder"}),e.jsxs("p",{children:["AI suggests 4-5 relevant links ranked by topic overlap and SEO opportunity — articles with fewer inbound links are flagged as ",e.jsx("strong",{className:"text-info",children:"low hanging fruit"})," (a boost there has more impact). Edit any anchor text, toggle which links to include, then apply."]})]}),T.length>0&&e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold text-foreground mb-2 flex items-center gap-2",children:[e.jsx(Tt,{className:"w-4 h-4 text-success"}),"Already linked in this article",e.jsxs("span",{className:"text-xs font-normal text-muted-foreground",children:[T.length," found"]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:T.map((B,U)=>e.jsxs("div",{className:"bg-success/15 border border-success/30 rounded px-2.5 py-1.5 text-xs flex items-center gap-1.5","data-testid":`chip-existing-link-${U}`,children:[e.jsx(Te,{className:"w-3 h-3 text-success shrink-0"}),e.jsx("span",{className:"text-success-ink",children:B.anchorText}),e.jsx("span",{className:"text-muted-foreground",children:"→"}),e.jsx("code",{className:"text-muted-foreground text-[10px]",children:B.path})]},U))})]}),i?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"text-sm font-semibold text-foreground flex items-center gap-2",children:[e.jsx($e,{className:"w-4 h-4 text-accent-gold"}),"Suggestions",e.jsxs("span",{className:"text-xs font-normal text-muted-foreground",children:[N.size," of ",i.length," selected"]})]}),e.jsxs(ee,{size:"sm",variant:"outline",onClick:A,disabled:j||p,className:"border-border text-muted-foreground hover:text-foreground text-xs","data-testid":"button-refresh-links",children:[e.jsx(Ue,{className:`w-3 h-3 mr-1 ${j?"animate-spin":""}`}),"Refresh"]})]}),i.length===0?e.jsx("p",{className:"text-xs text-muted-foreground italic py-4 text-center",children:"No strong link candidates found — try publishing more articles or add a focus keyword."}):e.jsx("div",{className:"space-y-2",children:i.map((B,U)=>
27{const c=N.has(U),D=x[U]??B.anchorText,$=B.inboundCount<3&&B.inboundCount!==99;return e.jsx("div",{onClick:()=>E(U),className:`rounded-lg border p-3 cursor-pointer transition-all ${c?"bg-accent-gold/15 border-accent-gold/40":"bg-card border-border opacity-55 hover:opacity-70"}`,"data-testid":`card-link-${U}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"mt-0.5 shrink-0",children:c?e.jsx(Te,{className:"w-4 h-4 text-accent-gold"}):e.jsx(Qs,{className:"w-4 h-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm font-medium text-foreground leading-snug",children:B.title}),e.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded border capitalize ${gi(B.priority)}`,children:B.priority}),$&&e.jsxs("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded border bg-info/10 text-info border-info/30 flex items-center gap-1",children:[e.jsx(Wr,{className:"w-2.5 h-2.5"}),B.inboundCount===0?"0 inbound links":`${B.inboundCount} inbound`," — low hanging fruit"]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] text-muted-foreground",children:[e.jsx(rs,{className:"w-3 h-3 shrink-0"}),e.jsx("code",{className:"text-muted-foreground",children:B.path}),e.jsx("a",{href:B.path,target:"_blank",rel:"noopener noreferrer",onClick:F=>F.stopPropagation(),className:"text-muted-foreground hover:text-info",children:e.jsx(_e,{className:"w-3 h-3"})})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-snug",children:B.reason}),e.jsxs("div",{onClick:F=>F.stopPropagation(),className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] text-muted-foreground shrink-0",children:"Anchor text:"}),e.jsx(he,{value:D,onChange:F=>H(J=>({...J,[U]:F.target.value})),placeholder:"anchor text…",className:"bg-secondary border-border text-accent-gold-ink text-xs h-7 flex-1","data-testid":`input-anchor-${U}`})]})]})]})},U)})}),i.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(ee,{onClick:L,disabled:p||N.size===0,className:"w-full bg-accent-gold hover:bg-accent-gold-light text-navy-deep font-semibold","data-testid":"button-apply-links",children:p?e.jsxs(e.Fragment,{children:[e.jsx(ie,{className:"w-4 h-4 mr-2 animate-spin"}),"Inserting links into article…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Se,{className:"w-4 h-4 mr-2"}),"Apply ",N.size," link",N.size!==1?"s":""," to article"]})}),e.jsx("p",{className:"text-[11px] text-muted-foreground text-center",children:"The AI inserts each link at the most natural point in y
27our paragraph text, then returns the updated article. Save after applying to persist changes."})]})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-10 gap-4 border border-dashed border-border rounded-lg",children:[e.jsxs("div",{className:"text-center space-y-1",children:[e.jsx("p",{className:"text-sm text-muted-foreground font-medium",children:"No link suggestions yet"}),e.jsx("p",{className:"text-xs text-muted-foreground max-w-sm",children:"Click below to analyse this article and find the best internal links to add — prioritising low-authority articles that need an SEO boost."})]}),e.jsxs(ee,{onClick:A,disabled:j||!t.title,className:"bg-accent-gold hover:bg-accent-gold-light text-navy-deep font-semibold gap-2","data-testid":"button-suggest-links",children:[j?e.jsx(ie,{className:"w-4 h-4 animate-spin"}):e.jsx($e,{className:"w-4 h-4"}),j?"Analysing article…":"Suggest internal links"]})]})]})}function fi({editor:t,setEditor:s,token:a,saving:n,saveStatus:i,saveArticle:m,showAiPanel:j,setShowAiPanel:k,editorSection:p,setEditorSection:u,canPublish:N,canFeature:P,togglePublish:x,audioJobStatus:H,audioUrl:T,generateAudio:A,permissions:L,canEditAny:E}){const B=m,{toast:U}=De(),[c,D]=h.useState("idle"),[$,F]=h.useState([]),[J,re]=h.useState(!1),[I,o]=h.useState(!1),[S,l]=h.useState(!1),[b,M]=h.useState(null),W=h.useRef(s);W.current=s,h.useEffect(()=>{const w=f=>{const r=f.detail?.items;!Array.isArray(r)||r.length===0||(W.current(v=>v&&{...v,keyTakeaways:[...v.keyTakeaways,...r.filter(Boolean)]}),u("seo"),U({title:`${r.length} item${r.length!==1?"s":""} moved to Key Takeaways`}))},R=f=>{const r=f.detail?.items;!Array.isArray(r)||r.length===0||(W.current(v=>v&&{...v,faqItems:[...v.faqItems,...r.filter(_=>_?.question)]}),u("seo"),U({title:`${r.length} FAQ item${r.length!==1?"s":""} moved to FAQ field`}))};return window.addEventListener("article:convert-to-key-takeaways",w),window.addEventListener("article:convert-to-faq-items",R),()=>{window.removeEventListener("article:convert-to-key-takeaways",w),window.removeEventListener("article:convert-to-faq-items",R)}},[u,U]);const te=c!=="idle",V=async w=>{if(D("publishing"),w.length>0&&t.id)try{const R=await fetch(`/api/admin/articles/${t.id}/batch-dismiss-stats`,{method:"POST",headers:{"Content-Type":"application/json",...oe()},body:JSON.stringify({originalTexts:w.map(f=>f.original)})});if(R.ok){const f=await R.json();s(r=>r&&{...r,statVerificationLog:f.verificationLog})}}catch{}try{await x()}finally{D("idle"),F([])}},ne=async()=>{if(t.id){l(!0),D("idle"),F([]);try{try{await m()}catch{}const w=await fetch(`/api/admin/articles/${t.id}/verify-stats`,{method:"POST",headers:{...oe()}});if(!w.ok){const C=await w.json().catch(()=>({}));throw new Error(C.error||"Verification failed")}const R=await w.json();s(C=>C&&{...C,statVerificationLog:R.verificationLog});const f=R.results??[],r=f.filter(C=>!C.verified&&C.replacementStat),v=f.filter(C=>C.verified),_=f.filter(C=>!C.verified&&!C.replacementStat),K=[];let g=[...t.blocks];for(const C of r){const X=!C.replacementUrl;try{const Q=await fetch(`/api/admin/articles/${t.id}/apply-stat-replacement`,{method:"POST",headers:{"Content-Type":"application/json",...oe()},body:JSON.stringify({originalSentence:C.original,replacementSentence:C.replacementStat,...X?{}:{sourceOrg:C.replacementOrg,sourceUrl:C.replacementUrl},currentBlocks:g})});if(Q.ok){const ae=await Q.json();Array.isArray(ae.blocks)&&(g=ae.blocks),K.push({original:C.original,status:X?"rewritten":"replaced",url:C.replacementUrl,replacementStat:C.replacementStat,replacementOrg:C.replacementOrg})}else K.push({original:C.original,status:"unresolvable"})}catch{K.push({original:C.original,status:"unresolvable"})}}if(r.length>0){s(C=>{if(!C)return C;const X=R.sources??C.sources;return{...C,blocks:g,sources:X}});try{await m(void 0,{blocks:g})}catch{}}for(const C of v)K.push({original:C.original,status:"verified",url:C.url});for(const C of _)K.push({original:C.original,status:"unresolvable"});M(K)}catch(w){U({title:"Fix stats failed",description:w.message,variant:"destructive"})}finally{l(!1)}}},Y=async()=>
27{if(t.status==="published"){await x();return}if(!t.id){await x();return}D("saving");try{await m()}catch{}let w=null;try{t.statVerificationLog&&(w=JSON.parse(t.statVerificationLog))}catch{}const R=new Set(w?.dismissedStats??[]),f=(w?.results??[]).filter(r=>!r.verified&&(!r.replacementStat||!r.replacementUrl)&&!R.has(r.original)).map(r=>({original:r.original}));if(f.length>0){F(f),D("confirming");return}await V([])},we=()=>{switch(c){case"saving":return e.jsxs(e.Fragment,{children:[e.jsx(ie,{className:"w-3.5 h-3.5 mr-1 animate-spin"}),"Saving…"]});case"confirming":return e.jsxs(e.Fragment,{children:[e.jsx(ie,{className:"w-3.5 h-3.5 mr-1 animate-spin"}),"Needs your call…"]});case"publishing":return e.jsxs(e.Fragment,{children:[e.jsx(ie,{className:"w-3.5 h-3.5 mr-1 animate-spin"}),"Publishing…"]});default:return e.jsxs(e.Fragment,{children:[e.jsx(qt,{className:"w-3.5 h-3.5 mr-1"}),"Publish"]})}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between bg-card border border-border rounded-xl px-4 py-3 sticky top-0 z-10",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{onClick:()=>{s(null),k(!1)},className:"text-muted-foreground hover:text-foreground",children:e.jsx(pt,{className:"w-4 h-4"})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:t.id?"Editing article":"New article"}),e.jsx(Gs,{status:t.status}),t.featured&&e.jsx(ve,{className:"border-accent-gold/30 text-accent-gold text-xs",children:"Featured"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[i==="saving"&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Saving…"}),i==="saved"&&e.jsxs("span",{className:"text-xs text-success flex items-center gap-1",children:[e.jsx(Te,{className:"w-3 h-3"})," Saved"]}),i==="error"&&e.jsx("span",{className:"text-xs text-destructive font-medium",children:"Autosave failed — check connection"}),e.jsxs("button",{onClick:()=>k(!j),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold transition-colors ${j?"bg-info text-foreground":"bg-info/20 text-info hover:bg-info/30"}`,"data-testid":"toggle-article-ai",children:[e.jsx($e,{className:"w-3.5 h-3.5"})," AI Write"]}),t.id&&e.jsx("button",{onClick:ne,disabled:S||n||te,title:"Scan the article for unverified stats, auto-apply replacements with real source URLs, then show you a report to double-check.",className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold transition-colors bg-accent-gold/15 text-accent-gold-ink hover:bg-accent-gold/25 disabled:opacity-50","data-testid":"button-fix-stats",children:S?e.jsxs(e.Fragment,{children:[e.jsx(ie,{className:"w-3.5 h-3.5 animate-spin"})," Fixing stats…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Se,{className:"w-3.5 h-3.5"})," Fix Stats"]})}),t.id&&E&&e.jsx("button",{onClick:A,disabled:H==="pending"||H==="processing","data-testid":"button-generate-audio",title:T?"Regenerate audio narration":"Generate audio narration",className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold transition-colors ${H==="completed"?"bg-success/20 text-success hover:bg-success/30":"bg-secondary/50 text-foreground hover:bg-secondary"} disabled:opacity-50`,children:H==="pending"||H==="processing"?e.jsxs(e.Fragment,{children:[e.jsx(ie,{className:"w-3.5 h-3.5 animate-spin"})," Generating..."]}):T?e.jsxs(e.Fragment,{children:[e.jsx(Is,{className:"w-3.5 h-3.5 text-success"})," Audio ready"]}):e.jsxs(e.Fragment,{children:[e.jsx(Is,{className:"w-3.5 h-3.5"})," Generate Audio"]})}),T&&H==="completed"&&e.jsxs("a",{href:T,target:"_blank",rel:"noreferrer",className:"flex items-center gap-1 px-2 py-1.5 rounded text-xs text-success hover:text-success transition-colors","data-testid":"link-audio-play",title:"Play audio",children:[e.jsx(qr,{className:"w-3.5 h-3.5"})," Play"]}),t.id&&e.jsx("a",{href:t.status==="published"?`/insights/${t.slug}`:`/insights/${t.slug}?preview=1`,target:"_blank",rel:"noreferrer",className:"text-muted-foreground hover:text-foreground p-1.5 rounded",title:t.status==="published"?"View live article":"Preview draft",children:e.jsx(It,{className:"w-4 h-4"})}),N&&(t.status==="published"?e.jsxs(ee,{size:"sm",variant:"outline",onClick:()=>Y(),disabled:n||te,className:"border-border text-sm text-warning-ink hover:text-warning-ink",children:[e.jsx(Xs,{className:"w-3.5 h-3.5 mr-1"}),"Unpublish"]}):e.jsx(ee,{size:"sm",variant:"outline",onClick:()=>Y(),disabled:n||te,className:"border-border text-sm text-success hover:text-success min-w-[130px] justify-center",children:we()})),e.jsxs(ee,{size:"sm",onClick:()=>m(),disabled:n,className:"bg-accent-gold hover:bg-accent-gold-light text-navy-deep font-semibold",children:[e.jsx(Ur,{className:"w-3.5 h-3.5 mr-1"}),n?"Saving...":"Save"]})]})]}),e.jsxs("div",{className:`${j?"grid grid-cols-[1fr_340px] gap-4 items-start":""}`,children:[e.jsxs("div",{className:"space-y-4 min-w-0",children:[e.jsx("div",{className:"flex gap-1 border-b border-border pb-0",children:["basics","content","seo","links","sources"].map(w=>{const R=w==="sources"?t.sources.filter(r=>!r.url).length:0,f=w==="seo"?"SEO & Schema":w==="links"?"Links":w.charAt(0).toUpperCase()+w.slice(1);return e.jsxs("button",{onClick:()=>u(w),className:`px-4 py-2 text-sm font-medium capitalize border-b-2 transition-colors flex items-center gap-1.5 ${p===w?"border-accent-gold text-accent-gold":"border-transparent text-muted-foreground hover:text-foreground"}`,"data-testid":`tab-${w}`,children:[f,R>0&&e.jsx("span",{className:"inline-flex items-center justify-center w-4 h-4 text-[9px] font-bold bg-accent-gold/15 text-accent-gold-ink rounded-full border border-accent-gold/30",children:R})]},w)})}),p==="basics"&&(()=>{const w=v=>/\.webp(\?|$)/i.test(v)||v.includes("object-storage")||v.includes("storage.googleapis")||v.includes("cloudinary")||v.includes("imagekit"),R=[{key:"cover",label:"Cover image",ok:!!t.coverImage,tip:"Needed for LCP — the largest visible element on page load"},{key:"webp",label:"Image is WebP",ok:!!t.coverImage&&w(t.coverImage),tip:"WebP images are ~30% smaller — use AI Generate or Upload rather than external URLs"},{key:"excerpt",label:"Excerpt",ok:t.excerpt.trim().length>=50,tip:"Used as the meta description fallback"},{key:"metaTitle",label:"Meta title",ok:t.metaTitle.trim().length>=40,tip:"50–60 chars with your focus keyword"},{key:"metaDesc",label:"Meta description",ok:t.metaDescription.trim().length>=100,tip:"120–155 chars — leave blank to use excerpt"},{key:"keyword",label:"Focus keyword",ok:t.focusKeyword.trim().length>=3,tip:"Powers the SEO score and AI meta generation"}],f=R.filter(v=>v.ok).length,r=f===R.length;return e.jsxs("div",{className:"space-y-3 max-w-4xl",children:[e.jsxs("div",{className:`flex items-center gap-3 px-3 py-2.5 rounded-lg border text-xs ${r?"bg-success/15 border-success/30":f>=4?"bg-warning/10 border-warning/30":"bg-card border-border"}`,children:[e.jsx(Kr,{className:`w-3.5 h-3.5 shrink-0 ${r?"text-success":f>=4?"text-warning":"text-muted-foreground"}`}),e.jsx("span",{className:`font-medium shrink-0 ${r?"text-success":f>=4?"text-warning":"text-muted-foreground"}`,children:r?"Ready to publish":`${f}/${R.length} checks`}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:R.map(v=>e.jsxs("span",{title:v.tip,"data-testid":`readiness-${v.key}`,className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full border text-[11px] cursor-default ${v.ok?"bg-success/15 border-success/30 text-success-ink":"bg-secondary border-border text-muted-foreground"}`,children:[v.ok?"✓":"○"," ",v.label]},v.key))})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx("label",{className:"block text-xs text-muted-foreground mb-1",children:"Title *"}),e.jsx(he,{value:t.title,onChange:v=>{const _=v.target.value;s(K=>K&&{...K,title:_,slug:K.id?K.slug:rt(_)})},placeholder:"Article title...",className:"bg-secondary border-border text-foreground text-lg font-display"})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsxs("label",{className:"flex items-center justify-between text-xs text-muted-foreground mb-1",children:[e.jsx("span",{children:"Subtitle (optional)"}),e.jsx(xs,{action:"generate_subtitle",label:"Generate",editor:t,token:a,onResult:v=>{v?.subtitle&&s({...t,subtitle:v.subtitle})}})]}),e.jsx(he,{value:t.subtitle,onChange:v=>s({...t,subtitle:v.target.value}),placeholder:"Supporting subheadline...",className:"bg-secondary border-border text-foreground"})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs text-muted-foreground mb-1",children:["Slug ",e.jsx("span",{className:"text-muted-foreground font-normal",children:"/insights/"})]}),e.jsx(he,{value:t.slug,onChange:v=>s({...t,slug:v.target.value}),placeholder:"url-friendly-slug",className:"bg-secondary border-border text-foreground font-mono text-sm"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-muted-foreground mb-1",children:"Category"}),e.jsxs(ft,{value:t.category,onValueChange:v=>s({...t,category:v}),children:[e.jsx(bt,{className:"bg-secondary border-border text-foreground",children:e.jsx(wt,{})}),e.jsx(yt,{className:"bg-secondary border-border",children:Lt.map(v=>e.jsx(Ee,{value:v,className:"text-foreground focus:bg-secondary",children:v},v))})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsxs("label",{className:"flex items-center justify-between text-xs text-muted-foreground mb-1",children:[e.jsxs("span",{children:["Excerpt * ",e.jsx(zt,{value:t.excerpt,max:300,recommended:155}),e.jsx("span",{className:"text-muted-foreground ml-2",children:"155 chars recommended for cards"})]}),e.jsx(xs,{action:"generate_excerpt",label:"Generate",editor:t,token:a,onResult:v=>{v?.excerpt&&s({...t,excerpt:v.excerpt})}})]}),e.jsx(ze,{value:t.excerpt,onChange:v=>s({...t,excerpt:v.target.value}),placeholder:"2-3 sentence summary shown on listing and in meta de
27scription...",rows:3,className:"bg-secondary border-border text-foreground"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-muted-foreground mb-1",children:"Cover Image"}),e.jsx(ci,{value:t.coverImage,onChange:v=>s({...t,coverImage:v}),token:a})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-muted-foreground mb-1",children:"Cover Image Alt Text"}),e.jsx(he,{value:t.coverImageAlt,onChange:v=>s({...t,coverImageAlt:v.target.value}),placeholder:"Descriptive alt text...",className:"bg-secondary border-border text-foreground"})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs text-muted-foreground mb-1",children:["Tags ",e.jsx("span",{className:"text-muted-foreground",children:"(comma-separated)"})]}),e.jsx(he,{value:t.tags,onChange:v=>s({...t,tags:v.target.value}),placeholder:"leadership, scaling, executive teams",className:"bg-secondary border-border text-foreground"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-muted-foreground mb-1",children:"Read Time (minutes)"}),e.jsx(he,{type:"number",value:t.readTimeMinutes,onChange:v=>s({...t,readTimeMinutes:v.target.value}),placeholder:"Auto-estimated from content",className:"bg-secondary border-border text-foreground"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-muted-foreground mb-1",children:"Published Date"}),e.jsx(he,{type:"date",value:t.publishedAt,onChange:v=>s({...t,publishedAt:v.target.value}),className:"bg-secondary border-border text-foreground"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-muted-foreground mb-1",children:"Author"}),e.jsx(he,{value:t.authorName,onChange:v=>s({...t,authorName:v.target.value}),className:"bg-secondary border-border text-foreground"})]}),P&&e.jsx("div",{className:"md:col-span-2",children:e.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[e.jsx("div",{onClick:()=>s({...t,featured:!t.featured}),className:`w-10 h-5 rounded-full transition-colors ${t.featured?"bg-accent-gold":"bg-secondary"} relative`,children:e.jsx("div",{className:`absolute top-0.5 w-4 h-4 bg-white rounded-full transition-transform ${t.featured?"left-5":"left-0.5"}`})}),e.jsxs("span",{className:"text-sm text-foreground",children:["Featured article ",e.jsx("span",{className:"text-muted-foreground",children:"(shown prominently on listing page)"})]})]})})]})]})})(),p==="content"&&(()=>{const w=t.blocks.reduce((f,r)=>{const v=r.text||r.content||"";return f+(typeof v=="string"?v.split(/\s+/).filter(Boolean).length:0)},0),R=Math.max(1,Math.round(w/200));return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2 px-1",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:[w," words · ~",R," min read"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Auto-saved · Content editor"})]}),e.jsx(li,{blocks:t.blocks,onChange:f=>s(r=>r&&{...r,blocks:f}),articleTitle:t.title,onTitleChange:f=>s(r=>r&&{...r,title:f,slug:r.id?r.slug:rt(f)}),token:a},`${t.id||"new"}-${t._blockVersion||0}`),t.sources.filter(f=>f.url).length>0&&e.jsxs("div",{className:"mt-2 px-5 pt-4 pb-5 bg-card/40 border border-border/50 rounded-xl",children:[e.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-widest text-muted-foreground mb-3 flex items-center gap-1.5",children:[e.jsx(_e,{className:"w-3 h-3"}),"Sources — rendered automatically at the bottom of the published article"]}),e.jsx("ol",{className:"space-y-1.5 list-none m-0 p-0",children:t.sources.filter(f=>f.url).map((f,r)=>e.jsxs("li",{className:"flex items-baseline gap-2 leading-relaxed",style:{fontSize:"11px"},children:[e.jsxs("span",{className:"text-muted-foreground font-medium shrink-0 min-w-[18px] text-right",children:[r+1,"."]}),e.jsxs("span",{className:"italic text-muted-foreground",children:[e.jsxs("a",{href:f.url,target:"_blank",rel:"noopener noreferrer",className:"not-italic hover:text-accent-gold transition-colors underline underline-offset-2 decoration-muted-foreground inline-flex items-baseline gap-1",children:[f.title,e.jsx(_e,{className:"w-2.5 h-2.5 shrink-0 translate-y-
27px"})]})," — ",f.organization,f.year?`, ${f.year}`:""]})]},r))})]})]})})(),p==="seo"&&e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"grid md:grid-cols-[1fr_280px] gap-4 items-start",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-info/15 border border-info/30 rounded-lg p-3 text-xs text-info space-y-1",children:[e.jsx("p",{className:"font-medium text-info",children:"SEO / AEO / GEO Optimisation Tips"}),e.jsxs("p",{children:["• ",e.jsx("strong",{children:"Meta Title:"})," 50-60 chars — leave blank to use article title"]}),e.jsxs("p",{children:["• ",e.jsx("strong",{children:"Meta Description:"})," 120-155 chars — leave blank to use excerpt"]}),e.jsxs("p",{children:["• ",e.jsx("strong",{children:"FAQ Items:"})," Add 3+ Q&A pairs to qualify for Google's People Also Ask boxes"]}),e.jsxs("p",{children:["• ",e.jsx("strong",{children:"Key Takeaways:"})," Structured list helps AI answer engines cite your content"]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs text-muted-foreground mb-1",children:["Focus Keyword ",e.jsx("span",{className:"text-muted-foreground",children:"(for SEO analysis)"})]}),e.jsx(he,{value:t.focusKeyword,onChange:w=>
27s({...t,focusKeyword:w.target.value}),placeholder:"e.g. leadership capability",className:"bg-secondary border-border text-foreground"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsxs("label",{className:"text-xs text-muted-foreground",children:["Meta Title ",e.jsx(zt,{value:t.metaTitle,max:60})]}),e.jsx(fs,{field:"metaTitle",editor:t,token:a,onFixed:w=>s({...t,...w})})]}),e.jsx(he,{value:t.metaTitle,onChange:w=>s({...t,metaTitle:w.target.value}),placeholder:`${t.title} | Stuart Andrews`,className:"bg-secondary border-border text-foreground"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsxs("label",{className:"text-xs text-muted-foreground",children:["Meta Description ",e.jsx(zt,{value:t.metaDescription,max:160,recommended:155})]}),e.jsx(fs,{field:"metaDescription",editor:t,token:a,onFixed:w=>s({...t,...w})})]}),e.jsx(ze,{value:t.metaDescription,onChange:w=>s({...t,metaDescription:w.target.value}),placeholder:t.excerpt||"Brief description for search engines...",rows:2,className:"bg-secondary border-border text-foreground"})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs text-muted-foreground mb-1",children:["OG Image URL ",e.jsx("span",{className:"text-muted-foreground",children:"(overrides cover image for social)"})]}),e.jsx(he,{value:t.ogImage,onChange:w=>s({...t,ogImage:w.target.value}),placeholder:"https://...",className:"bg-secondary border-border text-foreground"})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs text-muted-foreground mb-1",children:["Canonical URL ",e.jsx("span",{className:"text-muted-foreground",children:"(leave blank for auto)"})]}),e.jsx(he,{value:t.canonicalUrl,onChange:w=>s({...t,canonicalUrl:w.target.value}),placeholder:"https://stuartandrews.me/insights/...",className:"bg-secondary border-border text-foreground"})]}),e.jsxs("div",{className:"border-t border-border pt-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("label",{className:"text-xs text-muted-foreground font-medium",children:["Key Takeaways ",e.jsxs("span",{className:"ml-2 text-success",children:[t.keyTakeaways.length," items"]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs("button",{disabled:J,onClick:async()=>{re(!0);try{const w=t.blocks.map(r=>r.type==="paragraph"||r.type==="callout"||r.type==="blockquote"||r.type==="heading"?(r.content||r.text||"").replace(/<[^>]+>/g,""):r.type==="numberedList"?(r.items||[]).map(v=>typeof v=="string"?v:`${v.title||""}: ${v.content||""}`).join(". "):r.type==="bulletList"||r.type==="keyTakeaways"?(r.items||[]).join(". "):"").filter(Boolean).join(`
28`),f=await(await fetch("/api/admin/articles/ai-assist",{method:"POST",headers:{"Content-Type":"application/json",...oe()},body:JSON.stringify({action:"generate_takeaways",title:t.title,content:w})})).json();f?.takeaways?.length&&(s({...t,keyTakeaways:[...t.keyTakeaways,...f.takeaways]}),U({title:`${f.takeaways.length} takeaways extracted from body`}))}catch{U({title:"Extraction failed",variant:"destructive"})}finally{re(!1)}},className:"flex items-center gap-1 px-2 py-1 text-[11px] rounded border border-info/50 text-info hover:text-info hover:bg-info/20 disabled:opacity-50 transition-colors","data-testid":"button-extract-key-takeaways",children:[J?e.jsx(ie,{className:"w-3 h-3 animate-spin"}):e.jsx($e,{className:"w-3 h-3"}),J?"Extracting…":"Extract from body"]}),e.jsxs(ee,{size:"sm",variant:"outline",className:"border-border text-muted-foreground hover:text-foreground text-xs",onClick:()=>s({...t,keyTakeaways:[...t.keyTakeaways,""]}),children:[e.jsx(gt,{className:"w-3 h-3 mr-1"})," Add"]})]})]}),t.keyTakeaways.map((w,R)=>e.jsxs("div",{className:"flex gap-2 mb-1.5",children:[e.jsx(he,{value:w,onChange:f=>{const r=[...t.keyTakeaways];r[R]=f.target.value,s({...t,keyTakeaways:r})},placeholder:`Key takeaway ${R+1}`,className:"bg-secondary border-border text-foreground text-sm flex-1"}),e.jsx("button",{onClick:()=>s({...t,keyTakeaways:t.keyTakeaways.filter((f,r)=>r!==R)}),className:"text-muted-foreground hover:text-destructive",children:e.jsx(Ae,{className:"w-3.5 h-3.5"})})]},R))]}),e.jsxs("div",{className:"border-t border-border pt-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("label",{className:"text-xs text-muted-foreground font-medium",children:["FAQ Items",e.jsxs("span",{className:`ml-2 ${t.faqItems.length>=3?"text-success":"text-warning"}`,children:[t.faqItems.length," items",t.faqItems.length<3&&" — 3+ recommended"]})]}),e.jsxs(ee,{size:"sm",variant:"outline",className:"border-border text-muted-foreground hover:text-foreground text-xs",onClick:()=>s({...t,faqItems:[...t.faqItems,{question:"",answer:""}]}),children:[e.jsx(gt,{className:"w-3 h-3 mr-1"})," Add Q&A"]})]}),t.faqItems.map((w,R)=>e.jsxs("div",{className:"bg-card border border-border rounded-lg p-3 mb-2 space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(he,{value:w.question,onChange:f=>{const r=[...t.faqItems];r[R]={...r[R],question:f.target.value},s({...t,faqItems:r})},placeholder:"Question",className:"bg-secondary border-border text-foreground text-sm flex-1"}),e.jsx("button",{onClick:()=>s({...t,faqItems:t.faqItems.filter((f,r)=>r!==R)}),className:"text-muted-foreground hover:text-destructive",children:e.jsx(Ae,{className:"w-3.5 h-3.5"})})]}),e.jsx(ze,{value:w.answer,onChange:f=>{const r=[...t.faqItems];r[R]={...r[R],answer:f.target.value},s({...t,faqItems:r})},placeholder:"Answer...",rows:2,className:"bg-secondary border-border text-foreground text-sm"})]},R))]}),e.jsx("div",{className:"border-t border-border pt-4",children:e.jsxs("p",{className:"text-xs text-muted-foreground italic flex items-center gap-1.5",children:[e.jsx("span",{className:"text-warning font-medium",children:"Sources"})," have moved to the",e.jsx("button",{onClick:()=>u("sources"),className:"text-warning underline underline-offset-2 hover:text-warning",children:"Sources tab"}),"— including stat editing and AI URL suggestions."]})})]}),e.jsx("div",{className:"sticky top-24",children:e.jsx(Wa,{editor:t})})]})}),p==="links"&&e.jsx(xi,{editor:t,setEditor:s,token:a}),p==="sources"&&e.jsx(mi,{editor:t,setEditor:s,token:a,articleId:t.id,saveArticle:m})]}),j&&e.jsx("div",{className:"sticky top-24 h-[calc(100vh-120px)] overflow-hidden",children:e.jsx(ui,{editor:t,setEditor:s,token:a,onClose:()=>k(!1),onSectionChange:w=>u(w),onSave:async w=>{await B(void 0,w)}})})]}),e.jsx(st,{open:c==="confirming",onOpenChange:w=>{w||(D("idle"),F([]))},children:e.jsxs(at,{className:"bg-card border-border max-w-lg",children:[e.jsxs(ut,{children:[e.jsxs(ht,{className:"flex items-center gap-2 text-warning",children:[e.jsx(es,{className:"w-4 h-4 shrink-0"}),$.length," stat",$.length!==1?"s":""," couldn't be verified online"]}),e.jsx(At,{className:"text-muted-foreground text-sm pt-1",children:"The scan checked live sources but couldn't find a real replacement for the following. You can publish as-is (marking them as editorial decisions) or go back and fix them manually."})]}),e.jsx("div",{className:"space-y-1.5 max-h-52 overflow-y-auto pr-1",children:$.map((w,R)=>e.jsxs("div",{className:"bg-destructive/15 border border-destructive/30 rounded p-2 text-xs text-foreground leading-snug",children:[e.jsxs("span",{className:"text-destructive font-semibold mr-1.5",children:[R+1,"."]}
28),w.original.length>180?w.original.slice(0,180)+"…":w.original]},R))}),e.jsxs(mt,{className:"flex flex-col gap-2 pt-2",children:[e.jsx(ee,{className:"bg-accent-gold hover:bg-accent-gold/90 text-black font-semibold w-full",onClick:ne,disabled:S,"data-testid":"button-confirm-fix-automatically",children:S?e.jsxs(e.Fragment,{children:[e.jsx(ie,{className:"w-3.5 h-3.5 mr-1 animate-spin"})," Finding replacements…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Se,{className:"w-3.5 h-3.5 mr-1"})," Fix automatically — find & replace with verified sources"]})}),e.jsxs("div",{className:"flex gap-2 w-full",children:[e.jsx(ee,{variant:"outline",className:"border-border text-foreground hover:text-foreground flex-1",onClick:()=>{D("idle"),F([]),u("sources")},"data-testid":"button-confirm-go-sources",children:"Go back and fix"}),e.jsxs(ee,{className:"bg-success hover:bg-success/90 text-success-foreground flex-1",onClick:()=>V($),"data-testid":"button-confirm-publish-anyway",children:[e.jsx(qt,{className:"w-3.5 h-3.5 mr-1"})," Publish as-is"]})]})]})]})}),e.jsx(st,{open:b!==null,onOpenChange:w=>{w||M(null)},children:e.jsxs(at,{className:"bg-card border-border max-w-2xl",children:[e.jsxs(ut,{children:[e.jsxs(ht,{className:"flex items-center gap-2 text-accent-gold",children:[e.jsx(Se,{className:"w-4 h-4 shrink-0"}),"Fix Stats — results"]}),e.jsx(At,{className:"text-muted-foreground text-sm pt-1",children:b&&(()=>{const w=b.filter(_=>_.status==="replaced").length,R=b.filter(_=>_.status==="rewritten").length,f=b.filter(_=>_.status==="verified").length,r=b.filter(_=>_.status==="unresolvable").length,v=[];return w>0&&v.push(`${w} replaced with sourced stat${w!==1?"s":""}`),R>0&&v.push(`${R} rewritten qualitatively`),f>0&&v.push(`${f} already verified`),r>0&&v.push(`${r} still need${r===1?"s":""} manual review`),v.join(" · ")})()})]}),e.jsxs("div",{className:"space-y-2 max-h-[60vh] overflow-y-auto pr-1",children:[b?.filter(w=>w.status==="replaced").map((w,R)=>e.jsxs("div",{className:"bg-accent-gold/15 border border-accent-gold/30 rounded-lg p-3 space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] font-semibold text-accent-gold uppercase tracking-wider",children:[e.jsx(Se,{className:"w-3 h-3"})," Auto-replaced",w.replacementOrg&&e.jsxs("span",{className:"text-accent-gold/70 font-normal normal-case tracking-normal",children:["· ",w.replacementOrg]})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground line-through leading-snug",children:w.original.length>160?w.original.slice(0,160)+"…":w.original}),e.jsx("p",{className:"text-xs text-foreground leading-snug",children:w.replacementStat&&(w.replacementStat.length>160?w.replacementStat.slice(0,160)+"…":w.replacementStat)}),w.url&&e.jsxs("a",{href:w.url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-[11px] text-accent-gold hover:text-accent-gold transition-colors mt-0.5",style:{wordBreak:"break-all"},"data-testid":`link-fix-result-replaced-${R}`,children:[e.jsx(_e,{className:"w-3 h-3 shrink-0"}),e.jsx("span",{className:"underline underline-offset-2",children:w.url})]})]},`replaced-${R}`)),b?.filter(w=>w.status==="rewritten").map((w,R)=>e.jsxs("div",{className:"bg-info/15 border border-info/30 rounded-lg p-3 space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] font-semibold text-info uppercase tracking-wider",children:[e.jsx(Se,{className:"w-3 h-3"})," Rewritten qualitatively"]}),e.jsx("p",{className:"text-[11px] text-muted-foreground line-through leading-snug",children:w.original.length>160?w.original.slice(0,160)+"…":w.original}),e.jsx("p",{className:"text-xs text-foreground leading-snug",children:w.replacementStat&&(w.replacementStat.length>160?w.replacementStat.slice(0,160)+"…":w.replacementStat)})]},`rewritten-${R}`)),b?.filter(w=>w.status==="verified").map((w,R)=>e.jsxs("div",{className:"bg-success/15 border border-success/30 rounded-lg p-3 space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] font-semibold text-success uppercase tracking-wider",children:[e.jsx(Te,{className:"w-3 h-3"})," Verified online"]}),e.jsx("p",{className:"text-xs text-foreground leading-snug",children:w.original.length>160?w.original.slice(0,160)+"…":w.original}),w.url&&e.jsxs("a",{href:w.url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-[11px] text-success hover:text-success transition-colors mt-0.5",style:{wordBreak:"break-all"},"data-testid":`link-fix-result-verified-${R}`,children:[e.jsx(_e,{className:"w-3 h-3 shrink-0"}),e.jsx("span",{className:"underline underline-offset-2",children:w.url})]})]},`verified-${R}`)),b?.filter(w=>w.status==="unresolvable").map((w,R)=>e.jsxs("div",{className:"bg-destructive/15 border border-destructive/30 rounded-lg p-3 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] font-semibold text-destructive uppercase tracking-wider",children:[e.jsx(es,{className:"w-3 h-3"})," Needs manual review"]}),e.jsx("p",{className:"text-xs text-muted-foreground leading-snug",children:w.original.length>160?w.original.slice(0,160)+"…":w.original})]},`bad-${R}`))]}),e.jsxs(mt,{className:"pt-2",children:[e.jsx(ee,{variant:"outline",className:"border-border text-foreground hover:text-foreground",onClick:()=>M(null),"data-testid":"button-fix-results-close",children:"Close"}),N&&t.status!=="published"&&b?.filter(w=>w.status==="unresolvable").length===0&&e.jsxs(ee,{className:"bg-success hover:bg-success text-foreground",onClick:()=>{M(null),Y()},"data-testid":"button-fix-results-publish",children:[e.jsx(qt,{className:"w-3.5 h-3.5 mr-1"})," Publish now"]})]})]})})]})}const Gt=50;function bi({token:t,permissions:s,articles:a,loading:n,canCreate:i,canDelete:m,canPublish:j,canFeature:k,canEditAny:p,statusFilter:u,setStatusFilter:N,categoryFilter:P,setCategoryFilter:x,searchQuery:H,setSearchQuery:T,sortBy:A,setSortBy:L,seoLinkHealth:E,seoLinkPanelOpen:B,setSeoLinkPanelOpen:U,seoLinkLoading:c,seoLinkRunning:D,linkRunProgress:$,loadSeoLinkHealth:F,loadContentLinkMap:J,triggerSeoLinkRun:re,linkMapPanelOpen:I,set
28LinkMapPanelOpen:o,linkMapData:S,linkMapLoading:l,boostingSlug:b,boostArticle:M,openNew:W,openWizard:te,openEdit:V,toggleFeatured:ne,quickToggleStatus:Y,createNewsletterCampaign:we,setLinkedInArticle:w,setDeleteArticleId:R,deleteArticleId:f,deleteLoading:r,deleteArticle:v,linkedInArticle:_,setShowTemplates:K,setShowImport:g,setShowBulkImport:C,creatingCampaign:X}){const[Q,ae]=h.useState(new Set),[O,pe]=h.useState(!1),[ce,be]=h.useState("own_site");h.useEffect(()=>{t&&fetch("/api/admin/articles/prerender-status",{headers:{...oe()}}).then(y=>y.ok?y.json():[]).then(y=>ae(new Set(y))).catch(()=>{})},[t]);const fe=H.toLowerCase().trim(),ke={own_site:a.filter(y=>Nt(y)==="own_site").length,contributed:a.filter(y=>Nt(y)==="contributed").length,all:a.length},Ne=[{id:"own_site",label:"My site",count:ke.own_site},{id:"contributed",label:"Contributed elsewhere",count:ke.contributed},{id:"all",label:"All",count:ke.all}],xe=a.filter(y=>!(ce!=="all"&&Nt(y)!==ce||u!=="all"&&y.status!==u||P!=="all"&&y.category!==P||fe&&!y.title.toLowerCase().includes(fe)&&!(y.excerpt||"").toLowerCase().includes(fe)&&!y.authorName.toLowerCase().includes(fe))).sort((y,ue)=>A==="newest"?new Date(ue.publishedAt||ue.createdAt).getTime()-new Date(y.publishedAt||y.createdAt).getTime():A==="oldest"?new Date(y.publishedAt||y.createdAt).getTime()-new Date(ue.publishedAt||ue.createdAt).getTime():A==="az"?y.title.localeCompare(ue.title):A==="za"?ue.title.localeCompare(y.title):A==="longest"?(ue.readTimeMinutes||0)-(y.readTimeMinutes||0):A==="shortest"?(y.readTimeMinutes||0)-(ue.readTimeMinutes||0):0),je=Array.from(new Set(a.map(y=>y.category))).sort(),d=O?xe:xe.slice(0,Gt);h.useEffect(()=>{pe(!1)},[u,P,H,A,ce]);const G=h.useRef(null),[le,de]=h.useState(null);h.useEffect(()=>{const y=G.current;if(!y)return;const ue=new ResizeObserver(Me=>{const Le=Me[0];Le&&de(Le.contentRect.width)});return ue.observe(y),()=>ue.disconnect()},[]);const se=le===null||le>=480,ye=le===null||le>=680;return e.jsxs("div",{className:"space-y-4",children:[p&&e.jsxs("div",{className:"bg-card/60 border border-border rounded-xl",children:[e.jsxs("button",{className:"w-full flex items-center justify-between px-5 py-3 text-left hover:bg-secondary/40 transition-colors",onClick:()=>{const y=!B;U(y),y&&(!E&&!c&&F(),!S&&!l&&J())},"data-testid":"button-toggle-seo-link-panel",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mt,{className:"w-4 h-4 text-info"}),e.jsx("span",{className:"text-sm font-semibold text-foreground",children:"SEO Link Health"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"— weekly auto-link injection + orphan fixer"})]}),B?e.jsx(Se,{className:"w-4 h-4 text-muted-foreground rotate-180"}):e.jsx(Se,{className:"w-4 h-4 text-muted-foreground"})]}),B&&e.jsxs("div",{className:"px-5 pb-5 pt-2 border-t border-border space-y-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Automatically runs every Sunday at 02:00 UTC: injects keyword links between insight articles, then fixes orphan articles with fewer than 2 inbound links. You can also trigger a manual run below."}),S&&e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[{label:"Published articles",value:S.length},{label:"0 inbound links",value:S.filter(y=>y.inbound===0).length},{label:"1 inbound link",value:S.filter(y=>y.inbound===1).length},{label:"Last run links added",value:E?.results?.links_added??"—"},{label:"Last auto-run",value:E?.lastRunAt?new Date(E.lastRunAt).toLocaleDateString("en-GB",{day:"numeric",month:"short"}):"—"}].map(({label:y,value:ue})=>e.jsxs("div",{className:"bg-secondary/60 rounded-lg p-2 text-center","data-testid":`stat-${y.replace(/\s+/g,"-").toLowerCase()}`,children:[e.jsx("p",{className:"text-lg font-bold text-foreground",children:ue}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:y})]},y))}),(c||l)&&!S&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(ie,{className:"w-3 h-3 animate-spin"})," Loading…"]}),D&&$&&e.jsxs("div",{className:"bg-info/15 border border-info/30 rounded-lg px-4 py-3 flex items-center gap-3","data-testid":"link-run-progress",children:[e.jsx(ie,{className:"w-4 h-4 animate-spin text-info shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[e.jsx("span",{className:"text-info font-medium",children:"Injecting links…"}),e.jsxs("span",{className:"text-info tabular-nums",children:[$.done,"/",$.total," articles"]})]}),e.jsx("div",{className:"w-full bg-info/20 rounded-full h-1.5",children:e.jsx("div",{className:"bg-info h-1.5 rounded-full transition-all duration-500",style:{width:$.total>0?`${Math.round($.done/$.total*100)}%`:"0%"}})})]}),e.jsxs("span",{className:"text-xs text-info shrink-0",children:[$.linksAdded," links added"]})]}),E&&!c&&e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-3 space-y-2",children:[e.jsxs("p",{className:"text-xs font-semibold text-foreground",children:["Last run: ",E.lastRunAt?new Date(E.lastRunAt).toLocaleDateString("en-GB",{weekday:"short",day:"numeric",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"}):e.jsx("span",{className:"text-warning-ink",children:"Never run — trigger a manual run below"})]}),E.results&&e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2 mt-1",children:[{label:"Articles scanned",value:E.results.articles_scanned},{label:"Links added",value:E.results.links_added},{label:"Orphans fixed",value:E.results.orphans_fixed}].map(({label:y,value:ue})=>e.jsxs("div",{className:"bg-card/60 rounded-lg p-2 text-center",children:[e.jsx("p",{className:"text-lg font-bold text-foreground",children:ue}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:y})]},y))})]}),S&&S.filter(y=>y.inbound<2).length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-semibold text-foreground",children:"Articles needing links (top 20 by fewest inbound)"}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-left text-muted-foreground border-b border-border",children:[e.jsx("th",{className:"pb-2 pr-4 font-medium",children:"Article"}),e.jsx("th",{className:"pb-2 pr-4 font-medium text-center",children:"Inbound"}),e.jsx("th",{className:"pb-2 font-medium text-center",children:"Action"})]})}),e.jsx("tbody",{children:S.filter(y=>y.inbound<2).sort((y,ue)=>
28y.inbound-ue.inbound).slice(0,20).map(y=>e.jsxs("tr",{className:"border-b border-border/50 hover:bg-secondary/20","data-testid":`row-orphan-${y.slug}`,children:[e.jsxs("td",{className:"py-2 pr-4",children:[e.jsx("span",{className:`font-medium ${y.inbound===0?"text-destructive":"text-warning-ink"}`,children:y.inbound===0?"●":"○"}),e.jsx("span",{className:"ml-2 text-foreground truncate max-w-xs inline-block",children:y.title||y.slug})]}),e.jsx("td",{className:"py-2 pr-4 text-center",children:e.jsx("span",{className:`font-bold ${y.inbound===0?"text-destructive":"text-warning-ink"}`,children:y.inbound})}),e.jsx("td",{className:"py-2 text-center",children:e.jsx("button",{onClick:()=>M(y.slug),disabled:b===y.slug,"data-testid":`button-boost-${y.slug}`,className:"text-[10px] text-info hover:text-info/80 border border-info/30 hover:border-info/50 rounded px-2 py-0.5 disabled:opacity-50 transition-colors",children:b===y.slug?e.jsx(ie,{className:"w-3 h-3 animate-spin inline"}):"Boost"})})]},y.slug))})]})})]}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsxs(ee,{variant:"outline",size:"sm",disabled:D,onClick:re,"data-testid":"button-run-seo-link-health",className:"border-border text-foreground hover:text-foreground hover:border-info text-xs h-8",children:[D?e.jsx(ie,{className:"w-3 h-3 mr-1 animate-spin"}):e.jsx(Ue,{className:"w-3 h-3 mr-1"}),"Run All Now"]}),e.jsx(ee,{variant:"ghost",size:"sm",onClick:()=>{F(),J()},disabled:c||l,className:"text-xs text-muted-foreground hover:text-foreground h-8","data-testid":"button-refresh-seo-link-health",children:"↺ Refresh"})]})]})]}),p&&e.jsxs("div",{className:"bg-card/60 border border-border rounded-xl",children:[e.jsxs("button",{className:"w-full flex items-center justify-between px-5 py-3 text-left hover:bg-secondary/40 transition-colors",onClick:()=>{const y=!I;o(y),y&&!S&&!l&&J()},"data-testid":"button-toggle-link-map",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dt,{className:"w-4 h-4 text-success"}),e.jsx("span",{className:"text-sm font-semibold text-foreground",children:"Content Link Map"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"— per-article inbound & outbound link audit"})]}),I?e.jsx(Yt,{className:"w-4 h-4 text-muted-foreground rotate-180"}):e.jsx(Yt,{className:"w-4 h-4 text-muted-foreground"})]}),I&&e.jsxs("div",{className:"px-5 pb-5 pt-2 border-t border-border space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Articles sorted by inbound links (lowest first). Orphans have 0 inbound links."}),e.jsxs(ee,{variant:"ghost",size:"sm",onClick:J,disabled:l,className:"text-xs text-muted-foreground hover:text-foreground h-7","data-testid":"button-refresh-link-map",children:[l?e.jsx(ie,{className:"w-3 h-3 animate-spin mr-1"}):null," ↺ Refresh"]})]}),l&&!S&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(ie,{className:"w-3 h-3 animate-spin"})," Loading link map…"]}),S&&e.jsxs("div",{className:"overflow-x-auto",children:[e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-left text-muted-foreground border-b border-border",children:[e.jsx("th",{className:"pb-2 pr-4 font-medium",children:"Article"}),e.jsx("th",{className:"pb-2 pr-4 font-medium text-center",children:"Inbound"}),e.jsx("th",{className:"pb-2 pr-4 font-medium text-center",children:"Outbound"}),e.jsx("th",{className:"pb-2 font-medium",children:"Status"})]})}),e.jsx("tbody",{className:"divide-y divide-border/60",children:S.map(y=>e.jsxs("tr",{className:"hover:bg-secondary/30 transition-colors","data-testid":`link-map-row-${y.slug}`,children:[e.jsxs("td",{className:"py-2 pr-4",children:[e.jsx("p",{className:"font-medium text-foreground truncate max-w-xs",children:y.title}),e.jsxs("p",{className:"text-[10px] text-muted-foreground font-mono",children:["/",y.slug]})]}),e.jsx("td",{className:"py-2 pr-4 text-center",children:e.jsx("span",{className:`font-bold ${y.inbound===0?"text-destructive":y.inbound<2?"text-warning-ink":"text-success"}`,children:y.inbound})}),e.jsx("td",{className:"py-2 pr-4 text-center",children:e.jsx("span",{className:"font-bold text-foreground",children:y.outbound})}),e.jsx("td",{className:"py-2",children:y.inbound===0?e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-destructive/20 text-destructive-ink",children:"Orphan"}):y.inbound<2?e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-warning/20 text-warning-ink",children:"Low"}):e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-success/20 text-success-ink",children:"OK"})})]},y.slug))})]}),S.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-6",children:"No articles found."}),e.jsxs("div",{className:"mt-3 flex gap-4 text-[10px] text-muted-foreground",children:[e.jsxs("span",{children:[e.jsx("span",{className:"text-destructive font-bold",children:"●"})," Orphan = 0 inbound"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-warning-ink font-bold",children:"●"})," Low = 1 inbound"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-success font-bold",children:"●"})," OK = 2+ inbound"]})]})]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Insights Articles"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[a.length," article",a.length!==1?"s":""," total"]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i&&e.jsxs(ee,{variant:"outline",onClick:()=>K(!0),className:"border-border text-foreground hover:text-foreground","data-testid":"button-templates",children:[e.jsx(dt,{className:"w-4 h-4 mr-1.5"})," Templates"]}),i&&e.jsxs(ee,{variant:"outline",onClick:()=>g(!0),className:"border-border text-foreground hover:text-foreground","data-testid":"button-import",children:[e.jsx($t,{className:"w-4 h-4 mr-1.5"})," Import"]}),i&&e.jsxs(ee,{variant:"outline",onClick:()=>C(!0),className:"border-info/60 text-info hover:text-foreground hover:border-info/80","data-testid":"button-bulk-import",children:[e.jsx($t,{className:"w-4 h-4 mr-1.5"})," Bulk Import"]}),i&&e.jsxs(ee,{variant:"outline",onClick:te,className:"border-info/60 text-info hover:text-foreground hover:border-info/80","data-testid":"button-ai-write",children:[e.jsx($e,{className:"w-4 h-4 mr-1.5"})," AI Write"]}),i&&e.jsxs(ee,{onClick:W,className:"bg-accent-gold hover:bg-accent-gold-light text-navy-deep font-semibold","data-testid":"button-new-article",children:[e.jsx(gt,{className:"w-4 h-4 mr-1.5"}
28)," New Article"]})]})]}),e.jsx(Vr,{items:Ne,activeId:ce,onSelect:y=>be(y),layout:"tab","aria-label":"Filter by destination","data-testid":"count-strip-destination"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(Dt,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground pointer-events-none"}),e.jsx("input",{type:"text",placeholder:"Search articles…",value:H,onChange:y=>T(y.target.value),className:"w-full pl-10 pr-8 py-1.5 rounded-lg bg-secondary border border-border text-sm text-foreground placeholder-muted-foreground focus:outline-none focus:border-accent-gold/60","data-testid":"input-search-articles"}),H&&e.jsx("button",{onClick:()=>T(""),className:"absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:e.jsx("span",{className:"text-xs",children:"✕"})})]}),e.jsxs(ft,{value:A,onValueChange:L,children:[e.jsx(bt,{className:"w-44 bg-secondary border-border text-sm text-foreground","data-testid":"select-sort-articles",children:e.jsx(wt,{})}),e.jsxs(yt,{children:[e.jsx(Ee,{value:"newest",children:"Newest First"}),e.jsx(Ee,{value:"oldest",children:"Oldest First"}),e.jsx(Ee,{value:"az",children:"Title A–Z"}),e.jsx(Ee,{value:"za",children:"Title Z–A"}),e.jsx(Ee,{value:"longest",children:"Longest Read"}),e.jsx(Ee,{value:"shortest",children:"Shortest Read"})]})]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[["all","published","draft"].map(y=>e.jsx("button",{onClick:()=>N(y),className:`px-3 py-1 rounded-full text-xs font-medium transition-colors capitalize ${u===y?"bg-accent-gold text-navy-deep":"bg-secondary text-muted-foreground hover:bg-secondary"}`,children:y==="all"?`All (${a.length})`:`${y.charAt(0).toUpperCase()+y.slice(1)} (${a.filter(ue=>ue.status===y).length})`},y)),je.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground self-center",children:"|"}),e.jsx("button",{onClick:()=>x("all"),className:`px-3 py-1 rounded-full text-xs font-medium transition-colors ${P==="all"?"bg-info text-info-foreground":"bg-secondary text-muted-foreground hover:bg-secondary"}`,children:"All Categories"}),je.map(y=>e.jsx("button",{onClick:()=>x(y),className:`px-3 py-1 rounded-full text-xs font-medium transition-colors ${P===y?"bg-info text-info-foreground":"bg-secondary text-muted-foreground hover:bg-secondary"}`,children:y},y))]})]}),(H||u!=="all"||P!=="all"||ce!=="own_site")&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Showing ",e.jsx("span",{className:"text-foreground font-medium",children:xe.length})," of ",a.length," articles",H&&e.jsxs(e.Fragment,{children:[" matching ",e.jsxs("span",{className:"text-accent-gold-ink",children:['"',H,'"']})]})]}),n?e.jsx("div",{className:"text-center py-10 text-muted-foreground",children:"Loading articles..."}):xe.length===0?e.jsxs("div",{className:"text-center py-16 bg-card rounded-xl border border-dashed border-border text-muted-foreground",children:[e.jsx(nt,{className:"w-10 h-10 mx-auto mb-3 opacity-40"}),a.length===0?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"font-medium",children:"No articles yet"}),i&&e.jsx("p",{className:"text-sm mt-1",children:'Click "New Article" to write your first piece.'})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"font-medium",children:"No articles match these filters"}),e.jsx("button",{onClick:()=>{T(""),N("all"),x("all"),be("own_site")},className:"text-sm mt-1 text-accent-gold-ink hover:underline","data-testid":"button-insights-clear-filters",children:"Clear filters"})]})]}):e.jsxs("div",{className:"bg-card border border-border rounded-xl overflow-hidden",children:[e.jsx("div",{className:"overflow-x-auto",ref:G,children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border bg-secondary/50",children:[e.jsx("th",{className:"text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Article"}),se&&e.jsx("th",{className:"text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Category"}),e.jsx("th",{className:"text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Status"}),ye&&e.jsx("th",{className:"text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Date"}),e.jsx("th",{className:"text-right px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Actions"})]})}),e.jsx("tbody",{className:"divide-y divide-border",children:d.map(y=>e.jsxs("tr",{className:"hover:bg-secondary/40 transition-colors",children:[e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[y.featured&&e.jsx(Es,{className:"w-3.5 h-3.5 text-accent-gold 
28shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-foreground leading-snug line-clamp-2 break-words",title:y.title,"data-testid":`text-article-title-${y.id}`,children:y.title}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:y.excerpt})]})]})}),se&&e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:"text-xs text-muted-foreground",children:y.category})}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[e.jsx(Gs,{status:y.status}),e.jsx(qa,{destination:Nt(y)}),Q.has(y.slug)&&e.jsx(Gr,{variant:"success",size:"sm",title:"Static HTML cached — fast LCP","data-testid":`badge-prerendered-${y.slug}`,children:"⚡ Cached"})]})}),ye&&e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:"text-xs text-muted-foreground",children:y.publishedAt?new Date(y.publishedAt).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"}):new Date(y.createdAt).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})})}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[k&&e.jsx("button",{onClick:()=>ne(y),title:y.featured?"Unfeature":"Feature",className:`p-1.5 rounded transition-colors ${y.featured?"text-accent-gold hover:text-accent-gold-light":"text-muted-foreground hover:text-accent-gold"}`,children:y.featured?e.jsx(Es,{className:"w-3.5 h-3.5"}):e.jsx(mn,{className:"w-3.5 h-3.5"})}),j&&e.jsx("button",{onClick:()=>Y(y),title:y.status==="published"?"Unpublish":"Publish",className:`p-1.5 rounded transition-colors ${y.status==="published"?"text-success hover:text-warning-ink":"text-muted-foreground hover:text-success"}`,children:y.status==="published"?e.jsx(It,{className:"w-3.5 h-3.5"}):e.jsx(Xs,{className:"w-3.5 h-3.5"})}),i&&e.jsx("button",{onClick:()=>we(y),title:"Create Newsletter Campaign",disabled:X===y.id,className:"p-1.5 rounded transition-colors text-muted-foreground hover:text-accent-gold disabled:opacity-50","data-testid":`button-create-campaign-${y.id}`,children:X===y.id?e.jsx(ie,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(Da,{className:"w-3.5 h-3.5"})}),i&&e.jsx("button",{onClick:()=>w(y),title:"Repurpose as LinkedIn Post",className:"p-1.5 rounded transition-colors text-muted-foreground hover:text-[#0077b5]","data-testid":`button-linkedin-${y.id}`,children:e.jsx(xt,{className:"w-3.5 h-3.5"})}),(p||tt(s,"articles:edit_own"))&&e.jsx("button",{onClick:()=>V(y),title:"Edit",className:"p-1.5 rounded hover:bg-secondary text-muted-foreground hover:text-foreground transition-colors",children:e.jsx(Jr,{className:"w-3.5 h-3.5"})}),m&&e.jsx("button",{onClick:()=>R(y.id),title:"Delete",className:"p-1.5 rounded hover:bg-destructive/20 text-muted-foreground hover:text-destructive transition-colors",children:e.jsx(Ys,{className:"w-3.5 h-3.5"})})]})})]},y.id))})]})}),xe.length>Gt&&e.jsxs("div",{className:"px-4 py-3 border-t border-border flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{"data-testid":"text-articles-shown-count",children:["Showing ",d.length," of ",xe.length," articles"]}),e.jsx("button",{onClick:()=>pe(y=>!y),"data-testid":"button-toggle-show-all-articles",className:"px-2.5 py-1 rounded-lg bg-secondary/50 border border-border/50 text-foreground hover:bg-secondary/80 transition-colors",children:O?`Show top ${Gt} only`:`Show all ${xe.length} articles`})]})]}),e.jsx(st,{open:f!==null,onOpenChange:y=>!y&&R(null),children:e.jsxs(at,{className:"bg-card border-border text-foreground max-w-sm",children:[e.jsx(ut,{children:e.jsx(ht,{children:"Delete Article"})}),e.jsx("p",{className:"text-sm text-muted-foreground py-2",children:"This will permanently delete the article. This cannot be undone."}),e.jsxs(mt,{children:[e.jsx(ee,{variant:"ghost",onClick:()=>R(null),className:"text-muted-foreground",children:"Cancel"}),e.jsx(ee,{onClick:v,disabled:r,className:"bg-destructive hover:bg-destructive/90 text-destructive-foreground font-semibold",children:r?"Deleting...":"Delete"})]})]})}),_&&e.jsx(Ua,{article:_,token:t,onClose:()=>w(null)})]})}const wi=[{v:"authoritative",l:"Authoritative"},{v:"warm",l:"Warm"},{v:"conversational",l:"Conversational"},{v:"provocative",l:"Provocative"}],yi=[{label:"Writing article content",status:"pending"},{label:"Generating cover image",status:"pending"},{label:"Writing SEO meta title & description",status:"pending"},{label:"Writing subtitle",status:"pending"},{label:"Writing excerpt",status:"pending"},{label:"Injecting focus keyword",status:"pending"},{label:"Adding key takeaways",status:"pending"},{label:"Adding FAQs",status:"pending"},{label:"Extracting & suggesting sources",status:"pending"}];function Us(t){const s=t.focusKeyword.toLowerCase().trim(),a=t.title.toLowerCase(),n=t.metaDescription.toLowerCase(),i=t.blocks.find(A=>A.type==="paragraph"),m=(i?.content||i?.text||"").replace(/<[^>]*>/g,"").toLowerCase(),k=t.blocks.filter(A=>A.type==="heading"&&A.level>=2).map(A=>(A.content||A.text||"").toLowerCase()).join(" "),p=t.blocks.reduce((A,L)=>A+(L.content||L.text||"").replace(/<[^>]*>
28/g,"").split(/\s+/).filter(Boolean).length,0),u=t.keyTakeaways.join(" ").split(/\s+/).filter(Boolean).length,N=t.faqItems.reduce((A,L)=>A+`${L.question} ${L.answer}`.split(/\s+/).filter(Boolean).length,0),P=p+u+N,x=Ka(t.title),H=[{label:"Focus keyword in title",ok:!!(s&&a.includes(s))},{label:"Focus keyword in meta description",ok:!!(s&&n.includes(s))},{label:"Focus keyword in first paragraph",ok:!!(s&&m.includes(s))},{label:"Focus keyword in a heading",ok:!!(s&&k.includes(s))},{label:`Meta description (${t.metaDescription.length} chars)`,ok:t.metaDescription.length>=120&&t.metaDescription.length<=160,warn:t.metaDescription.length>=100&&t.metaDescription.length<120},{label:`Meta title (${t.metaTitle.length} chars)`,ok:t.metaTitle.length>=50&&t.metaTitle.length<=60,warn:t.metaTitle.length>=40&&t.metaTitle.length<50},{label:`Article length (${P} words, ${x.min}+ target)`,ok:P>=x.min,warn:P>=x.warn},{label:"Has cover image",ok:!!t.coverImage},{label:`FAQs (${t.faqItems.length})`,ok:t.faqItems.length>=1},{label:`Key takeaways (${t.keyTakeaways.length})`,ok:t.keyTakeaways.length>=3}];return{score:Math.round(H.filter(A=>A.ok).length/H.length*100),checks:H}}function vi({blocks:t}){return e.jsx("div",{className:"space-y-2 text-sm text-foreground leading-relaxed",children:t.map((s,a)=>
28{if(s.type==="heading"){const n=s.level===1?"h1":s.level===2?"h2":"h3";return e.jsx(n,{className:`font-bold text-foreground ${s.level===1?"text-lg":s.level===2?"text-base":"text-sm"}`,children:s.text||s.content||""},a)}if(s.type==="paragraph")return e.jsx("p",{className:"text-foreground text-xs leading-relaxed",dangerouslySetInnerHTML:{__html:Yr.sanitize(s.content||s.text||"")}},a);if(s.type==="callout"){const n={insight:"bg-[hsl(var(--accent-gold))]/15 border-[hsl(var(--accent-gold))]/40 text-[hsl(var(--accent-gold))]",framework:"bg-info/30 border-info/40 text-info",warning:"bg-warning/30 border-warning/40 text-warning",stat:"bg-success/30 border-success/40 text-success"},i=n[s.variant]??n.insight;return e.jsx("div",{className:`border rounded-lg px-3 py-2 text-xs italic ${i}`,children:s.content||""},a)}if(s.type==="blockquote")return e.jsxs("blockquote",{className:"border-l-2 border-info pl-3 py-0.5",children:[e.jsx("p",{className:"text-xs text-foreground italic",children:s.content||""}),s.attribution&&e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:["— ",s.attribution]})]},a);if(s.type==="stat"&&Array.isArray(s.items))return e.jsx("div",{className:"flex flex-wrap gap-2",children:s.items.map((n,i)=>e.jsxs("div",{className:"bg-secondary rounded-lg px-3 py-2 text-center min-w-[90px]",children:[e.jsx("p",{className:"text-base font-bold text-warning",children:n.value}),e.jsx("p",{className:"text-[10px] text-foreground",children:n.label}),n.context&&e.jsx("p",{className:"text-[9px] text-muted-foreground mt-0.5",children:n.context})]},i))},a);if(s.type==="numberedList"&&Array.isArray(s.items))return e.jsx("ol",{className:"space-y-1.5 list-none",children:s.items.map((n,i)=>e.jsxs("li",{className:"flex gap-2 text-xs",children:[e.jsx("span",{className:"shrink-0 w-4 h-4 rounded-full bg-info/40 text-info flex items-center justify-center text-[9px] font-bold mt-0.5",children:i+1}),e.jsxs("span",{children:[e.jsx("span",{className:"font-semibold text-foreground",children:n.title}),n.content?e.jsxs("span",{className:"text-muted-foreground",children:[" — ",n.content]}):null]})]},i))},a);if(s.type==="bulletList"&&Array.isArray(s.items))return e.jsx("ul",{className:"space-y-1",children:s.items.map((n,i)=>e.jsxs("li",{className:"flex gap-1.5 text-xs text-foreground",children:[e.jsx("span",{className:"text-info shrink-0 mt-0.5",children:"·"}),n]},i))},a);if(s.type==="framework"&&Array.isArray(s.items))return e.jsxs("div",{className:"bg-secondary/60 rounded-lg px-3 py-2.5 border border-border/50",children:[s.title&&e.jsx("p",{className:"text-xs font-bold text-warning mb-1.5",children:s.title}),e.jsx("div",{className:"space-y-1.5",children:s.items.map((n,i)=>e.jsxs("div",{className:"text-xs",children:[e.jsxs("span",{className:"font-semibold text-foreground",children:[n.label,": "]}),e.jsx("span",{className:"text-muted-foreground",children:n.description})]},i))})]},a);if(s.type==="keyTakeaways"&&Array.isArray(s.items))return e.jsxs("div",{className:"bg-secondary rounded-lg px-3 py-2",children:[e.jsx("p",{className:"text-xs font-semibold text-warning mb-1",children:"Key Takeaways"}),e.jsx("ul",{className:"space-y-1",children:s.items.map((n,i)=>e.jsxs("li",{className:"text-xs text-foreground flex gap-1.5",children:[e.jsx(Te,{className:"w-3 h-3 text-success mt-0.5 shrink-0"}),n]},i))})]},a);if(s.type==="faq"&&Array.isArray(s.items))return e.jsxs("div",{className:"bg-secondary rounded-lg px-3 py-2",children:[e.jsx("p",{className:"text-xs font-semibold text-info mb-1",children:"FAQs"}),e.jsx("div",{className:"space-y-1",children:s.items.slice(0,2).map((n,i)=>e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium text-foreground",children:n.question}),e.jsx("p",{className:"text-xs text-muted-foreground",children:n.answer})]},i))})]},a);if(s.type==="cta")return e.jsxs("div",{className:"bg-warning/20 border border-warning/30 rounded-lg px-3 py-2",children:[e.jsx("p",{className:"text-xs font-bold text-warning",children:s.title||"CTA"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:s.description||""})]},a);if(s.type==="divider")return e.jsx("hr",{className:"border-border"},a);if(s.type==="furtherReading"||s.type==="further-reading")return e.jsxs("div",{className:"bg-secondary/40 border border-border/40 rounded-lg px-3 py-2",children:[e.jsx("p",{className:"text-[10px] font-semibold text-muted-foreground uppercase tracking-wider mb-1",children:"Further Reading"}),Array.isArray(s.items)&&s.items.map((n,i)=>e.jsx("p",{className:"text-xs text-info",children:n.title||n.label},i))]},a);if(s.type==="table"&&(Array.isArray(s.headers)||Array.isArray(s.rows))){const n=s.headers??[],i=s.rows??[];return e.jsx("div",{className:"overflow-x-auto rounded-lg border border-border/50",children:e.jsxs("table",{className:"w-full text-xs text-foreground border-collapse",children:[n.length>0&&e.jsx("thead",{children:e.jsx("tr",{className:"bg-secondary border-b border-border",children:n.map((m,j)=>e.jsx("th",{className:"px-3 py-2 text-left font-semibold text-foreground whitespace-nowrap",children:m},j))})}),e.jsx("tbody",{children:i.map((m,j)=>e.jsx("tr",{className:`border-b border-border/60 ${j%2===0?"bg-card/40":"bg-secondary/20"}`,children:m.map((k,p)=>e.jsx("td",{className:"px-3 py-1.5",children:k},p))},j))})]})},a)}return null})})}function ji({token:t,open:s,onClose:a,onSave:n}){const[i,m]=h.useState("ideate"),[j,k]=h.useState(""),[p,u]=h.useState(""),[N,P]=h.useState(""),[x,H]=h.useState("authoritative"),[T,A]=h.useState([]),[L,E]=h.useState(!1),[B,U]=h.useState([]),[c,D]=h.useState(null),[$,F]=h.useState(!1),[J,re]=h.useState(""),[I,o]=h.useState(!1),[S,l]=h.useState(!1),{toast:b}=De(),M=h.useRef(!1);function W(){m("ideate"),k(""),u(""),P(""),H("authoritative"),A([]),U([]),D(null),re(""),M.current=!1}function te(){i!=="generating"&&(W(),a())}async function V(f,r){const v=f==="generate_article"||f==="generate_cover_image",_=new AbortController,
28K=setTimeout(()=>_.abort(),v?8e4:45e3);try{const g=await fetch("/api/admin/articles/ai-assist",{method:"POST",headers:{"Content-Type":"application/json",...oe()},body:JSON.stringify({action:f,...r}),signal:_.signal}),C=await g.json();if(!g.ok)throw new Error(C.error||"AI error");return C}catch(g){throw g.name==="AbortError"?new Error("Generation timed out — please try again. If it keeps failing, try a shorter brief."):g}finally{clearTimeout(K)}}async function ne(){if(!(!j.trim()&&!N.trim())){E(!0);try{const f=await V("generate_headlines",{title:j||N,content:N,brief:N});A(f.suggestions||[])}catch(f){b({title:"Couldn't suggest angles",description:f.message,variant:"destructive"})}E(!1)}}function Y(f,r){U(v=>v.map((_,K)=>K===f?{..._,status:r}:_))}async function we(){if(!j.trim()&&!N.trim()){b({title:"Add a title or brief first",variant:"destructive"});return}M.current=!1;const f=yi.map(_=>({..._}));p.trim()||(f[5]={label:"Keyword injection (no keyword — skipping)",status:"pending"}),U(f),m("generating");let r={...Zt,title:j.trim()||N.slice(0,80),focusKeyword:p.trim()};const v=_=>{r={...r,..._},D({...r})};try{Y(0,"running");const _=await V("generate_article",{title:r.title,brief:N,tone:x,focusKeyword:r.focusKeyword});if(_.blocks?.length>0){const g=_.blocks.find(Q=>Q.type==="faq"),C=_.blocks.find(Q=>Q.type==="keyTakeaways"),X=Array.isArray(_.sources)?_.sources.map(Q=>({organization:Q.organisation??Q.organization??"",title:"",year:Q.year??"",url:Q.url??null})):[];v({blocks:_.blocks,faqItems:g?.items?.length?g.items:r.faqItems,keyTakeaways:C?.items?.length?C.items:r.keyTakeaways,...X.length>0?{sources:X}:{}})}Y(0,"done");const K=()=>r.blocks.map(g=>(g.content||g.text||"").replace(/<[^>]*>/g,"")).join(`
29`).slice(0,3e3);Y(1,"running");try{const g=await V("generate_cover_image",{title:r.title,content:K(),focusKeyword:r.focusKeyword});g.coverImage&&v({coverImage:g.coverImage,coverImageAlt:g.coverImageAlt||r.title}),Y(1,"done")}catch{Y(1,"skipped")}Y(2,"running");try{const g=await V("generate_meta",{title:r.title,content:K(),tone:"authoritative",focusKeyword:r.focusKeyword});g.metaTitle&&v({metaTitle:g.metaTitle,metaDescription:g.metaDescription||""}),Y(2,"done")}catch{Y(2,"skipped")}Y(3,"running");try{const g=await V("generate_subtitle",{title:r.title,content:K()});g.subtitle&&v({subtitle:g.subtitle}),Y(3,"done")}catch{Y(3,"skipped")}Y(4,"running");try{const g=await V("generate_excerpt",{title:r.title,content:K()});g.excerpt&&v({excerpt:g.excerpt}),Y(4,"done")}catch{Y(4,"skipped")}if(r.focusKeyword.trim()){Y(5,"running");try{const g=await V("inject_keyword_paragraph",{focusKeyword:r.focusKeyword,blocks:r.blocks});g.blocks?.length&&v({blocks:g.blocks});const C=await V("inject_keyword_heading",{focusKeyword:r.focusKeyword,blocks:r.blocks,title:r.title});C.blocks?.length&&v({blocks:C.blocks}),r.focusKeyword&&!r.title.toLowerCase().includes(r.focusKeyword.toLowerCase())&&v({title:`${r.title}: ${r.focusKeyword.split(" ").map(X=>X.charAt(0).toUpperCase()+X.slice(1)).join(" ")} Strategies`}),Y(5,"done")}catch{Y(5,"skipped")}}else Y(5,"skipped");Y(6,"running");try{if(r.keyTakeaways.length<3){const g=await V("generate_takeaways",{title:r.title,content:K()});g.takeaways?.length&&v({keyTakeaways:g.takeaways})}Y(6,"done")}catch{Y(6,"skipped")}Y(7,"running");try{if(r.faqItems.length<1){const g=await V("generate_faqs",{title:r.title,content:K()});g.faqs?.length&&v({faqItems:g.faqs})}Y(7,"done")}catch{Y(7,"skipped")}Y(8,"running");try{const g=[];for(const C of r.blocks)C.type==="stat"&&Array.isArray(C.items)&&g.push(...C.items);if(g.length>0){const C=new Map;for(const X of g)if(X.context){const Q=X.context.match(/^(.+?)\s+(\d{4})$/);if(Q){const ae=Q[1].trim();C.has(ae)||C.set(ae,Q[2])}else{const ae=X.context.trim().slice(0,80);ae&&!C.has(ae)&&C.set(ae,"")}}if(C.size>0){const X=new Map(r.sources.map(O=>[O.organization.toLowerCase(),O])),Q=Array.from(C.entries()).map(([O,pe])=>{const ce=X.get(O.toLowerCase());return ce||{organization:O,title:"",...pe?{year:pe}:{},url:null}});for(const O of r.sources)!C.has(O.organization)&&!Q.some(pe=>pe.organization.toLowerCase()===O.organization.toLowerCase())&&Q.push(O);v({sources:Q});const ae=g.map(O=>`${O.value} — ${O.label}${O.context?` (${O.context})`:""}`);try{const O=await fetch("/api/admin/articles/suggest-sources",{method:"POST",headers:{"Content-Type":"application/json",...oe()},body:JSON.stringify({sources:Q,statTexts:ae}),signal:AbortSignal.timeout(25e3)});if(O.ok){const{sources:pe}=await O.json(),ce=new Map(pe.map(fe=>[fe.organization.toLowerCase(),fe])),be=Q.map(fe=>{if(fe.url)return fe;
29const ke=ce.get(fe.organization.toLowerCase());return ke?{...fe,url:ke.url}:fe});v({sources:be})}}catch{}}}Y(8,"done")}catch{Y(8,"skipped")}D({...r}),m("review")}catch(_){b({title:"Generation failed",description:_.message,variant:"destructive"}),m("ideate")}}async function w(){if(!(!J.trim()||!c)){o(!0);try{const f=c.blocks.map(v=>(v.content||v.text||"").replace(/<[^>]*>/g,"")).join(`
30`).slice(0,8e3),r=await V("custom_instruction",{instruction:J,title:c.title,content:f,blocks:c.blocks,focusKeyword:c.focusKeyword,faqItems:c.faqItems,keyTakeaways:c.keyTakeaways,excerpt:c.excerpt,metaTitle:c.metaTitle,metaDescription:c.metaDescription});r.updates?.length?(D(v=>{if(!v)return v;let _={...v};for(const K of r.updates)K.field==="blocks"&&Array.isArray(K.value)&&K.value.length>0?_={..._,blocks:K.value}:K.field==="title"&&K.value?_={..._,title:K.value}:K.field==="subtitle"&&K.value?_={..._,subtitle:K.value}:K.field==="excerpt"&&K.value?_={..._,excerpt:K.value}:K.field==="metaTitle"&&K.value?_={..._,metaTitle:K.value}:K.field==="metaDescription"&&K.value?_={..._,metaDescription:K.value}:K.field==="keyTakeaways"&&Array.isArray(K.value)?_={..._,keyTakeaways:K.value}:K.field==="faqItems"&&Array.isArray(K.value)&&(_={..._,faqItems:K.value});return _}),re(""),b({title:r.summary||"Applied!"})):b({title:"No changes applied",description:r.summary||`The AI didn't make any edits. Try rephrasing — e.g. "Expand the intro section" or "Add statistics from Gallup".`})}catch(f){b({title:"Error",description:f.message,variant:"destructive"})}o(!1)}}async function R(f){if(c){F(!0);try{await n(c,f),W(),a()}catch(r){b({title:"Save failed",description:r.message,variant:"destructive"})}F(!1)}}return c&&Us(c),e.jsx(st,{open:s,onOpenChange:f=>{f||te()},children:e.jsxs(at,{className:"max-w-5xl bg-background border border-border text-foreground p-0 gap-0 overflow-hidden",style:{maxHeight:"92vh"},"data-testid":"dialog-ai-wizard",children:[e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-border shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-info/20 flex items-center justify-center",children:e.jsx($e,{className:"w-4 h-4 text-info"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-sm font-bold text-foreground",children:"AI Write"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Ideate · Generate · Review · Publish"})]})]}),e.jsx("div",{className:"flex items-center gap-1.5 text-xs",children:["ideate","generating","review"].map((f,r)=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs("div",{className:`flex items-center gap-1.5 px-2.5 py-1 rounded-full transition-colors ${i===f?"bg-info text-foreground font-semibold":["generating","review"].indexOf(f)<=["ideate","generating","review"].indexOf(i)?"text-success":"text-muted-foreground"}`,children:[f==="ideate"&&"1 · Ideate",f==="generating"&&"2 · Generate",f==="review"&&"3 · Review"]}),r<2&&e.jsx(Qr,{className:"w-3 h-3 text-muted-foreground"})]},f))}),i!=="generating"&&e.jsx("button",{onClick:te,className:"text-muted-foreground hover:text-foreground transition-colors","data-testid":"button-close-wizard",children:e.jsx(Ae,{className:"w-4 h-4"})})]}),i==="ideate"&&e.jsx("div",{className:"flex-1 overflow-y-auto p-6 space-y-5",style:{maxHeight:"calc(92vh - 130px)"},children:e.jsxs("div",{className:"max-w-2xl mx-auto space-y-5",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-foreground mb-1",children:"What's your article about?"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Give it a working title or describe the idea — AI will do the rest."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs text-muted-foreground font-medium flex items-center gap-1.5",children:[e.jsx(nt,{className:"w-3 h-3"})," Working Title"]}),e.jsx(he,{value:j,onChange:f=>k(f.target.value),placeholder:"e.g. Why Leadership Teams Stop Being Honest",className:"bg-card border-border text-foreground text-sm h-10 focus:border-info","data-testid":"input-wizard-title"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs text-muted-foreground font-medium flex items-center gap-1.5",children:[e.jsx(Xr,{className:"w-3 h-3"})," Focus Keyword ",e.jsx("span",{className:"text-muted-foreground",children:"(for SEO — strongly recommended)"})]}),e.jsx(he,{value:p,onChange:f=>u(f.target.value),placeholder:"e.g. leadership capability",className:"bg-card border-border text-foreground text-sm h-10 focus:border-info","data-testid":"input-wizard-keyword"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs text-muted-foreground font-medium",children:"Tone"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:wi.map(f=>e.jsx("button",{onClick:()=>H(f.v),className:`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${x===f.v?"bg-info text-foreground":"bg-secondary text-muted-foreground hover:bg-secondary hover:text-foreground border border-border"}`,"data-testid":`button-tone-${f.v}`,children:f.l},f.v))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-xs text-muted-foreground font-medium",children:["Brief / Angle ",e.jsx("span",{className:"text-muted-foreground",children:"(optional but helps)"})]}),e.jsx(ze,{value:N,onChange:f=>P(f.target.value),placeholder:"What's the key insight? What will the reader walk away knowing? Any specific examples or frameworks to include?",className:"bg-card border-border text-foreground text-sm resize-none focus:border-info",rows:3,"data-testid":"input-wizard-brief"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("button",{onClick:ne,disabled:L||!j.trim()&&!N.trim(),className:"flex items-center gap-1.5 text-xs text-info hover:text-info disabled:opacity-40 disabled:cursor-not-allowed transition-colors","data-testid":"button-suggest-angles",children:[L?e.jsx(ie,{className:"w-3 h-3 animate-spin"}):e.jsx($e,{className:"w-3 h-3"}),L?"Thinking…":"Suggest 5 article angles"]}),T.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Click an angle to use it as your title:"}),T.map((f,r)=>e.jsxs("button",{onClick:()=>
30k(f),className:`w-full text-left px-3 py-2 rounded-lg border text-xs transition-colors ${j===f?"bg-info/20 border-info/60 text-info":"bg-card border-border text-foreground hover:bg-secondary hover:text-foreground"}`,"data-testid":`button-angle-${r}`,children:[e.jsxs("span",{className:"text-info font-bold mr-1.5",children:[r+1,"."]}),f]},r))]})]})]})}),i==="generating"&&e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center p-8 space-y-6",style:{minHeight:"420px"},children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx("div",{className:"w-14 h-14 rounded-full bg-info/20 flex items-center justify-center mx-auto",children:e.jsx(ct,{className:"w-7 h-7 text-info animate-pulse"})}),e.jsx("h3",{className:"text-lg font-bold text-foreground",children:"Generating your article"}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-sm",children:"AI is writing everything from scratch — content, images, SEO, FAQs. This takes 2-4 minutes."})]}),e.jsx("div",{className:"w-full max-w-sm space-y-2.5",children:B.map((f,r)=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"w-5 h-5 shrink-0 flex items-center justify-center",children:[f.status==="done"&&e.jsx(Te,{className:"w-4 h-4 text-success"}),f.status==="running"&&e.jsx(ie,{className:"w-4 h-4 text-info animate-spin"}),f.status==="pending"&&e.jsx(Qs,{className:"w-4 h-4 text-muted-foreground"}),f.status==="skipped"&&e.jsx(Zr,{className:"w-4 h-4 text-muted-foreground"}),f.status==="error"&&e.jsx(Ae,{className:"w-4 h-4 text-destructive"})]}),e.jsx("span",{className:`text-sm transition-colors ${f.status==="running"?"text-foreground font-medium":f.status==="done"?"text-success":(f.status==="skipped","text-muted-foreground")}`,children:f.label})]},r))})]}),i==="review"&&c&&(()=>{const{score:f,checks:r}=Us(c);return e.jsxs("div",{className:"flex flex-1 overflow-hidden",style:{maxHeight:"calc(92vh - 130px)"},children:[e.jsxs("div",{className:`shrink-0 border-r border-border flex flex-col overflow-y-auto p-4 space-y-4 transition-all duration-200 ${S?"hidden":"w-72"}`,children:[e.jsxs("div",{className:"bg-card rounded-xl border border-border p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Mt,{className:"w-3.5 h-3.5 text-accent-gold"}),e.jsx("span",{className:"text-xs font-semibold text-foreground",children:"SEO Score"})]}),e.jsxs("div",{className:"relative w-12 h-12",children:[e.jsxs("svg",{viewBox:"0 0 36 36",className:"w-12 h-12 -rotate-90",children:[e.jsx("circle",{cx:"18",cy:"18",r:"15.9",fill:"none",stroke:"#1e2d40",strokeWidth:"3"}),e.jsx("circle",{cx:"18",cy:"18",r:"15.9",fill:"none",stroke:f>=90?"#22c55e":f>=70?"#f59e0b":"#ef4444",strokeWidth:"3",strokeDasharray:`${f} 100`,strokeLinecap:"round"})]}),e.jsxs("span",{className:"absolute inset-0 flex items-center justify-center text-xs font-bold text-foreground",children:[f,"%"]})]})]}),e.jsx("div",{className:"space-y-1",children:r.map((v,_)=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${v.ok?"bg-success":v.warn?"bg-warning":"bg-destructive"}`}),e.jsx("span",{className:`text-[10px] leading-tight ${v.ok?"text-success":v.warn?"text-warning-ink":"text-destructive"}`,children:v.label})]},_))})]}),c.coverImage&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"text-[10px] text-muted-foreground font-medium flex items-center gap-1",children:[e.jsx(Pt,{className:"w-3 h-3"})," Cover Image"]}),e.jsx("img",{src:c.coverImage,alt:c.coverImageAlt||"",className:"w-full aspect-video object-cover rounded-lg border border-border"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-[10px] text-muted-foreground font-medium",children:"Title"}),e.jsx("p",{className:"text-xs text-foreground font-medium leading-tight",children:c.title})]}),c.subtitle&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-[10px] text-muted-foreground font-medium",children:"Subtitle"}),e.jsx("p",{className:"text-xs text-foreground leading-tight",children:c.subtitle})]}),c.metaTitle&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("label",{className:"text-[10px] text-muted-foreground font-medium",children:["Meta Title (",c.metaTitle.length," chars)"]}),e.jsx("p",{className:"text-xs text-foreground leading-tight",children:c.metaTitle})]}),c.metaDescription&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("label",{className:"text-[10px] text-muted-foreground font-medium",children:["Meta Description (",c.metaDescription.length," chars)"]}),e.jsx("p",{className:"text-xs text-muted-foreground leading-tight",children:c.metaDescription})]}),c.excerpt&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-[10px] text-muted-foreground font-medium",children:"Excerpt"}),e.jsx("p",{className:"text-xs text-muted-foreground leading-tight",children:c.excerpt})]}),c.keyTakeaways.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("label",{className:"text-[10px] text-muted-foreground font-medium",children:["Key Takeaways (",c.keyTakeaways.length,")"]}),e.jsx("ul",{className:"space-y-0.5",children:c.keyTakeaways.map((v,_)=>e.jsxs("li",{className:"text-[10px] text-muted-foreground flex gap-1",children:[e.jsx("span",{className:"text-success shrink-0",children:"·"}),v]},_))})]})]})]}),e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-5 pt-4 pb-1 shrink-0",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-widest font-semibold",children:"Article Preview"}),e.jsxs("button",{onClick:()=>l(v=>!v),className:"flex items-center gap-1.5 text-[10px] text-muted-foreground hover:text-foreground transition-colors",title:S?"Show sidebar":"Expand preview","data-testid":"button-wizard-expand-preview",children:[S?e.jsx(en,{className:"w-3.5 h-3.5"}):e.jsx(tn,{className:"w-3.5 h-3.5"}),S?"Show sidebar":"Expand"]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-5 pb-4",children:[e.jsx("h2",{className:"text-lg font-bold text-foreground mb-1 leading-tight",children:c.title}),c.subtitle&&e.jsx("p",{className:"text-sm text-muted-foreground mb-4 italic",children:c.subtitle}),e.jsx(vi,{blocks:c.blocks}
30)]}),e.jsxs("div",{className:"border-t border-border p-3 shrink-0",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(ct,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground pointer-events-none"}),e.jsx("input",{value:J,onChange:v=>re(v.target.value),onKeyDown:v=>{v.key==="Enter"&&!v.shiftKey&&(v.preventDefault(),w())},placeholder:'Refine with AI — e.g. "add a callout about trust" or "shorten all paragraphs"',className:"w-full pl-9 pr-3 py-2 rounded-lg bg-secondary border border-border text-sm text-foreground placeholder-muted-foreground focus:outline-none focus:border-info transition-colors",disabled:I,"data-testid":"input-wizard-instruction"})]}),e.jsx("button",{onClick:w,disabled:I||!J.trim(),className:"px-3 py-2 rounded-lg bg-info hover:bg-info/90 disabled:opacity-40 text-foreground transition-colors shrink-0","data-testid":"button-wizard-run-instruction",children:I?e.jsx(ie,{className:"w-4 h-4 animate-spin"}):e.jsx(xt,{className:"w-4 h-4"})})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1.5 ml-1",children:"Press Enter to apply · Full AI editor available after saving"})]})]})]})})(),e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-t border-border shrink-0 bg-background",children:[i==="ideate"&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"AI will write, optimise, and score your article automatically."}),e.jsxs("button",{onClick:we,disabled:!j.trim()&&!N.trim(),className:"flex items-center gap-2 px-5 py-2.5 rounded-lg bg-info hover:bg-info/90 disabled:opacity-40 disabled:cursor-not-allowed text-foreground text-sm font-semibold transition-colors","data-testid":"button-wizard-generate",children:[e.jsx(Se,{className:"w-4 h-4"}),"Generate Everything",e.jsx(sn,{className:"w-4 h-4"})]})]}),i==="generating"&&e.jsx("p",{className:"text-xs text-muted-foreground mx-auto",children:"Working through all the steps — hang tight, this will be worth it."}),i==="review"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>m("ideate"),className:"text-xs text-muted-foreground hover:text-foreground transition-colors","data-testid":"button-wizard-back",children:"← Start over"}),e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("button",{onClick:()=>R("draft"),disabled:$,className:"px-4 py-2 rounded-lg bg-secondary hover:bg-secondary text-foreground text-sm font-medium transition-colors border border-border disabled:opacity-40","data-testid":"button-wizard-save-draft",children:[$?e.jsx(ie,{className:"w-4 h-4 animate-spin inline mr-1.5"}):null,"Save as Draft"]}),e.jsxs("button",{onClick:()=>R("published"),disabled:$,className:"flex items-center gap-2 px-5 py-2 rounded-lg bg-success hover:bg-success/90 text-success-foreground text-sm font-semibold transition-colors disabled:opacity-40","data-testid":"button-wizard-publish",children:[$?e.jsx(ie,{className:"w-4 h-4 animate-spin"}):e.jsx(Te,{className:"w-4 h-4"}),"Approve & Publish"]})]})]})]})]})})}function ml({token:t,permissions:s,initialArticleId:a,initialTitle:n}){const{toast:i}=De(),[m,j]=h.useState([]),[k,p]=h.useState(!0),[u,N]=h.useState("all"),[P,x]=h.useState("all"),[H,T]=h.useState(""),[A,L]=h.useState("newest"),[E,B]=h.useState(null),[U,c]=h.useState(!1),[D,$]=h.useState(!1),[F,J]=h.useState(!1),[re,I]=h.useState("basics"),[o,S]=h.useState(!1),[l,b]=h.useState("idle"),[M,W]=h.useState(null),[te,V]=h.useState(!1),[ne,Y]=h.useState(!1),[we,w]=h.useState(!1),[R,f]=h.useState(null),[r,v]=h.useState(null),_=h.useRef(null),[K,g]=h.useState(null),[C,X]=h.useState("idle"),[Q,ae]=h.useState(null),O=h.useRef(null),[pe,ce]=h.useState(null),[be,fe]=h.useState(!1),[ke,Ne]=h.useState(!1),[xe,je]=h.useState(!1),[d,G]=h.useState(null),[le,de]=h.useState(null),se=h.useRef(null);h.useEffect(()=>()=>{se.current&&clearInterval(se.current)},[]);const[ye,y]=h.useState(!1),[ue,Me]=h.useState(null),[Le,ns]=h.useState(!1),Ot=t?{...oe()}:{},is=async()=>{Ne(!0);try{const z=await fetch("/api/admin/seo-link-health",{headers:Ot});z.ok&&ce(await z.json())}catch(z){console.error("[AdminInsights] loadSeoLinkHealth failed:",z)}finally{Ne(!1)}},ma=async()=>{je(!0),de(null);try{const z=await fetch("/api/admin/seo-link-health/run",{method:"POST",headers:Ot});if(z.ok)i({title:"SEO link jobs started",description:"Running link injection and orphan fixer in the background."}),se.current&&clearInterval(se.current),se.current=setInterval(async()=>{try{const q=await fetch("/api/admin/inject-article-links/status",{headers:{...oe()}});if(q.ok){const Z=await q.json();de({done:Z.done??0,total:Z.total??0,linksAdded:Z.totalLinksAdded??0}),Z.running||(se.current&&clearInterval(se.current),je(!1),setTimeout(()=>{is(),Ht()},1e3))}}catch(q){console.error("[AdminInsights] link-run status poll failed:",q)}},2e3);else{const q=await z.json();i({title:"Failed to start",description:q.message??q.error??"Unknown error",variant:"destructive"}),je(!1)}}catch{je(!1)}},pa=async z=>{G(z);try{const q=await fetch("/api/admin/inject-article-links",{method:"POST",headers:{"Content-Type":"application/json",...oe()},body:JSON.stringify({testSlugs:[z]})});if(q.ok)i({title:"Boost started",description:`Injecting links into "${z}" in the background.`}),setTimeout(()=>Ht(),4e3);else{const Z=await q.json();i({title:"Boost failed",description:Z.error??"Unknown error",variant:"destructive"})}}catch(q){i({title:"Boost failed",description:q instanceof Error?q.message:"Network error",variant:"destructive"})}finally{G(null)}},Ht=async()=>{ns(!0);try{const z=await fetch("/api/admin/content-link-map",{headers:Ot});if(z.ok){const q=await z.json();Me(Array.isArray(q)?q:q.articles??[])}}catch(z){console.error("[AdminInsights] loadContentLinkMap failed:",z)}finally{ns(!1)}},ga=tt(s,"articles:create"),xa=tt(s,"articles:delete"),os=tt(s,"articles:publish"),ls=tt(s,"articles:featured"),fa=tt(s,"articles:edit_any");async function Oe(){p(!0);try{const z=await me("/api/admin/articles",t);
30j(z)}catch(z){i({title:"Error",description:z.message,variant:"destructive"})}finally{p(!1)}}h.useEffect(()=>{Oe()},[]);const cs=h.useRef(null);h.useEffect(()=>{if(!a||m.length===0||E||cs.current===a)return;const z=m.find(q=>q.id===a);z&&(cs.current=a,vt(z))},[a,m]),h.useEffect(()=>{!n||E||(B({...Zt,title:n}),I("basics"))},[n]),h.useEffect(()=>{const z=async q=>{const{articleId:Z}=q.detail;if(Z)try{const ge=await me(`/api/admin/articles/${Z}`,t);B(kt(ge)),I("basics")}catch{}};return window.addEventListener("admin:insights:open-article",z),()=>window.removeEventListener("admin:insights:open-article",z)},[t]),h.useEffect(()=>{E?(ae(E.audioUrl||null),X(E.audioUrl?"completed":"idle")):(g(null),X("idle"),ae(null),O.current&&clearInterval(O.current))},[E?.id]),h.useEffect(()=>(K&&(C==="pending"||C==="processing")&&(O.current&&clearInterval(O.current),O.current=setInterval(async()=>{try{const z=await fetch(`/api/admin/audio/jobs/${K}`,{headers:{...oe()}});if(z.ok){const q=await z.json();X(q.status),q.status==="completed"&&q.audioUrl?(ae(q.audioUrl),O.current&&clearInterval(O.current),Oe()):q.status==="failed"&&(O.current&&clearInterval(O.current),i({title:"Audio generation failed",description:q.error||"Unknown error",variant:"destructive"}))}}catch{}},3e3)),()=>{O.current&&clearInterval(O.current)}),[K,C]);async function ba(){if(!E?.id){i({title:"Save the article first",variant:"destructive"});return}X("pending");try{const z=await fetch("/api/admin/audio/generate",{method:"POST",headers:{"Content-Type":"application/json",...oe()},body:JSON.stringify({type:"article",id:E.id})});if(!z.ok){const Z=await z.json();throw new Error(Z.error||"Failed to start generation")}const q=await z.json();g(q.jobId),X("pending"),i({title:"Audio generation started",description:"This will take 1-2 minutes. Status will update automatically."})}catch(z){X("failed"),i({title:"Error",description:z.message,variant:"destructive"})}}function wa(){B({...Zt}),I("basics")}async function ya(z,q){const Z={...z,status:q};Z.excerpt?.trim()||(Z.excerpt=Z.metaDescription?.slice(0,155)||Z.title);const ge=Wt(Z),We=await fetch("/api/admin/articles",{method:"POST",headers:{"Content-Type":"application/json",...oe()},body:JSON.stringify(ge)}),He=await We.json();if(!We.ok)throw new Error(He.error||"Save failed");if(await Oe(),i({title:q==="published"?"Article published!":"Saved as draft"}),He.id){const Ie=await me(`/api/admin/articles/${He.id}`).catch(()=>He);B(kt(Ie)),I("basics")}}async function vt(z){try{const q=await me(`/api/admin/articles/${z.id}`,t);B(kt(q))}catch{B(kt(z))}I("basics")}async function ds(z,q){const Z=q?{...E,...q}:E;if(!Z)return!1;if(!Z.title.trim())return i({title:"Title is required",variant:"destructive"}),!1;if(!Z.excerpt.trim())return i({title:"Excerpt is required",variant:"destructive"}),!1;S(!0);try{let ge={...Z};if(!ge.metaTitle?.trim()&&!ge.metaDescription?.trim()&&ge.title)try{const He=(ge.blocks||[]).map(Ge=>Ge.content||Ge.text||"").join(" ").slice(0,1500),Ie=await me("/api/admin/articles/ai-assist",t,{method:"POST",body:JSON.stringify({action:"generate_meta",title:ge.title,content:He,focusKeyword:""})});Ie.metaTitle&&(ge={...ge,metaTitle:Ie.metaTitle}),Ie.metaDescription&&(ge={...ge,metaDescription:Ie.metaDescription}),B(Ge=>Ge&&{...Ge,metaTitle:ge.metaTitle,metaDescription:ge.metaDescription})}catch{}const We=Wt({...ge,status:z||ge.status});if(Z.id)await me(`/api/admin/articles/${Z.id}`,t,{method:"PUT",body:JSON.stringify(We)}),i({title:"Article saved",description:!Z.metaTitle?.trim()&&!Z.metaDescription?.trim()?"Auto-generated SEO meta fields":void 0});else{const He=await me("/api/admin/articles",t,{method:"POST",body:JSON.stringify(We)});B(Ie=>Ie&&{...Ie,id:He.id}),i({title:"Article created"})}return Oe(),!0}catch(ge){return i({title:"Error saving",description:ge.message,variant:"destructive"}),!1}finally{S(!1)}}async function va(){if(!E)return;const z=E.status==="published"?"draft":"published";await ds(z)&&B(Z=>Z&&{...Z,status:z})}async function ja(z){try{await me(`/api/admin/articles/${z.id}`,t,{method:"PUT",body:JSON.stringify({featured:!z.featured})}),j(q=>q.map(Z=>Z.id===z.id?{...Z,featured:!Z.featured}:Z))}catch(q){i({title:"Error",description:q.message,variant:"destructive"})}}async function Na(z){try{const q=z.status==="published"?"draft":"published";await me(`/api/admin/articles/${z.id}`,t,{method:"PUT",body:JSON.stringify({status:q})}),j(Z=>Z.map(ge=>ge.id===z.id?{...ge,status:q}:ge)),i({title:q==="published"?"Published":"Moved to draft"})}catch(q){i({title:"Error",description:q.message,variant:"destructive"})}}
30async function ka(){if(M){V(!0);try{await me(`/api/admin/articles/${M}`,t,{method:"DELETE"}),i({title:"Article deleted"}),W(null),j(z=>z.filter(q=>q.id!==M))}catch(z){i({title:"Error",description:z.message,variant:"destructive"})}finally{V(!1)}}}async function Ca(z){v(z.id);try{const q=await me("/api/admin/newsletter/campaigns/from-article",t,{method:"POST",body:JSON.stringify({articleId:z.id})});i({title:"Campaign created!",description:"Opening in newsletter editor..."}),setTimeout(()=>{window.location.href=`/admin?tab=newsletter&campaign=${q.campaign.id}`},800)}catch(q){i({title:"Error",description:q.message,variant:"destructive"})}finally{v(null)}}async function Sa(z){const q=E;if(!(!q||!q.title.trim()||!q.id)){b("saving");try{const Z=Wt(q);await me(`/api/admin/articles/${q.id}`,t,{method:"PUT",body:JSON.stringify(Z)}),b("saved"),Oe()}catch(Z){b("error"),i({title:"Autosave failed",description:Z?.message||"Check your connection — your last edit was not saved.",variant:"destructive"})}}}return h.useEffect(()=>{if(E)return _.current&&clearTimeout(_.current),_.current=setTimeout(()=>{Sa()},1800),()=>{_.current&&clearTimeout(_.current)}},[E?.blocks,E?.title,JSON.stringify(E?.sources)]),h.useEffect(()=>{if(l==="saved"){const z=setTimeout(()=>b("idle"),3e3);return()=>clearTimeout(z)}},[l]),U?e.jsx(yn,{token:t,onClose:()=>c(!1),onEditArticle:z=>{const q=m.find(Z=>Z.id===z);q?vt(q):Oe().then(()=>{me("/api/admin/articles").then(Z=>{const ge=Z.find(We=>We.id===z);ge&&vt(ge),c(!1)}).catch(Z=>{console.error("[AdminInsights] reload article after template failed:",Z),c(!1)})}).catch(Z=>console.error("[AdminInsights] loadArticles after template failed:",Z)),c(!1)}}):D?e.jsx(vn,{token:t,onClose:()=>$(!1),onImportComplete:()=>{$(!1),Oe()}}):F?e.jsx(jn,{token:t,onClose:()=>J(!1),onImportComplete:()=>{J(!1),Oe()}}):E!==null?e.jsx(fi,{editor:E,setEditor:B,token:t,saving:o,saveStatus:l,saveArticle:ds,showAiPanel:ne,setShowAiPanel:Y,editorSection:re,setEditorSection:I,canPublish:os,canFeature:ls,togglePublish:va,audioJobStatus:C,audioUrl:Q,generateAudio:ba,permissions:s}):e.jsx(ss,{pageName:"AdminInsights",children:e.jsxs(e.Fragment,{children:[e.jsx(bi,{token:t,permissions:s,articles:m,loading:k,canCreate:ga,canDelete:xa,canPublish:os,canFeature:ls,canEditAny:fa,statusFilter:u,setStatusFilter:N,categoryFilter:P,setCategoryFilter:x,searchQuery:H,setSearchQuery:T,sortBy:A,setSortBy:L,seoLinkHealth:pe,seoLinkPanelOpen:be,setSeoLinkPanelOpen:fe,seoLinkLoading:ke,seoLinkRunning:xe,linkRunProgress:le,loadSeoLinkHealth:is,loadContentLinkMap:Ht,triggerSeoLinkRun:ma,linkMapPanelOpen:ye,setLinkMapPanelOpen:y,linkMapData:ue,linkMapLoading:Le,boostingSlug:d,boostArticle:pa,openNew:wa,openWizard:()=>w(!0),openEdit:vt,toggleFeatured:ja,quickToggleStatus:Na,createNewsletterCampaign:Ca,setLinkedInArticle:f,setDeleteArticleId:W,deleteArticleId:M,deleteLoading:te,deleteArticle:ka,linkedInArticle:R,setShowTemplates:c,setShowImport:$,setShowBulkImport:J,creatingCampaign:r}),e.jsx(ji,{token:t,open:we,onClose:()=>w(!1),onSave:ya})]})})}export{ml 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.