@canonry/canonry 4.141.0 → 4.143.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/agent-workspace/skills/canonry/references/canonry-cli.md +45 -5
- package/assets/assets/{AuditHistoryPanel-DlyLhzqq.js → AuditHistoryPanel--kNrRAQm.js} +1 -1
- package/assets/assets/{BacklinksPage-DNxtwQBF.js → BacklinksPage-CtW1w9lh.js} +1 -1
- package/assets/assets/{ChartPrimitives-BStLR_NC.js → ChartPrimitives-C-nMEqdu.js} +1 -1
- package/assets/assets/{HistoryPage-CIcCgoWK.js → HistoryPage-CAPJDSbc.js} +1 -1
- package/assets/assets/ProjectPage-79R3wJW6.js +9 -0
- package/assets/assets/{RunRow-C0mFtLlc.js → RunRow-aDzTzGSK.js} +1 -1
- package/assets/assets/{RunsPage-C-yo0yoj.js → RunsPage-Dy9oWMBK.js} +1 -1
- package/assets/assets/{SettingsPage-jg4MXOuo.js → SettingsPage-DTAs1BrZ.js} +1 -1
- package/assets/assets/{TrafficPage-CnYHIg8t.js → TrafficPage-B4ADqeKG.js} +1 -1
- package/assets/assets/{TrafficSourceDetailPage-CEdyQT2P.js → TrafficSourceDetailPage-CFcoL_PR.js} +1 -1
- package/assets/assets/{arrow-left-DUv0imIl.js → arrow-left-DV9xcX1v.js} +1 -1
- package/assets/assets/{extract-error-message-CCOGDwlm.js → extract-error-message-DXtgw8Q8.js} +1 -1
- package/assets/assets/{index-BDo9nl4O.css → index-CYA3jd24.css} +1 -1
- package/assets/assets/index-H2iFFrr1.js +213 -0
- package/assets/assets/{trash-2-1Yg9W-vs.js → trash-2-DMV6uGU1.js} +1 -1
- package/assets/index.html +2 -2
- package/dist/{chunk-ZCFQGF3V.js → chunk-3G5B3IMZ.js} +319 -7
- package/dist/{chunk-OJOA425V.js → chunk-KUPTGRME.js} +4342 -3042
- package/dist/{chunk-HXXO2AF5.js → chunk-TJ6SDLXL.js} +4 -4
- package/dist/{chunk-2LUSZFB6.js → chunk-VN3CI6K6.js} +3339 -1226
- package/dist/cli.js +187 -65
- package/dist/index.js +4 -4
- package/dist/{intelligence-service-4HQIUC7U.js → intelligence-service-V6JYDYGF.js} +2 -2
- package/dist/mcp.js +2 -2
- package/package.json +9 -9
- package/assets/assets/ProjectPage-BSI3Qum9.js +0 -8
- package/assets/assets/index-D6EP4dQs.js +0 -213
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{j as e,r as l,L as zt,n as as,u as Ne,o as en,A as Ki,B as Fi,h as _i}from"./vendor-tanstack-Be8JdV5M.js";import{c as rn,T as Z,t as Ui,a as Bi,S as Gi,X as Qi,C as Pa,u as Br,b as zi,P as Ts,B as A,h as Hi,d as Vi,e as Wi,f as te,i as H,g as ze,j as ye,I as Ke,k as Gs,l as Yi,m as V,n as Ji,o as Xi,p as Zi,q as eo,r as Gr,s as to,v as so,w as hs,x as no,y as ao,z as us,A as Dt,D as ro,E as Xa,F as Qr,G as We,H as Ra,J as io,K as oo,L as lo,M as co,N as Za,O as xe,Q as zr,R as uo,U as zn,V as mo,W as ho,Y as xo,Z as po,_ as go,$ as fo,a0 as bo,a1 as jo,a2 as yo,a3 as vo,a4 as No,a5 as wo,a6 as So,a7 as Co,a8 as ko,a9 as Ao,aa as fs,ab as $o,ac as Hr,ad as Ln,ae as To,af as Po,ag as Ro,ah as Lo,ai as In,aj as Io,ak as Do,al as Eo,am as pa,an as Mo,ao as qo,ap as ga,aq as Oo,ar as Ko,as as Ps,at as Vr,au as Wr,av as Fo,aw as Yr,ax as _o,ay as Uo,az as Bo,aA as Go,aB as Jr,aC as Qo,aD as zo,aE as Ho,aF as Ys,aG as xs,aH as Vo,aI as Wo,aJ as Yo,aK as Jo,aL as Xr,aM as Xo,aN as Zo,aO as el,aP as tl,aQ as sl,aR as Zr,aS as nl,aT as La,aU as al,aV as rl,aW as il,aX as er,aY as ol,aZ as ll,a_ as cl,a$ as dl,b0 as ul,b1 as ml,b2 as hl,b3 as xl,b4 as pl,b5 as gl,b6 as fl,b7 as bl,b8 as jl,b9 as yl,ba as vl,bb as Nl,bc as wl,bd as Sl,be as Hn,bf as Cl,bg as kl,bh as tr,bi as Al,bj as $l,bk as Tl,bl as Pl,bm as Rl,bn as Ll,bo as Il,bp as Dl,bq as El,br as Ml,bs as ql,bt as Ol,bu as Kl,bv as Fl,bw as _l,bx as Ul,by as sr,bz as Bl,bA as Vn,bB as Gl,bC as Ql,bD as zl,bE as Hl,bF as Vl,bG as nr,bH as Wl,bI as Yl,bJ as Jl,bK as Xl,bL as Zl,bM as ec,bN as tc,bO as sc,bP as nc,bQ as ei,bR as ti,bS as ac,bT as si,bU as rc,bV as ni,bW as ic,bX as oc,bY as yn,bZ as lc,b_ as cc,b$ as dc,c0 as ar}from"./index-H2iFFrr1.js";import{R as uc}from"./RunRow-aDzTzGSK.js";import{C as mc,R as tn,f as fa,a as Wt,b as vt,c as Dn,d as ps,e as at,g as nt,h as Ht,i as Ia,j as Da,k as ns,o as Et,p as hc}from"./ChartPrimitives-C-nMEqdu.js";import{u as xc,t as pc,e as gc}from"./extract-error-message-DXtgw8Q8.js";import{R as Rs,C as Ls,X as Is,Y as Ds,T as Es,L as ai,A as Ns,a as Ea,b as fc,d as Ma,e as bc}from"./vendor-recharts-DSxTZhaH.js";import{D as ri,C as jc,E as yc,T as vc}from"./trash-2-DMV6uGU1.js";import{A as Nc}from"./AuditHistoryPanel--kNrRAQm.js";import"./vendor-radix-CQ77EO2y.js";import"./vendor-markdown-6dwjPOKK.js";const wc=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],ii=rn("circle-check",wc);const Sc=[["path",{d:"M5 12h14",key:"1ays0h"}]],Cc=rn("minus",Sc);const kc=[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"m16 16-1.9-1.9",key:"1dq9hf"}]],Ac=rn("scan-search",kc);const $c=[["path",{d:"m19 5 3-3",key:"yk6iyv"}],["path",{d:"m2 22 3-3",key:"19mgm9"}],["path",{d:"M6.3 20.3a2.4 2.4 0 0 0 3.4 0L12 18l-6-6-2.3 2.3a2.4 2.4 0 0 0 0 3.4Z",key:"goz73y"}],["path",{d:"M7.5 13.5 10 11",key:"7xgeeb"}],["path",{d:"M10.5 16.5 13 14",key:"10btkg"}],["path",{d:"m12 6 6 6 2.3-2.3a2.4 2.4 0 0 0 0-3.4l-2.6-2.6a2.4 2.4 0 0 0-3.4 0Z",key:"1snsnr"}]],Tc=rn("unplug",$c);const Pc=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],Rc=rn("upload",Pc);function Pn(t){return Number.isFinite(t)?Math.abs(t)>=1e6?`${(t/1e6).toFixed(1)}M`:Math.abs(t)>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString("en-US"):"—"}function Lc(t,s){return s<=0?null:Math.round((t-s)/s*100)}function Wn(t,s,n="vs prior 7 days"){return t.deltaPct===null?t.prior===0?"First baseline week":"":t.deltaPct>0?`Up ${t.deltaPct}% ${n} (${Pn(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${Pn(t.prior)} ${s})`:`Flat ${n} (${Pn(t.prior)} ${s})`}const oi=30;function rr(t){return Math.round(t*10)/10}function Ic(t){return t.prior>=oi&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% vs prior`:`${t.deltaAbs>0?"+":""}${rr(t.deltaAbs)} vs ${rr(t.prior)}`}function Dc(t,s,n){return t.prior>=oi&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% ${n}`:`${t.deltaAbs>0?"+":""}${Pn(Math.round(t.deltaAbs))} ${s} ${n}`}const Ec=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function li(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function ci(t){return t.length>4&&t.endsWith("ies")?`${t.slice(0,-3)}y`:t.length>4&&t.endsWith("s")&&!t.endsWith("ss")?t.slice(0,-1):t}function di(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(li).map(ci).filter(Boolean)):new Set}function ui(t,s){const n=li(t).map(ci).filter(Boolean).filter(a=>!Ec.has(a)).filter(a=>!s.has(a));return[...new Set(n)].sort().join(" ")}function Mc(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function qc(t,s){const n=di(t);if(s.length<=1||n.size===0)return[...s];const a=new Set,r=[];for(const i of s){if(i.category!=="content"){r.push(i);continue}const c=ui(Mc(i),n);!c||a.has(c)||(a.add(c),r.push(i))}return r}function Oc(t){const s=di(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const a=new Set;return n.filter(r=>{const i=ui(r.query,s);return!i||a.has(i)?!1:(a.add(i),!0)})}function ba({state:t,label:s}){return e.jsx(Z,{tone:Bi(t),children:s??Ui(t)})}const Tt=25;function Kc(t){return t.trim().toLocaleLowerCase().split(/\s+/).filter(Boolean)}function mi(t){let s=t;try{s=decodeURIComponent(t.replace(/\+/g," "))}catch{}let n="";const a=t.indexOf("?");return a>=0&&new URLSearchParams(t.slice(a+1)).forEach((i,c)=>{n+=` ${c} ${i}`}),`${t} ${s}${n}`}function Fc(t,s=36,n=18){const a=[...t];return a.length<=s+n+1?t:`${a.slice(0,s).join("")}…${a.slice(-n).join("")}`}function Js({value:t,headLength:s,tailLength:n,className:a,title:r}){const i=Fc(t,s,n);return e.jsx("span",{className:a,title:r??t,children:i===t?t:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"sr-only",children:t}),e.jsx("span",{"aria-hidden":"true",children:i})]})})}function sn({rows:t,getSearchText:s,pageSize:n=Tt}){const[a,r]=l.useState(""),[i,c]=l.useState(1),u=l.useMemo(()=>Kc(a),[a]),o=l.useMemo(()=>u.length===0||!s?t:t.filter(v=>{const j=s(v).toLocaleLowerCase();return u.every(D=>j.includes(D))}),[s,t,u]),h=Math.max(1,Math.ceil(o.length/n)),p=Math.min(Math.max(1,i),h),m=(p-1)*n,g=l.useMemo(()=>o.slice(m,m+n),[o,n,m]),k=l.useCallback(v=>{r(v),c(1)},[]),R=l.useCallback(v=>{c(Math.max(1,v))},[]);return{query:a,setQuery:k,page:p,setPage:R,rows:g,filteredRows:o,totalRows:o.length,totalPages:h,pageSize:n,rangeStart:o.length===0?0:m+1,rangeEnd:m+g.length,hasQuery:a.trim().length>0}}function Ss({value:t,onChange:s,label:n,placeholder:a="Filter rows",className:r}){return e.jsxs("div",{className:`relative ${r??""}`,children:[e.jsx(Gi,{"aria-hidden":"true",className:"pointer-events-none absolute left-3 top-1/2 size-3.5 -translate-y-1/2 text-muted"}),e.jsx("input",{type:"search",value:t,onChange:i=>s(i.target.value),"aria-label":n,placeholder:a,autoComplete:"off",spellCheck:!1,className:"h-9 w-full rounded-md border border-default bg-surface/50 pl-9 pr-9 text-sm text-strong placeholder:text-muted outline-none transition focus:border-mono-500 focus:ring-1 focus:ring-mono-500 [&::-webkit-search-cancel-button]:appearance-none"}),t.trim().length>0?e.jsx("button",{type:"button",onClick:()=>s(""),"aria-label":`Clear ${n.toLocaleLowerCase()}`,className:"absolute right-2 top-1/2 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded text-muted transition-colors hover:bg-surface-hover hover:text-strong focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",children:e.jsx(Qi,{"aria-hidden":"true",className:"size-3.5"})}):null]})}function gs({page:t,pageSize:s=Tt,visibleRows:n,totalRows:a,hasNextPage:r,onPageChange:i,itemLabel:c="rows",className:u,disabled:o=!1}){if(n===0)return null;const h=(t-1)*s+1,p=h+n-1,m=a===void 0?void 0:Math.max(1,Math.ceil(a/s)),g=r??(m!==void 0&&t<m),k=t>1||g;return e.jsxs("div",{className:`mt-3 flex flex-wrap items-center justify-between gap-x-4 gap-y-2 text-xs text-secondary ${u??""}`,children:[e.jsxs("p",{className:"tabular-nums",children:[h.toLocaleString("en-US"),"–",p.toLocaleString("en-US"),a===void 0?`${g?"+":""} ${c}`:` of ${a.toLocaleString("en-US")} ${c}`]}),k?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>i(t-1),disabled:o||t<=1,className:"inline-flex items-center gap-1 rounded-md border border-base bg-bg px-2.5 py-1.5 text-strong transition hover:border-strong hover:text-primary disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-base disabled:hover:text-strong",children:[e.jsx(mc,{"aria-hidden":"true",className:"size-3.5"}),"Previous"]}),e.jsx("span",{className:"tabular-nums",children:m===void 0?`Page ${t}`:`Page ${t} of ${m}`}),e.jsxs("button",{type:"button",onClick:()=>i(t+1),disabled:o||!g,className:"inline-flex items-center gap-1 rounded-md border border-base bg-bg px-2.5 py-1.5 text-strong transition hover:border-strong hover:text-primary disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-base disabled:hover:text-strong",children:["Next",e.jsx(Pa,{"aria-hidden":"true",className:"size-3.5"})]})]}):null]})}function ir({history:t,maxDots:s=12}){const n=t.slice(-s);if(n.length===0)return e.jsx("span",{className:"text-[11px] text-faint",children:"No data"});const a={cited:"bg-positive-400","not-cited":"bg-mono-600",lost:"bg-negative-400",emerging:"bg-caution-400 ring-1 ring-caution-300/60"},r={cited:"rounded-full","not-cited":"rounded-sm",lost:"rotate-45 rounded-[1px]",emerging:"rounded-full"},i=n.length-1,c=new Date(n[0].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),u=new Date(n[i].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),o=n.map((h,p)=>{const m=new Date(h.createdAt).toLocaleDateString();return`${p===i?"Latest run, ":""}${m}: ${h.citationState}${h.model?`, model ${h.model}`:""}`}).join("; ");return e.jsxs("div",{className:"flex items-center gap-1",role:"img","aria-label":`Citation history across ${n.length} runs. ${o}`,children:[e.jsx("span",{className:"text-[9px] text-faint shrink-0","aria-hidden":"true",children:c}),e.jsx("div",{className:"flex items-center gap-[3px]",title:`${n.length} runs`,"aria-hidden":"true",children:n.map((h,p)=>{const m=!!(h.model&&p>0&&n[p-1]?.model&&n[p-1].model!==h.model),g=p===i;return e.jsx("span",{className:`h-2.5 w-2.5 ${r[h.citationState]??"rounded-sm"} ${a[h.citationState]??"bg-mono-700"} ${m?"ring-1 ring-caution-300/80 ring-offset-1 ring-offset-bg":""} ${g?"outline outline-1 outline-offset-2 outline-mono-400":""}`,title:[h.citationState,new Date(h.createdAt).toLocaleDateString(),h.model?`model ${h.model}`:null,m?"model changed":null,g?"latest run":null].filter(Boolean).join(" · ")},`${h.runId}:${h.createdAt}`)})}),e.jsxs("span",{className:"text-[9px] shrink-0 text-secondary","aria-hidden":"true",children:[u," ",e.jsx("span",{className:"text-faint",children:"latest"})]})]})}function ja(t){const s=new Map;for(const a of t)for(const r of a.runHistory){const i=s.get(r.createdAt);i?i.states.push(r.citationState):s.set(r.createdAt,{states:[r.citationState],runId:r.runId})}return[...s.entries()].sort(([a],[r])=>a.localeCompare(r)).map(([a,{states:r,runId:i}])=>({runId:i,createdAt:a,citationState:r.includes("cited")?"cited":r.includes("emerging")?"emerging":"not-cited"}))}const _c=320;function Uc(t){return[t.phrase,t.location??"",...t.rawItems.map(s=>s.provider)].join(" ")}function or(t,s){return s==="citations"?t.citationState:t.visibilityState==="pending"||t.answerMentioned==null&&t.visibilityState==null?"pending":t.visibilityState==="visible"||t.answerMentioned===!0?"cited":"not-cited"}function lr(t,s){if(s==="mentions")switch(t){case"cited":return"Mentioned";case"not-cited":return"Not Mentioned";case"pending":return"Pending";case"emerging":return"Newly Mentioned";case"lost":return"No Longer Mentioned"}switch(t){case"cited":return"Cited";case"not-cited":return"Not Cited";case"lost":return"Lost";case"emerging":return"Emerging";case"pending":return"Pending"}}function cr(t,s){const n=s==="mentions"?"mentioned":"cited",a=s==="mentions"?"Mentioned":"Cited";if(t.length===0)return"Awaiting first run";if(t.length===1)return"First observation";const r=t[t.length-1].citationState,i=t[t.length-2].citationState;if(i!=="cited"&&r==="cited")return`Newly ${n}`;if(i==="cited"&&r!=="cited")return"Lost since last run";let c=0;for(let u=t.length-1;u>=0&&t[u].citationState===r;u--)c++;return r==="cited"?c<=1?`${a} in latest run`:`${a} for ${c} runs`:c<=1?`Not ${n} in latest run`:`Not ${n} across ${c} runs`}function Bc(t,s){return t.map(n=>hi(n,s))}function hi(t,s){return s==="citations"?t:{...t,citationState:or(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:or(n,s)}))}}function dr(t,s){const n=s==="mentions"?"mention":"citation",a=s==="mentions"?"Mention":"Citation";if(t.length===0)return{key:s,label:`${a} pending`,tone:"pending"};const r=t[t.length-1].citationState,i=t.length>=2?t[t.length-2].citationState:null,c=r==="cited"||r==="emerging",u=i==="cited"||i==="emerging";return r==="lost"||i!==null&&u&&!c?{key:s,label:`Lost ${n}`,tone:"negative"}:r==="emerging"||i!==null&&!u&&c?{key:s,label:`New ${n}`,tone:"positive"}:i===null&&c?{key:s,label:`First ${n}`,tone:"positive"}:c?{key:s,label:s==="mentions"?"Still mentioned":"Still cited",tone:"neutral"}:{key:s,label:`No ${n}`,tone:"neutral"}}function Gc(t){const s=ja(Bc(t,"mentions")),n=ja(t);return[dr(s,"mentions"),dr(n,"citations")]}function Qc({signal:t}){const s=t.tone==="positive"?"border-positive-500/25 bg-positive-500/10 text-positive":t.tone==="negative"?"border-negative-500/25 bg-negative-500/10 text-negative":t.tone==="pending"?"border-caution-500/20 bg-caution-500/10 text-caution":"border-mono-700/60 bg-bg-elevated/70 text-secondary";return e.jsx("span",{className:`inline-flex items-center rounded-md border px-1.5 py-0.5 text-[10px] font-medium leading-none ${s}`,children:t.label})}function ur({items:t}){return e.jsx("div",{className:"mt-1 flex flex-wrap gap-1","aria-label":"Latest run mention and citation signals",children:Gc(t).map(s=>e.jsx(Qc,{signal:s},s.key))})}function zc({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:a}=Br(),[r,i]=l.useState(new Set),[c,u]=l.useState("mentions"),[o,h]=l.useState(n),p=l.useMemo(()=>{const O=new Map;for(const E of t){const F=E.query,x=s?E.location??null:null,$=s?JSON.stringify([F,x]):F,M=O.get($)??{key:$,phrase:F,location:x,items:[],rawItems:[]};M.items.push(hi(E,c)),M.rawItems.push(E),O.set($,M)}return[...O.values()]},[t,c,s]),m=sn({rows:p,getSearchText:Uc}),g=m.rows.map(O=>O.key),k=g.length>0&&g.every(O=>r.has(O)),R=O=>{i(E=>{const F=new Set(E);return F.has(O)?F.delete(O):F.add(O),F})},v=c==="mentions"?"mentioned":"cited",j=c==="mentions"?"Mention History":"Citation History",D=c==="mentions"?"mentioned":"cited";return e.jsxs("div",{children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"View by"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-bg-elevated/60 border border-subtle",role:"tablist","aria-label":"Citation tracking view",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":c==="mentions",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${c==="mentions"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>u("mentions"),children:"Mentions"}),e.jsx("button",{type:"button",role:"tab","aria-selected":c==="citations",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${c==="citations"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>u("citations"),children:"Citations"})]}),e.jsx("span",{className:"text-[11px] text-muted",children:c==="mentions"?"Brand or domain in answer text":"Brand or domain in source links"}),e.jsxs("div",{className:"ml-auto flex items-center gap-3",children:[e.jsx("button",{type:"button",className:"text-[11px] text-secondary hover:text-strong",onClick:()=>{i(O=>{const E=new Set(O);for(const F of g)k?E.delete(F):E.add(F);return E})},children:k?"Collapse page":"Expand page"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Density"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-bg-elevated/60 border border-subtle",role:"tablist","aria-label":"Evidence row density",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":o==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${o==="compact"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>h("compact"),children:"Compact"}),e.jsx("button",{type:"button",role:"tab","aria-selected":o==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${o==="detailed"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>h("detailed"),children:"Detailed"})]})]})]})]}),p.length>0?e.jsx(Ss,{value:m.query,onChange:m.setQuery,label:"Filter tracked queries",placeholder:"Filter query, location, or provider",className:"mb-3 max-w-md"}):null,e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{style:{width:"2rem"}}),e.jsx("th",{scope:"col",children:"Query"}),e.jsx("th",{scope:"col",children:"Status"}),e.jsx("th",{scope:"col",children:j}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:m.rows.map(({key:O,phrase:E,location:F,items:x,rawItems:$})=>{const M=r.has(O),se=x.map(w=>w.citationState),de=se.includes("cited")?"cited":se.includes("emerging")?"emerging":se.includes("lost")?"lost":se.every(w=>w==="pending")?"pending":"not-cited",C=ja(x),b=x.filter(w=>w.citationState===zi.cited||w.citationState==="emerging").length,_=cr(C,c);return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"cursor-pointer hover:bg-mono-800/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>R(O),onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),R(O))},tabIndex:0,role:"button","aria-expanded":M,children:[e.jsx("td",{children:e.jsx(Pa,{size:14,className:`transition-transform duration-150 text-muted ${M?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-heading",children:E}),s&&e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-muted",children:F??"No location"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:x.map(w=>e.jsx(Ts,{provider:w.provider},w.id))})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ba,{state:de,label:lr(de,c)}),e.jsxs("span",{className:"text-[11px] text-muted",title:`${b} of ${x.length} engines ${D}`,children:[b,"/",x.length]})]})}),e.jsx("td",{children:e.jsx(ir,{history:C})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:_}),e.jsx(ur,{items:$})]}),e.jsx("td",{})]}),M&&x.map((w,B)=>e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"bg-surface",children:[e.jsx("td",{}),e.jsx("td",{className:"evidence-query-cell pl-5",children:e.jsx(Ts,{provider:w.provider})}),e.jsx("td",{children:e.jsx(ba,{state:w.citationState,label:lr(w.citationState,c)})}),e.jsx("td",{children:e.jsx(ir,{history:w.runHistory})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:cr(w.runHistory,c)}),e.jsx(ur,{items:[$[B]??w]})]}),e.jsx("td",{children:e.jsx(A,{variant:"ghost",size:"sm",type:"button",onClick:oe=>{oe.stopPropagation(),a(w.id)},children:"View"})})]}),o==="detailed"&&e.jsxs("tr",{className:"bg-surface-subtle",children:[e.jsx("td",{}),e.jsx("td",{colSpan:5,className:"px-5 pb-4",children:e.jsx(Wc,{item:w,onViewFull:()=>a(w.id)})})]})]},w.id))]},O)})})]})}),m.totalRows===0&&m.hasQuery?e.jsx("p",{className:"supporting-copy mt-3",children:"No tracked queries match this filter."}):null,e.jsx(gs,{page:m.page,pageSize:m.pageSize,visibleRows:m.rows.length,totalRows:m.totalRows,onPageChange:m.setPage,itemLabel:m.hasQuery?"matches":"queries"}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",v==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function Hc(t){const s=(t.matchedTerms??[]).filter(r=>r.trim().length>2),n=[...t.competitorDomains.flatMap(r=>{const i=Vi(r);return i.length>=4?[i]:[]}),...t.recommendedCompetitors??[]].filter(r=>r.trim().length>2),a=[];return s.length>0&&a.push({terms:s,className:"answer-highlight-brand"}),n.length>0&&a.push({terms:n,className:"answer-highlight-competitor"}),a}function Vc(t,s){if(t.length<=s)return{body:t,truncated:!1};const n=t.lastIndexOf(" ",s);return{body:`${t.slice(0,n>s-40?n:s).trimEnd()}…`,truncated:!0}}function Wc({item:t,onViewFull:s}){if(!(t.answerSnippet.trim().length>0))return e.jsx("p",{className:"text-[11px] text-muted italic",children:"No answer text captured for this run."});const{body:a,truncated:r}=Vc(t.answerSnippet,_c),i=Hc(t);return e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Answer text"}),e.jsx("p",{className:"text-sm leading-relaxed text-neutral",children:Hi(a,i)}),(t.citedDomains.length>0||t.competitorDomains.length>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[t.citedDomains.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Cited:"}),t.citedDomains.slice(0,6).map(c=>e.jsx("span",{className:"rounded-full border border-mono-700/60 bg-bg-elevated/60 px-2 py-0.5 text-[11px] text-neutral",children:c},`c-${c}`)),t.citedDomains.length>6&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.citedDomains.length-6," more"]})]}),t.competitorDomains.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-negative-500/80",children:"Competitors:"}),t.competitorDomains.slice(0,4).map(c=>e.jsx("span",{className:"rounded-full border border-negative-900/40 bg-negative-950/30 px-2 py-0.5 text-[11px] text-negative",children:c},`co-${c}`)),t.competitorDomains.length>4&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.competitorDomains.length-4," more"]})]})]}),r&&e.jsx("button",{type:"button",className:"text-[11px] font-medium text-positive-400 hover:text-positive",onClick:c=>{c.stopPropagation(),s()},children:"View full answer →"})]})}function Yc({competitors:t,onSelectCompetitor:s,onRemoveCompetitor:n,activeFilter:a}){if(t.length===0)return e.jsx("p",{className:"text-sm text-muted",children:"No competitors configured. Add competitors to track overlap."});const r=s!=null,i=n!=null;return e.jsx("div",{className:"competitor-table-wrap",children:e.jsxs("table",{className:"competitor-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Domain"}),e.jsx("th",{children:"Pressure"}),e.jsx("th",{children:"Citations"}),e.jsx("th",{children:"Queries"}),i&&e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{children:t.map(c=>{const u=a!=null&&a.toLowerCase()===c.domain.toLowerCase(),o=[r?"cursor-pointer hover:bg-mono-800/30 transition-colors":"",u?"bg-negative-950/20":""].filter(Boolean).join(" ");return e.jsxs("tr",{className:o,onClick:r?()=>s(c.domain):void 0,title:r?`Filter answers to queries where ${c.domain} surfaced`:void 0,children:[e.jsx("td",{className:"font-medium text-heading",children:c.domain}),e.jsx("td",{children:e.jsx(Z,{tone:Wi(c.pressureLabel),children:c.pressureLabel})}),e.jsx("td",{className:"text-neutral tabular-nums",children:c.totalQueries>0?`${c.citationCount} / ${c.totalQueries}`:"—"}),e.jsx("td",{className:"text-muted text-xs",children:c.citedQueries.length>0?c.citedQueries.join(", "):"Not cited"}),i&&e.jsx("td",{className:"text-right",children:e.jsx("button",{type:"button",className:"rounded px-1.5 py-0.5 text-xs text-muted transition-colors hover:text-negative-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-negative-500","aria-label":`Remove competitor ${c.domain}`,title:`Remove ${c.domain}`,onClick:h=>{h.stopPropagation(),n(c.domain)},children:"Remove"})})]},c.id)})})]})})}function vn({label:t,value:s,tone:n}){const a=n==="positive"?"text-positive-400":n==="negative"?"text-negative-400":"text-strong";return e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:t}),e.jsx("p",{className:`mt-2 text-2xl font-semibold ${a}`,children:s})]})}const Jc=6,Ms="__other__",Cs="_socialTotal";function Xc(t,s=Jc){const n=new Map;for(const p of t)n.set(p.source,(n.get(p.source)??0)+p.sessions);const a=[...n.entries()].sort((p,m)=>m[1]!==p[1]?m[1]-p[1]:p[0].localeCompare(m[0])),r=a.slice(0,s),i=new Set(r.map(([p])=>p)),c=Math.max(0,a.length-s),u=new Map;for(const p of t){let m=u.get(p.date);m||(m={date:p.date,[Cs]:0},u.set(p.date,m));const g=i.has(p.source)?p.source:Ms;m[g]=(m[g]??0)+p.sessions,m[Cs]=(m[Cs]??0)+p.sessions}const o=[...u.values()].sort((p,m)=>String(p.date).localeCompare(String(m.date))),h=r.map(([p])=>p);return c>0&&h.push(Ms),{data:o,sources:h,otherCount:c}}function ks(t){return t.replace(/\+/g," ")}function xi(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const mr="_totalSessions",hr="_organicSessions";function Zc(t,s){const n=new Map;for(const c of s)n.set(c.date,{[mr]:c.sessions,[hr]:c.organicSessions});for(const c of t.days){let u=n.get(c.date);u||(u={[mr]:0,[hr]:0},n.set(c.date,u));for(const o of c.bySource)u[o.source]=(u[o.source]??0)+o.sessions}const a=[...n.entries()].sort(([c],[u])=>c.localeCompare(u)).map(([c,u])=>({date:c,...u})),r=a.map(c=>c.date),i=r.length>0?{start:r[0],end:r[r.length-1]}:null;return{data:a,sources:t.sources,dateRange:i}}const ed=["7d","30d","90d","all"],ts=nt,ya=at.textDim,pi=at.textFaint,Qs=25;function td(t){return mi(t.landingPage)}const sd=25,Yn={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0};function Nn(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function gi(t){const s=Date.now()-new Date(t).getTime(),n=Math.floor(s/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const a=Math.floor(n/60);return a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`}function nd({projectName:t}){const{data:s,isLoading:n,isError:a}=xc(t);if(n)return e.jsx(te,{className:"p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading server activity…"})});if(a)return e.jsx(te,{className:"p-5",children:e.jsx("div",{className:"text-sm text-negative-400",children:"Failed to load server activity."})});const r=s?.sources??[];return e.jsxs("section",{children:[e.jsx("div",{className:"flex items-baseline justify-between mb-3",children:e.jsxs("div",{children:[e.jsx("div",{className:"eyebrow",children:"Server activity (last 24h)"}),e.jsx("h2",{className:"text-lg font-semibold text-primary",children:"Server activity"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["Crawler, AI fetch, and referral activity from connected sources."," ",!H()&&e.jsx(zt,{to:"/traffic",className:"text-link hover:underline",children:"Manage sources →"})]})]})}),r.length===0?e.jsx(te,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-secondary",children:["No server traffic source connected yet."," ",!H()&&e.jsxs(e.Fragment,{children:[e.jsx(zt,{to:"/traffic",className:"text-link hover:underline",children:"Connect a traffic source"})," ","to surface bot crawls and AI referrals straight from server logs."]})]})}):e.jsx(te,{className:"overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-bg-elevated/50 text-[10px] uppercase tracking-wide text-muted",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Source"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Status"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Crawler hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI sessions 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Last sync"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium","aria-label":"open"})]})}),e.jsx("tbody",{children:r.map(i=>e.jsxs("tr",{className:"border-t border-default",children:[e.jsx("td",{className:"px-4 py-3 text-heading",children:i.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(Z,{tone:pc(i.status),children:i.status})}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:i.totals24h.crawlerHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:i.totals24h.aiUserFetchHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:i.totals24h.aiReferralHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right text-secondary text-xs",children:i.lastSyncedAt?gi(i.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:H()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(zt,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:i.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},i.id))})]})})]})}function ad({projectName:t}){return e.jsxs("div",{className:"space-y-10",children:[e.jsx(nd,{projectName:t}),e.jsx(rd,{projectName:t})]})}function rd({projectName:t}){const s=as(),[n,a]=l.useState(null),[r,i]=l.useState(null),[c,u]=l.useState(!0),[o,h]=l.useState(!1),[p,m]=l.useState(!1),[g,k]=l.useState(null),[R,v]=l.useState(null),[j,D]=l.useState("sessions"),[O,E]=l.useState("desc"),[F,x]=l.useState("sessions"),[$,M]=l.useState("desc"),[se,de]=l.useState("sessions"),[C,b]=l.useState("desc"),[_,w]=l.useState("sessions"),[B,oe]=l.useState("desc"),[ee,U]=l.useState(Yn),[pe,le]=l.useState([]),[K,q]=l.useState([]),[y,Y]=l.useState(!1),[me,N]=l.useState("30d");async function G(I){u(!0),k(null);try{const ge=await s.fetchQuery({...Yi({client:V,path:{name:t}}),staleTime:Gs});if(I.current)return;if(a(ge),!ge.connected){i(null),U(Yn),le([]),q([]),u(!1);return}const ue=me==="all"?void 0:me,[ie,Ee,Os,Ge]=await Promise.all([s.fetchQuery({...Ji({client:V,path:{name:t},query:ue?{window:ue}:void 0}),staleTime:Gs}).then(ot=>ot),s.fetchQuery({...Xi({client:V,path:{name:t},query:ue?{window:ue}:void 0}),staleTime:Gs}).catch(()=>Yn),s.fetchQuery({...Zi({client:V,path:{name:t},query:ue?{window:ue}:void 0}),staleTime:Gs}).catch(()=>[]),s.fetchQuery({...eo({client:V,path:{name:t},query:ue?{window:ue}:void 0}),staleTime:Gs}).catch(()=>[])]);if(I.current)return;i(ie),U(Ee),le(Os),q(Ge),u(!1)}catch(ge){if(I.current)return;k(ge instanceof Error?ge.message:"Failed to load GA4 data"),u(!1)}}l.useEffect(()=>{const I={current:!1};return G(I),()=>{I.current=!0}},[t,me,s]);async function Q(){h(!0),k(null),v(null);try{const I=await Gr(t);v(`Synced ${I.rowCount.toLocaleString()} page rows, ${I.aiReferralCount.toLocaleString()} AI and ${I.socialReferralCount.toLocaleString()} social referral rows (${I.days} days)`),await ze(s,"ga"),await G({current:!1})}catch(I){k(I instanceof Error?I.message:"Sync failed")}finally{h(!1)}}async function T(){m(!0),k(null),v(null);try{await to(t),await ze(s,"ga"),a({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),i(null),v("GA4 disconnected")}catch(I){k(I instanceof Error?I.message:"Disconnect failed")}finally{m(!1)}}function ne(I){j===I?E(ge=>ge==="desc"?"asc":"desc"):(D(I),E("desc"))}function ce(I){F===I?M(ge=>ge==="desc"?"asc":"desc"):(x(I),M("desc"))}function Ae(I){se===I?b(ge=>ge==="desc"?"asc":"desc"):(de(I),b("desc"))}const Fe=l.useMemo(()=>r?.topPages?[...r.topPages].sort((I,ge)=>{const ue=I[j],ie=ge[j];return typeof ue=="string"&&typeof ie=="string"?O==="asc"?ue.localeCompare(ie):ie.localeCompare(ue):O==="asc"?ue-ie:ie-ue}):[],[r?.topPages,j,O]),Te=l.useMemo(()=>r?.aiReferrals?[...r.aiReferrals].sort((I,ge)=>{const ue=I[F],ie=ge[F];return typeof ue=="string"&&typeof ie=="string"?$==="asc"?ue.localeCompare(ie):ie.localeCompare(ue):$==="asc"?ue-ie:ie-ue}):[],[r?.aiReferrals,F,$]),Me=l.useMemo(()=>r?.aiReferralLandingPages?[...r.aiReferralLandingPages].sort((I,ge)=>{const ue=I[_],ie=ge[_];return typeof ue=="string"&&typeof ie=="string"?B==="asc"?ue.localeCompare(ie):ie.localeCompare(ue):B==="asc"?ue-ie:ie-ue}):[],[r?.aiReferralLandingPages,_,B]),Se=sn({rows:Me,getSearchText:td,pageSize:sd}),ct=Se.totalRows>0?`${Se.totalRows.toLocaleString()} ${Se.hasQuery?Se.totalRows===1?"match":"matches":Se.totalRows===1?"row":"rows"}`:Se.hasQuery&&(r?.aiReferralLandingPages.length??0)>0?"0 matches":"No landing-page rows";function Xe(I){Se.setPage(1),_===I?oe(ge=>ge==="desc"?"asc":"desc"):(w(I),oe("desc"))}const _e=l.useMemo(()=>r?.socialReferrals?[...r.socialReferrals].sort((I,ge)=>{const ue=I[se],ie=ge[se];return typeof ue=="string"&&typeof ie=="string"?C==="asc"?ue.localeCompare(ie):ie.localeCompare(ue):C==="asc"?ue-ie:ie-ue}):[],[r?.socialReferrals,se,C]),{socialChartData:X,socialChartSources:Pe,socialOtherCount:Ie}=l.useMemo(()=>{const I=Xc(K);return{socialChartData:I.data,socialChartSources:I.sources,socialOtherCount:I.otherCount}},[K]),{chartData:ht,chartSources:L,dateRange:ve}=l.useMemo(()=>{const I=Zc(ee,pe);return{chartData:I.data,chartSources:I.sources,dateRange:I.dateRange}},[ee,pe]);if(c&&!n)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!n?.connected)return H()?e.jsx(te,{className:"p-5",children:e.jsx("div",{className:"text-sm text-secondary",children:"No Google Analytics 4 property connected yet."})}):e.jsx(id,{projectName:t,onConnected:()=>{(async()=>(await ze(s,"ga"),await G({current:!1})))()}});const De=r?.organicSharePctDisplay??"0%",Rt=r?.channelBreakdown?.organic.sharePctDisplay??De,Re=r?.channelBreakdown?.organic.sessions??r?.totalOrganicSessions??0,Yt=r?.aiSessionsDeduped??0,dt=r?.channelBreakdown?.ai.sessions??r?.aiSessionsBySession??0,Be=r?.channelBreakdown?.ai.sharePctDisplay??r?.aiSharePctBySessionDisplay??"0%",ut=r?.paidAiSessionsBySession??0,qt=r?.paidAiSharePctBySessionDisplay??"0%",Nt=r?new Set(r.aiReferrals.map(I=>I.source.toLowerCase())).size:0,xt=Te[0]??null,Ze=r?.totalDirectSessions??0,Ot=r?.directSharePctDisplay??"0%",S=r?.channelBreakdown?.direct.sessions??Ze,re=r?.channelBreakdown?.direct.sharePctDisplay??Ot,he=r?.channelBreakdown?.other.sessions??r?.otherSessions??0,it=r?.channelBreakdown?.other.sharePctDisplay??r?.otherSharePctDisplay??"0%",$e=r?.socialSessions??0,Jt=r?.socialSharePctDisplay??"0%",rs=r?.channelBreakdown?.social.sessions??$e,is=r?.channelBreakdown?.social.sharePctDisplay??Jt,pt=r?new Set(r.socialReferrals.map(I=>I.source.toLowerCase())).size:0,Ye=_e[0]??null;return e.jsxs(e.Fragment,{children:[g&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative",children:g}),R&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-positive-900/20 border border-positive-800/60 text-sm text-positive",children:R}),e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-positive-500"}),e.jsxs("span",{className:"text-xs text-secondary",children:["Property ",e.jsx("span",{className:"text-neutral",children:n.propertyId}),n.clientEmail&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"text-muted",children:n.clientEmail})]})]})]}),!H()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(A,{variant:"outline",size:"sm",disabled:o,onClick:ye(Q),children:[e.jsx(tn,{className:`w-3.5 h-3.5 mr-1.5 ${o?"animate-spin":""}`}),o?"Syncing…":"Sync"]}),e.jsxs(A,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:p,onClick:ye(T),children:[e.jsx(Tc,{className:"w-3.5 h-3.5 mr-1.5"}),"Disconnect"]})]})]}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4 flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Traffic Overview"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Site Traffic",e.jsx(Ke,{text:`Aggregated traffic metrics from Google Analytics 4. Sessions and users are summed across the selected period.${r?.periodStart&&r?.periodEnd?` Data available: ${new Date(r.periodStart+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})} – ${new Date(r.periodEnd+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}.`:""} Organic sessions are Google organic search sessions specifically.`})]})]}),e.jsx("div",{className:"segmented",role:"group","aria-label":"Traffic time period",children:ed.map(I=>e.jsx("button",{type:"button","aria-pressed":me===I,className:`segmented-option ${me===I?"segmented-option-active":""}`,onClick:()=>N(I),children:I==="all"?"All":I},I))})]}),r?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(Jn,{value:Nn(r.totalSessions),label:"Total Sessions",subtitle:r.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(Jn,{value:Nn(r.totalOrganicSessions),label:"Organic Sessions",subtitle:`${De} of total`,tone:"positive"}),e.jsx(Jn,{value:Nn(r.totalUsers),label:"Total Users",subtitle:r.totalUsers.toLocaleString(),tone:"neutral"})]}):e.jsxs("div",{className:"surface-card rounded-lg p-6 text-center border border-default",children:[e.jsx("p",{className:"text-sm text-secondary mb-3",children:"No traffic data yet."}),!H()&&e.jsxs(A,{variant:"outline",size:"sm",disabled:o,onClick:ye(Q),children:[e.jsx(tn,{className:`w-3.5 h-3.5 mr-1.5 ${o?"animate-spin":""}`}),"Sync from GA4"]})]})]}),r&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Traffic Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Traffic by channel",e.jsx(Ke,{text:"Decomposes GA4 sessions into five disjoint channels — known AI referrers first, then organic search, social, direct, and other channels. Known AI includes paid and organic AI referrals; paid rows are labeled in the source table below. Known AI referrers are removed from their native GA4 channel before the residual Other bucket is computed."})]})]}),ve&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(ve.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(ve.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),ht.length>0&&e.jsxs(te,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:L.length>0?"AI vs. total sessions":"All sessions (baseline)"}),L.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),L.length===0&&e.jsx("p",{className:"text-xs text-muted",children:"No AI referrals detected yet"})]}),e.jsx("div",{className:"h-64",children:e.jsx(Rs,{width:"100%",height:"100%",children:e.jsxs(Ls,{data:ht,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Is,{dataKey:"date",tick:vt,tickLine:!1,axisLine:{stroke:Wt},tickFormatter:fa}),e.jsx(Ds,{tick:vt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Es,{...ps,labelFormatter:Dn,formatter:(I,ge)=>{const ue=typeof I=="number"?I.toLocaleString():String(I??0),ie=String(ge??"");return ie==="_totalSessions"?[ue,"Total Sessions"]:ie==="_organicSessions"?[ue,"Organic Sessions"]:[ue,ie]}}),e.jsx(ai,{wrapperStyle:{fontSize:11,color:at.text},formatter:I=>I==="_totalSessions"?"Total Sessions":I==="_organicSessions"?"Organic Sessions":I}),e.jsx(Ns,{type:"monotone",dataKey:"_totalSessions",stroke:at.textFaint,fill:at.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),L.map((I,ge)=>e.jsx(Ns,{type:"monotone",dataKey:I,stackId:"ai",stroke:ts[ge%ts.length],fill:ts[ge%ts.length],fillOpacity:.4,strokeWidth:1.5},I))]})})})]}),e.jsxs(te,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Summary"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Channel breakdown"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(At,{label:"Organic",value:Rt,hint:`${Re.toLocaleString()} sessions`,tone:"positive",tooltip:"Sessions from Google organic search (sessionDefaultChannelGrouping = 'Organic Search'), after known AI referrers are removed for a disjoint channel breakdown."}),e.jsx(At,{label:"Social",value:is,hint:`${rs.toLocaleString()} sessions`,tone:"neutral",tooltip:"Sessions from social platforms (sessionDefaultChannelGrouping = 'Organic Social' or 'Paid Social'), after known AI referrers are removed for a disjoint channel breakdown."}),e.jsx(At,{label:"Direct",value:re,hint:`${S.toLocaleString()} sessions`,tone:"neutral",tooltip:"Sessions with no source — bookmarks, typed URLs, untagged email, in-app browsers, and AI-driven traffic whose referrer header was stripped. Known AI referrers are removed if GA4 classified them as Direct."}),e.jsx(At,{label:"Known AI referrers (lower bound)",value:Be,hint:ut>0?`${dt.toLocaleString()} sessions · ${ut.toLocaleString()} paid`:`${dt.toLocaleString()} sessions`,tone:"positive",tooltip:"Sessions whose current sessionSource matched a known AI engine (e.g. chatgpt.com, claude.ai, gemini.google.com). Paid AI is inferred from paid/cpc/sponsored UTM values or GA4 paid channel groups. Untagged ad clicks with no referrer still fall under Direct because GA4 has no paid evidence for them."}),e.jsx(At,{label:"Other channels",value:it,hint:`${he.toLocaleString()} sessions`,tone:"neutral",tooltip:"Remaining GA4 session default channel groups after Known AI, Organic Search, Organic/Paid Social, and Direct are accounted for. This is a residual bucket, not a single source. It can include Referral, Email, Paid Search, Display, Cross-network, Shopping, Video, Affiliates, SMS, Mobile Push Notifications, Paid Other, and unclassified traffic."})]}),xt&&e.jsxs("div",{className:"mt-4 rounded-lg border border-positive-800/40 bg-positive-500/6 px-4 py-3 text-sm text-positive-100",children:["Top AI referrer: ",e.jsx("span",{className:"font-medium",children:xt.source})," via ",xt.medium,", accounting for ",xt.sessions.toLocaleString()," sessions.",ut>0&&e.jsxs("span",{children:[" Paid AI: ",ut.toLocaleString()," sessions (",qt,")."]})]})]}),e.jsxs(te,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Detail"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Known AI referrers by source"})]}),e.jsx("p",{className:"text-xs text-muted",children:r.aiReferrals.length>0?`${Nt} unique sources, ${r.aiReferrals.length} rows`:"No source rows"})]}),r.aiReferrals.length>0?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(mt,{label:"Source",sortKey:"source",current:F,dir:$,onSort:ce,align:"left"}),e.jsx(mt,{label:"Medium",sortKey:"medium",current:F,dir:$,onSort:ce,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Class"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(mt,{label:"Sessions",sortKey:"sessions",current:F,dir:$,onSort:ce,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:Te.map(I=>e.jsx(ld,{referral:I,totalSessions:Yt},`${I.source}:${I.medium}:${I.sourceDimension}`))})]})}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No AI referrer sessions detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"AI engines that preserve a referrer (Perplexity, copy/paste from ChatGPT, etc.) will appear here. Most AI traffic strips the referrer — see the Direct cell above for the upper bound."})]})]}),e.jsxs(te,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Detail"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Known AI referrers by landing page"})]}),e.jsx("p",{className:"text-xs text-muted",children:ct})]}),r.aiReferralLandingPages.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Ss,{value:Se.query,onChange:Se.setQuery,label:"Filter landing page URLs or query parameters",placeholder:"Filter URL or query parameters",className:"mb-4 max-w-md"}),Se.totalRows>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(mt,{label:"Landing Page",sortKey:"landingPage",current:_,dir:B,onSort:Xe,align:"left"}),e.jsx(mt,{label:"Source",sortKey:"source",current:_,dir:B,onSort:Xe,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(mt,{label:"Sessions",sortKey:"sessions",current:_,dir:B,onSort:Xe,align:"right"})]})}),e.jsx("tbody",{children:Se.rows.map(I=>e.jsx(cd,{row:I},`${I.landingPage}:${I.source}:${I.medium}:${I.sourceDimension}`))})]})}),e.jsx(gs,{page:Se.page,pageSize:Se.pageSize,visibleRows:Se.rows.length,totalRows:Se.totalRows,onPageChange:Se.setPage,itemLabel:Se.hasQuery?"matches":"rows"})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary",children:"No landing pages match this filter"}),e.jsx("button",{type:"button",onClick:()=>Se.setQuery(""),className:"mt-2 text-xs text-link hover:underline focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",children:"Clear filter"})]})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No AI landing pages detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"Known-AI landing pages appear after a GA4 sync records visits from AI referrers."})]})]})]})]}),r&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Social Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Social Media Traffic",e.jsx(Ke,{text:"Tracks sessions classified as social traffic by GA4's default channel grouping (Organic Social and Paid Social). Google maintains the source-to-channel mapping."})]})]}),X.length>0&&e.jsxs(te,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social sessions over time"})]}),Ie>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",Pe.length-1," sources · ",Ie," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(Rs,{width:"100%",height:"100%",children:e.jsxs(Ls,{data:X,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Is,{dataKey:"date",tick:vt,tickLine:!1,axisLine:{stroke:Wt},tickFormatter:fa}),e.jsx(Ds,{tick:vt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Es,{...ps,labelFormatter:Dn,formatter:(I,ge)=>{const ue=typeof I=="number"?I.toLocaleString():String(I??0),ie=String(ge??"");if(ie===Cs)return[ue,"Total Social"];if(ie===Ms){const Ee=`Other (${Ie} source${Ie===1?"":"s"})`;return[ue,Ee]}return[ue,ks(ie)]}}),e.jsx(Ns,{type:"monotone",dataKey:Cs,stroke:pi,fill:at.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),Pe.map((I,ge)=>{const ie=I===Ms?ya:ts[ge%ts.length];return e.jsx(Ns,{type:"monotone",dataKey:I,stackId:"social",stroke:ie,fill:ie,fillOpacity:.4,strokeWidth:1.5},I)})]})})}),e.jsx(ud,{sources:Pe,otherCount:Ie})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.5fr)]",children:[e.jsxs(te,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Summary"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social media visits"})]}),r.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(At,{label:"Social Sessions",value:Nn($e),hint:`${$e.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(At,{label:"Share of Traffic",value:Jt,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(At,{label:"Platforms",value:String(pt),hint:`${r.socialReferrals.length} source rows`,tone:"neutral",tooltip:"Number of distinct social media platforms detected. Each unique source/medium combination counts as one source row."})]}),Ye&&e.jsxs("div",{className:"mt-4 rounded-lg border border-info-800/40 bg-info-500/6 px-4 py-3 text-sm text-info-100",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-info-300/70 mb-1",children:"Top social source"}),e.jsx("p",{className:"font-medium truncate",title:`${Ye.source} via ${Ye.medium}`,children:xi(ks(Ye.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:Ye.medium,children:["via ",ks(Ye.medium)," · ",Ye.sessions.toLocaleString()," sessions"]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(At,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(At,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(At,{label:"Platforms",value:"0",hint:"known platforms",tone:"neutral",tooltip:"Number of distinct social media platforms detected."})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3 text-sm text-secondary",children:[e.jsx("p",{className:"mb-1.5 text-neutral",children:"Monitoring social media traffic via GA4 channel grouping"}),e.jsx("p",{className:"text-xs text-muted",children:"Sessions classified as Organic Social or Paid Social by GA4 will appear here. Google maintains the source-to-channel mapping, which includes Facebook, Instagram, X/Twitter, LinkedIn, Reddit, Pinterest, Snapchat, and other platforms."})]})]})]}),e.jsxs(te,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Breakdown"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Source / medium"})]}),e.jsx("p",{className:"text-xs text-muted",children:r.socialReferrals.length>0?_e.length>Qs&&!y?`Top ${Qs} of ${_e.length}`:`${_e.length} rows`:"No source rows"})]}),r.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm table-fixed",children:[e.jsxs("colgroup",{children:[e.jsx("col",{className:"w-[32%]"}),e.jsx("col",{className:"w-[22%]"}),e.jsx("col",{className:"w-[12%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[12%]"})]}),e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(mt,{label:"Source",sortKey:"source",current:se,dir:C,onSort:Ae,align:"left"}),e.jsx(mt,{label:"Medium",sortKey:"medium",current:se,dir:C,onSort:Ae,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(mt,{label:"Sessions",sortKey:"sessions",current:se,dir:C,onSort:Ae,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(mt,{label:"Users",sortKey:"users",current:se,dir:C,onSort:Ae,align:"right"})]})}),e.jsx("tbody",{children:(y?_e:_e.slice(0,Qs)).map(I=>e.jsx(dd,{referral:I,totalSessions:$e},`${I.source}:${I.medium}:${I.channelGroup}`))})]})}),_e.length>Qs&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>Y(I=>!I),className:"rounded-md border border-base px-3 py-1.5 text-xs text-secondary transition-colors hover:border-strong hover:text-strong",children:y?`Show top ${Qs}`:`Show all ${_e.length} sources`})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No social media sessions detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"When visitors arrive from Facebook, X/Twitter, LinkedIn, or other social platforms, their sessions will be broken down here by source and medium."})]})]})]})]})]}),r&&r.topPages.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Page Performance"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Top Landing Pages",e.jsx(Ke,{text:"Landing pages ranked by session volume. Click column headers to sort. Organic % shows the share of sessions coming from Google organic search."})]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(mt,{label:"Landing Page",sortKey:"landingPage",current:j,dir:O,onSort:ne,align:"left"}),e.jsx(mt,{label:"Sessions",sortKey:"sessions",current:j,dir:O,onSort:ne,align:"right"}),e.jsx(mt,{label:"Organic",sortKey:"organicSessions",current:j,dir:O,onSort:ne,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"})]})}),e.jsx("tbody",{children:Fe.map(I=>e.jsx(od,{page:I},I.landingPage))})]})})]})]}),e.jsxs("div",{className:"mt-6 flex items-center justify-between text-xs text-muted",children:[e.jsx("span",{children:r?.lastSyncedAt?`Last synced ${gi(r.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:r?`${r.topPages.length} pages · ${r.aiReferrals.length} AI rows · ${r.socialReferrals.length} social rows`:""})]})]})}function id({projectName:t,onConnected:s}){const[n,a]=l.useState(""),[r,i]=l.useState(null),[c,u]=l.useState(null),[o,h]=l.useState(!1),[p,m]=l.useState(null),g=l.useRef(null),k=l.useCallback(v=>{const j=v.target.files?.[0];if(!j)return;m(null),i(j.name);const D=new FileReader;D.onload=()=>{const O=D.result;try{const E=JSON.parse(O);if(!E.client_email||!E.private_key){m("JSON file is missing required fields: client_email and private_key. Make sure you downloaded a service account key (not an OAuth client)."),u(null);return}u(O)}catch{m("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),u(null)}},D.onerror=()=>{m("Failed to read file."),u(null)},D.readAsText(j)},[]);async function R(){if(m(null),!n.trim()){m("Property ID is required.");return}if(!c){m("Please upload a service account key file.");return}h(!0);try{await so(t,{propertyId:n.trim(),keyJson:c});try{await Gr(t)}catch{}s()}catch(v){m(v instanceof Error?v.message:"Failed to connect GA4")}finally{h(!1)}}return e.jsxs(te,{className:"surface-card p-6",children:[e.jsx("h3",{className:"text-base font-semibold text-primary mb-1",children:"Connect Google Analytics 4"}),e.jsx("p",{className:"text-sm text-secondary mb-5",children:"Connect a GA4 property to see traffic data for this project. You'll need a service account key file from Google Cloud Console."}),p&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative",children:p}),e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{htmlFor:"ga4-property-id",className:"block text-xs font-medium text-secondary mb-1.5",children:"GA4 Property ID"}),e.jsx("input",{id:"ga4-property-id",type:"text",placeholder:"e.g. 123456789",value:n,onChange:v=>a(v.target.value),className:"w-full rounded-lg bg-bg-elevated/60 border border-default px-3 py-2 text-sm text-strong placeholder-mono-600 focus:outline-none focus:ring-1 focus:ring-mono-600"}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:"Find this in GA4 → Admin → Property Settings. It's a numeric ID, not the Measurement ID (G-XXXXXX)."})]}),e.jsxs("div",{className:"mb-5",children:[e.jsx("label",{className:"block text-xs font-medium text-secondary mb-1.5",children:"Service Account Key File"}),e.jsx("input",{ref:g,type:"file",accept:".json,application/json",onChange:k,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>g.current?.click(),className:"flex items-center gap-2 w-full rounded-lg bg-bg-elevated/60 border border-default border-dashed px-4 py-3 text-sm text-secondary hover:border-mono-600 hover:text-neutral transition-colors cursor-pointer",children:[e.jsx(Rc,{className:"w-4 h-4 shrink-0"}),r?e.jsx("span",{className:"text-strong truncate",children:r}):e.jsx("span",{children:"Upload .json key file"})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Download from Google Cloud Console → IAM & Admin → Service Accounts → Keys → Add Key → JSON. The service account must have ",e.jsx("span",{className:"text-secondary",children:"Viewer"})," access on the GA4 property."]})]}),e.jsx(A,{variant:"default",size:"sm",disabled:o||!n.trim()||!c,onClick:ye(R),children:o?"Connecting & syncing…":"Connect GA4"})]})}function mt({label:t,sortKey:s,current:n,dir:a,onSort:r,align:i}){const c=n===s;return e.jsx("th",{className:`py-1 ${i==="right"?"text-right":"text-left"}`,children:e.jsxs("button",{type:"button",className:"font-medium cursor-pointer select-none hover:text-neutral transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-400 rounded",onClick:()=>r(s),"aria-label":`Sort by ${t}${c?` (currently ${a==="asc"?"ascending":"descending"})`:""}`,children:[t,c&&e.jsx("span",{className:"ml-0.5",children:a==="asc"?"↑":"↓"})]})})}const fi={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function Jn({value:t,label:s,subtitle:n,tone:a}){return e.jsxs("div",{className:"rounded-lg bg-surface border border-default px-5 py-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:s}),e.jsx("p",{className:`text-2xl font-bold tabular-nums ${fi[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function At({value:t,label:s,hint:n,tone:a,tooltip:r}){return e.jsxs("div",{className:"rounded-lg border border-default bg-bg/40 px-4 py-3 flex flex-col",children:[e.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1 flex items-center gap-1",children:[s,r&&e.jsx(Ke,{text:r})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${fi[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function od({page:t}){const s=t.sessions>0?(t.organicSessions/t.sessions*100).toFixed(1):"0.0";return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 text-neutral max-w-[400px] truncate",title:t.landingPage,children:t.landingPage}),e.jsx("td",{className:"py-1.5 text-right text-strong tabular-nums",children:t.sessions.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.organicSessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[s,"%"]})]})}const bi={session:"Session",first_user:"First Visit",manual_utm:"UTM"},ji={session:"Detected via GA4 sessionSource (referrer or utm_source for this session)",first_user:"Detected via GA4 firstUserSource (referrer from the user's first-ever visit)",manual_utm:"Detected via GA4 sessionManualSource (explicit utm_source parameter for the session)"};function ld({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=bi[t.sourceDimension]??t.sourceDimension,r=ji[t.sourceDimension]??"",i=t.trafficClass==="paid"?"Paid":"Organic",c=t.trafficClass==="paid"?"Paid AI traffic inferred from paid/cpc/sponsored UTM values or a GA4 paid channel group":"AI traffic without a paid attribution signal";return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 text-strong max-w-[220px] truncate",title:t.source,children:t.source}),e.jsx("td",{className:"py-1.5 text-muted max-w-[180px] truncate",title:t.medium,children:t.medium}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:`inline-block text-[10px] px-1.5 py-0.5 rounded-full border ${t.trafficClass==="paid"?"border-caution-700 text-caution-300":"border-strong text-secondary"}`,title:c,children:i})}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:r,children:a})}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[n,"%"]})]})}function cd({row:t}){const s=bi[t.sourceDimension]??t.sourceDimension,n=ji[t.sourceDimension]??"";return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"max-w-[400px] py-1.5 text-neutral",children:e.jsx(Js,{value:t.landingPage,className:"whitespace-nowrap"})}),e.jsx("td",{className:"py-1.5 text-strong max-w-[220px] truncate",title:t.source,children:t.source}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:n,children:s})}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.sessions.toLocaleString()})]})}function dd({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=t.channelGroup==="Paid Social"?"Paid":"Organic",r=ks(t.source),i=ks(t.medium);return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 pr-3 text-strong truncate",title:t.source,children:r}),e.jsx("td",{className:"py-1.5 pr-3 text-muted truncate",title:t.medium,children:i}),e.jsx("td",{className:"py-1.5 pr-3",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:`GA4 channel group: ${t.channelGroup}`,children:a})}),e.jsx("td",{className:"py-1.5 text-right text-info-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[n,"%"]}),e.jsx("td",{className:"py-1.5 text-right text-strong tabular-nums",children:t.users.toLocaleString()})]})}function ud({sources:t,otherCount:s}){const n=[{key:Cs,color:pi,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const r=t[a];if(r===Ms)n.push({key:Ms,color:ya,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const i=ks(r);n.push({key:r,color:ts[a%ts.length]??ya,label:xi(i,32),tooltip:i})}}return e.jsx("div",{className:"mt-3 flex flex-wrap gap-x-4 gap-y-1.5 text-[11px] text-secondary",children:n.map(a=>e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 max-w-[260px]",title:a.tooltip,children:[e.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-sm shrink-0",style:{backgroundColor:a.color},"aria-hidden":"true"}),e.jsx("span",{className:"truncate",children:a.label})]},a.key))})}function md(t){const s=t.details;if(t.code!=="FORBIDDEN"||!s||s.reason!=="gsc-api-disabled")return null;const n=typeof s.projectNumber=="string"?s.projectNumber:void 0;return{title:"Enable the Search Console API",message:`Your Google Cloud project${n?` (${n})`:""} hasn't enabled the Search Console API. Enable the Search Console API and the Indexing API, wait ~2–5 minutes, then retry.`,enableUrl:typeof s.enableUrl=="string"?s.enableUrl:void 0,indexingApiUrl:typeof s.indexingApiUrl=="string"?s.indexingApiUrl:void 0,projectNumber:n}}const hd=["7d","30d","90d","all"],wn=500,Zt=25,xd="canonry:google-oauth-complete";function xr(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function pr(t){const s=Number(t.errors??0),n=Number(t.warnings??0);return[s>0?`${s} error${s===1?"":"s"}`:"",n>0?`${n} warning${n===1?"":"s"}`:""].filter(Boolean).join(" · ")}function gr(t){return t.isPending?"Processing":Number(t.errors??0)>0?"Errors":Number(t.warnings??0)>0?"Warnings":"Success"}function pd({projectName:t,refreshNonce:s}){const n=as(),[a,r]=l.useState(!1),[i,c]=l.useState([]),[u,o]=l.useState([]),[h,p]=l.useState([]),[m,g]=l.useState(null),[k,R]=l.useState([]),[v,j]=l.useState([]),[D,O]=l.useState(null),[E,F]=l.useState(""),[x,$]=l.useState(""),[M,se]=l.useState("30"),[de,C]=l.useState(!1),[b,_]=l.useState("30d"),[w,B]=l.useState({startDate:"",endDate:"",query:"",page:""}),[oe,ee]=l.useState(0),[U,pe]=l.useState(!1),[le,K]=l.useState(0),[q,y]=l.useState(!1),[Y,me]=l.useState(""),[N,G]=l.useState(!0),[Q,T]=l.useState(!1),[ne,ce]=l.useState(!1),[Ae,Fe]=l.useState(!1),[Te,Me]=l.useState(!1),[Se,ct]=l.useState(!1),[Xe,_e]=l.useState(!1),[X,Pe]=l.useState(null),[Ie,ht]=l.useState(!1),[L,ve]=l.useState(!1),[De,Rt]=l.useState(null),[Re,Yt]=l.useState(null),[dt,Be]=l.useState([]),[ut,qt]=l.useState(new Set),[Nt,xt]=l.useState({}),[Ze,Ot]=l.useState(new Set),[S,re]=l.useState(""),[he,it]=l.useState(null),[$e,Jt]=l.useState(""),[rs,is]=l.useState(!1),[pt,Ye]=l.useState(!1),[I,ge]=l.useState(!1),[ue,ie]=l.useState(!1),[Ee,Os]=l.useState("indexed"),[Ge,ot]=l.useState(null),Kt=!!(w.query.trim()||w.page.trim()||Ge),Lt=Ge!==null,cn=l.useMemo(()=>{if(!Ge)return h;const{key:d,dir:P}=Ge;return[...h].sort((z,J)=>{const je=d===hs.CTR?Number.isFinite(z.ctr)?z.ctr:0:z[d],we=d===hs.CTR?Number.isFinite(J.ctr)?J.ctr:0:J[d];return P==="asc"?je-we:we-je})},[h,Ge]),wt=sn({rows:cn,pageSize:Tt}),os=q?wt.rows:cn,Ft=sn({rows:(De??[]).filter(d=>d.path.toLowerCase().includes(S.trim().toLowerCase())),pageSize:Tt}),[gt,dn]=l.useState([]),[lt,He]=l.useState(null),[Ks,St]=l.useState(1),ft=l.useMemo(()=>{if(gt.length<2)return null;const d=gt[gt.length-1],P=gt[gt.length-2];return{indexed:d.indexed-P.indexed,notIndexed:d.notIndexed-P.notIndexed}},[gt]);l.useEffect(()=>{St(1)},[X,Ee,lt]);const It=l.useMemo(()=>lt?(X?.reasonGroups??[]).find(d=>d.reason===lt):void 0,[X,lt]),Ve=l.useMemo(()=>X?Ee==="indexed"?X.indexed:Ee==="deindexed"?X.deindexed:Ee==="notIndexed"?lt?It?.urls??[]:(X.reasonGroups??[]).length===0?X.notIndexed:[]:[]:[],[X,Ee,lt,It]),Kn=Math.max(1,Math.ceil(Ve.length/Zt)),Fs=Math.min(Math.max(1,Ks),Kn),et=(Fs-1)*Zt,un=l.useMemo(()=>X?.indexed.slice(et,et+Zt)??[],[X,et]),mn=l.useMemo(()=>X?.notIndexed.slice(et,et+Zt)??[],[X,et]),Fn=l.useMemo(()=>X?.deindexed.slice(et,et+Zt)??[],[X,et]),_n=l.useMemo(()=>(It?.urls??[]).slice(et,et+Zt),[It,et]),[ls,bs]=l.useState(!1),[hn,be]=l.useState(null),[Ct,f]=l.useState(null),[W,ae]=l.useState(null);function Le(d,P){const z=gc(d),J=md(z);J?(f(J),be(null)):(f(null),be(z.message||P))}const qe=i.find(d=>d.connectionType==="gsc"),_t=(qe?.scopes??[]).includes("https://www.googleapis.com/auth/webmasters"),Ue=dt.length>0?dt:(De??[]).map(d=>d.path),xn=Ue.filter(d=>De?.some(P=>P.path===d&&P.isSitemapsIndex)).length,pn=xn===1?"Resubmit sitemap index":xn>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",Un=h.length>0||k.length>0||v.length>0,_s=no(),Bn=ao();async function Ba(d,P=!1){if(!d){o([]),F("");return}ce(!0);try{const{sites:z}=await n.fetchQuery({...bo({client:V,path:{name:t}}),staleTime:P?0:We});o(z),F(d.propertyId??z[0]?.siteUrl??""),f(null)}catch(z){o([]),Le(z,"Failed to load Search Console properties")}finally{ce(!1)}}async function Us(d){Me(!0);const P=d??oe;try{const z=Kt?wn:Tt,J=Kt?0:P,je={limit:String(z)};w.startDate&&(je.startDate=w.startDate),w.endDate&&(je.endDate=w.endDate),w.query&&(je.query=w.query),w.page&&(je.page=w.page),J>0&&(je.offset=String(J)),b&&b!=="all"&&!w.startDate&&(je.window=b);const we=await n.fetchQuery({...io({client:V,path:{name:t},query:je}),staleTime:We}),Ce=we.rows;Kt?(pe(!1),p(Ce),K(Ce.length),y(!0)):(pe(J+Ce.length<we.totalMatching),p(Ce),K(0),y(!1))}catch(z){p([]),pe(!1),K(0),be(z instanceof Error?z.message:"Failed to load GSC performance data")}finally{Me(!1)}}async function Gn(){try{const d={};w.startDate&&(d.startDate=w.startDate),w.endDate&&(d.endDate=w.endDate),b&&b!=="all"&&!w.startDate&&(d.window=b);const P=await n.fetchQuery({...oo({client:V,path:{name:t},query:d}),staleTime:We});g(P)}catch{g(null)}}async function gn(d=!1){ct(!0);try{const P=Y.trim()||void 0,z={limit:"20"};P&&(z.url=P);const[J,je]=await Promise.all([n.fetchQuery({...go({client:V,path:{name:t},query:z}),staleTime:d?0:We}),n.fetchQuery({...fo({client:V,path:{name:t}}),staleTime:d?0:We})]);R(J),j(je)}catch(P){R([]),j([]),be(P instanceof Error?P.message:"Failed to load GSC inspection history")}finally{ct(!1)}}async function Ga(d=!1){ht(!0);try{const[P,z]=await Promise.all([n.fetchQuery({...zr({client:V,path:{name:t}}),staleTime:d?0:We}),n.fetchQuery({...uo({client:V,path:{name:t}}),staleTime:d?0:We}).catch(()=>[])]);Pe(P),dn(z)}catch(P){Pe(null),dn([]),be(P instanceof Error?P.message:"Failed to load coverage data")}finally{ht(!1)}}async function Qa(d){bs(!0),be(null);try{const P=await Za(t,{urls:d}),{succeeded:z,failed:J,total:je}=P.summary;xe({title:"Indexing requested",detail:J===0?`${z} URL${z!==1?"s":""} submitted for indexing.`:`${z}/${je} submitted successfully, ${J} failed.`,tone:J===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(P){be(P instanceof Error?P.message:"Failed to request indexing")}finally{bs(!1)}}async function Pi(){bs(!0),be(null);try{const d=await Za(t,{urls:[],allUnindexed:!0}),{succeeded:P,failed:z,total:J}=d.summary;xe({title:"Indexing requested",detail:z===0?`${P} unindexed URL${P!==1?"s":""} submitted for indexing.`:`${P}/${J} submitted successfully, ${z} failed.`,tone:z===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(d){be(d instanceof Error?d.message:"Failed to request indexing")}finally{bs(!1)}}async function Qn(){ve(!0),be(null);try{const d=await zn(t);n.setQueryData(mo({client:V,path:{name:t}}),d),Rt(d.sitemaps),Yt(d.summary),Be(d.preferredSubmissionUrls),qt(new Set),xt({}),d.sitemaps.length===0&&ae("No sitemaps found in this GSC property. Submit one here to start Google processing it.")}catch(d){be(d instanceof Error?d.message:"Failed to list sitemaps")}finally{ve(!1)}}async function Ri(d){const P=ut.has(d);if(qt(z=>{const J=new Set(z);return P?J.delete(d):J.add(d),J}),!(P||Nt[d])){Ot(z=>new Set(z).add(d));try{const z=await zn(t,d);xt(J=>({...J,[d]:z.sitemaps}))}catch(z){be(z instanceof Error?z.message:"Failed to load sitemap files")}finally{Ot(z=>{const J=new Set(z);return J.delete(d),J})}}}async function js(d){if(!_t||d.length===0)return;const P=[...new Set(d)];Ye(!0),be(null),it({completed:0,total:P.length});let z=0,J=0,je=0,we=null;try{for(let Oe=0;Oe<P.length;Oe+=50){const fe=P.slice(Oe,Oe+50);try{const tt=await ho(t,fe);z+=tt.summary.accepted,J+=tt.summary.failed,je+=fe.length,it({completed:je,total:P.length})}catch(tt){je+=fe.length;const kt=fe.length,cs=P.length-je,ys=tt instanceof Error?tt.message:"The batch request failed",Bs=`${z} accepted, ${J} failed, ${kt} unconfirmed, ${cs} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;we=`Sitemap submission stopped after a batch request failed. ${Bs} ${ys}`,be(we),xe({title:"Sitemap resubmission partially completed",detail:Bs,tone:"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"});return}}const Ce=P.length;xe({title:J===0?"Sitemap submitted to Google":"Some sitemap submissions need attention",detail:J===0?"Google accepted the sitemap submission/refetch request; indexing is not guaranteed.":`Google accepted ${z}/${Ce} sitemap submissions; ${J} failed. Indexing is not guaranteed.`,tone:J===0?"positive":"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"}),Jt("")}catch(Ce){be(Ce instanceof Error?Ce.message:"Failed to submit sitemap to Google")}finally{Ye(!1),it(null),await Qn(),we&&be(we)}}async function Li(){Ye(!0);const d=De??[];try{const P=d.filter(J=>J.isSitemapsIndex),z=[];for(let J=0;J<P.length;J+=4)(await Promise.all(P.slice(J,J+4).map(async we=>{const Ce=Nt[we.path];if(Ce)return Ce;const Oe=await zn(t,we.path);return xt(fe=>({...fe,[we.path]:Oe.sitemaps})),Oe.sitemaps}))).forEach((we,Ce)=>{z.push(...we.length>0?we.map(Oe=>Oe.path):[P[J+Ce].path])});await js([...d.filter(J=>!J.isSitemapsIndex).map(J=>J.path),...z])}catch(P){be(P instanceof Error?P.message:"Failed to load sitemap files"),Ye(!1)}}async function za(d){is(!0),be(null);try{await xo(t,"gsc",d),await ze(n,"google"),c(P=>P.map(z=>z.connectionType==="gsc"?{...z,sitemapUrl:d}:z)),xe({title:"Default sitemap updated",detail:d,tone:"positive",dedupeKey:`gsc:sitemap-default:${t}`,dedupeMode:"replace"})}catch(P){be(P instanceof Error?P.message:"Failed to set the default sitemap")}finally{is(!1)}}async function Ha(d){try{await Bn.mutateAsync({projectName:t,projectLabel:t,opts:d?{sitemapUrl:d}:void 0})}catch{}}async function Va(){G(!0),be(null);try{const[d,P]=await Promise.all([Qr().catch(()=>null),n.fetchQuery({...Ra({client:V,path:{name:t}}),staleTime:We}).catch(()=>[])]);r(!!d?.google?.configured),c(P);const z=P.find(J=>J.connectionType==="gsc");await Promise.all([Ba(z),Us(),Gn(),gn(),Ga(),z?.propertyId?Qn():Promise.resolve()])}finally{G(!1)}}l.useEffect(()=>{Va()},[t,s]),l.useEffect(()=>{ee(0),Us(0),Gn()},[b]);const Wa=l.useRef(!1);l.useEffect(()=>{if(!Wa.current){Wa.current=!0;return}ee(0),Us(0)},[Lt]);async function Ya(){if(!a){be("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}T(!0),be(null),ae(null);try{let d=function(tt){if(tt.source!==J||tt.origin!==je||!tt.data||typeof tt.data!="object")return;const kt=tt.data;kt.type!==xd||kt.connectionType!=="gsc"||fe(!0)};const{authUrl:P,redirectUri:z}=await co(t,"gsc");if(!P.startsWith("https://accounts.google.com/")){be("Unexpected OAuth redirect URL. Please try again.");return}const J=window.open(P,"_blank","width=600,height=700");if(!J){window.location.assign(P);return}const je=z?new URL(z).origin:window.location.origin;let we=!1,Ce=null;const Oe=()=>{Ce!==null&&window.clearInterval(Ce),window.removeEventListener("message",d)},fe=async tt=>{if(!we){we=!0,Oe(),ae(tt?"Google connected. Refreshing access…":"Refreshing Google connection…");try{await ze(n,"google"),await Va()}finally{ae(null)}}};window.addEventListener("message",d),ae("Finish the Google consent flow in the popup. This page will refresh automatically."),Ce=window.setInterval(()=>{J.closed&&fe(!1)},1e3)}catch(d){be(d instanceof Error?d.message:"Failed to start OAuth flow")}finally{T(!1)}}async function Ii(){be(null),ae(null);try{await lo(t,"gsc"),await ze(n,"google"),c(d=>d.filter(P=>P.connectionType!=="gsc")),o([]),F("")}catch(d){be(d instanceof Error?d.message:"Failed to disconnect")}}async function Di(){if(E){Fe(!0),be(null);try{await jo(t,"gsc",E),await ze(n,"google"),c(d=>d.map(P=>P.connectionType==="gsc"?{...P,propertyId:E}:P)),xe({title:"GSC property updated",detail:`${t} is now linked to ${E}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(d){be(d instanceof Error?d.message:"Failed to save GSC property")}finally{Fe(!1)}}}async function Ei(){be(null),ae(null);try{await _s.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(M,10)||void 0,full:de||void 0}}),await ze(n,"gsc")}catch{}}async function Ja(){if(x.trim()){_e(!0),be(null),ae(null);try{const d=await po(t,x.trim());await ze(n,"gsc"),O(d),$(""),await gn()}catch(d){be(d instanceof Error?d.message:"Failed to inspect URL")}finally{_e(!1)}}}return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search Console"}),e.jsx("h2",{children:"Google Search Console"})]})}),Ct&&e.jsx("div",{className:"mb-3 rounded-lg border border-caution-800/40 bg-caution-950/20 px-3 py-2.5 text-sm text-caution-200",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-caution-100",children:Ct.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:Ct.message}),(us(Ct.enableUrl)||us(Ct.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[us(Ct.enableUrl)&&e.jsx("a",{href:us(Ct.enableUrl),target:"_blank",rel:"noopener noreferrer",className:"font-medium text-caution-100 underline decoration-caution-500/50 underline-offset-2 hover:text-caution-50",children:"Enable Search Console API ↗"}),us(Ct.indexingApiUrl)&&e.jsx("a",{href:us(Ct.indexingApiUrl),target:"_blank",rel:"noopener noreferrer",className:"font-medium text-caution-100 underline decoration-caution-500/50 underline-offset-2 hover:text-caution-50",children:"Enable Indexing API ↗"})]})]}),e.jsx("button",{type:"button",className:"text-caution-400 hover:text-caution-200",onClick:()=>f(null),children:"×"})]})}),hn&&e.jsxs("div",{className:"mb-3 rounded-lg border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:[hn,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>be(null),children:"×"})]}),W&&e.jsxs("div",{className:"mb-3 rounded-lg border border-positive-800/40 bg-positive-950/20 px-3 py-2 text-sm text-positive",children:[W,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>ae(null),children:"×"})]}),N?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[qe?e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 px-1 text-xs text-muted",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-positive-500"}),e.jsx("span",{className:"text-neutral",children:"Authorized"})]}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsx("code",{className:"text-secondary",children:qe.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Last updated ",Dt(qe.updatedAt)]}),e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:ye(Ii),children:"Disconnect"})]}):e.jsxs(te,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(Z,{tone:a?"caution":"negative",children:a?"Ready to connect":"App credentials missing"})]}),e.jsxs("div",{className:"mt-3 rounded-lg border border-default bg-surface px-4 py-5",children:[e.jsx("p",{className:"text-sm text-neutral",children:a?"Generate a Google OAuth link for this project and have the client sign in with a Google account that already has access to the correct Search Console property.":"Set Google OAuth client credentials first. Once configured, you can generate a consent link for this project domain."}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[a?e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:Q,onClick:ye(Ya),children:Q?"Opening…":"Connect Google Search Console"}):e.jsx(A,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(zt,{to:"/settings",children:"Open Settings"})}),!a&&e.jsx("p",{className:"text-xs text-muted",children:"The same Google OAuth app credentials are shared across all projects."})]})]})]}),(qe||Un)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs(te,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Performance"}),e.jsx("h3",{children:"Search performance"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"segmented",role:"group","aria-label":"Performance time period",children:hd.map(d=>e.jsx("button",{type:"button","aria-pressed":b===d,className:`segmented-option ${b===d?"segmented-option-active":""}`,onClick:()=>{_(d),ee(0),wt.setPage(1)},children:d==="all"?"All":d},d))}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:Te,onClick:()=>{ee(0),wt.setPage(1),Us(0),Gn()},children:Te?"Loading…":"Apply filters"})]})]}),m&&m.daily.length>0&&(()=>{const d=m.daily,P=Math.max(...d.map(ke=>ke.impressions),1),{clicks:z,impressions:J,ctr:je}=m.totals,we=(je*100).toFixed(1),Ce=700,Oe=220,fe={top:12,bottom:36,left:48,right:12},tt=Ce-fe.left-fe.right,kt=Oe-fe.top-fe.bottom,cs=tt/d.length,ys=Math.max(Math.min(cs*.35,24),4),Bs=Math.max(ys*.15,1),Mi=ke=>{if(ke<=0)return 1;const Ut=Math.pow(10,Math.floor(Math.log10(ke))),bt=ke/Ut,Xt=bt<=1.5?1.5:bt<=3?3:bt<=5?5:10;return Math.ceil(Xt*Ut)},fn=4,bn=Math.ceil(Mi(P)/fn)*fn,qi=Array.from({length:fn+1},(ke,Ut)=>bn/fn*Ut),Oi=ke=>ke>=1e3?`${(ke/1e3).toFixed(ke>=1e4?0:1)}k`:String(ke);return e.jsxs("div",{className:"mt-3",children:[e.jsxs("div",{className:"flex items-center gap-5 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-sm bg-positive-500"}),e.jsxs("span",{className:"text-xs text-secondary",children:["Clicks ",e.jsx("span",{className:"text-strong tabular-nums font-medium",children:z.toLocaleString()})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-sm bg-chart-series-2"}),e.jsxs("span",{className:"text-xs text-secondary",children:["Impressions ",e.jsx("span",{className:"text-strong tabular-nums font-medium",children:J.toLocaleString()})]})]}),e.jsxs("span",{className:"text-xs text-muted",children:["CTR ",e.jsxs("span",{className:"text-caution-400 tabular-nums font-medium",children:[we,"%"]})]})]}),e.jsx("div",{className:"relative w-full",style:{aspectRatio:`${Ce} / ${Oe}`},children:e.jsxs("svg",{viewBox:`0 0 ${Ce} ${Oe}`,className:"h-full w-full",children:[qi.map((ke,Ut)=>{const bt=fe.top+kt-ke/bn*kt;return e.jsxs("g",{children:[e.jsx("line",{x1:fe.left,y1:bt,x2:Ce-fe.right,y2:bt,stroke:at.gridLine,strokeWidth:"1"}),e.jsx("text",{x:fe.left-6,y:bt+3.5,textAnchor:"end",fill:at.text,fontSize:"10",fontFamily:"inherit",children:Oi(ke)})]},`t-${Ut}`)}),d.map((ke,Ut)=>{const bt=fe.left+cs*Ut+cs/2,Xt=ke.impressions/bn*kt,jn=ke.clicks/bn*kt;return e.jsxs("g",{children:[e.jsx("title",{children:`${ke.date}
|
|
2
|
+
Clicks: ${ke.clicks}
|
|
3
|
+
Impressions: ${ke.impressions}
|
|
4
|
+
CTR: ${(ke.ctr*100).toFixed(1)}%`}),e.jsx("rect",{x:bt-ys-Bs/2,y:fe.top+kt-Xt,width:ys,height:Math.max(Xt,1),rx:2,fill:nt[1],opacity:.85}),e.jsx("rect",{x:bt+Bs/2,y:fe.top+kt-jn,width:ys,height:Math.max(jn,1),rx:2,fill:Ht.positiveDeep,opacity:.85})]},ke.date)}),(()=>{const ke=Math.min(d.length,7);return Array.from({length:ke},(Ut,bt)=>{const Xt=d.length===1?0:Math.round(bt/(ke-1)*(d.length-1)),jn=fe.left+cs*Xt+cs/2;return e.jsx("text",{x:jn,y:Oe-8,textAnchor:"middle",fill:at.textDim,fontSize:"10",fontFamily:"inherit",children:d[Xt].date.slice(5)},`xl-${Xt}`)})})()]})})]})})(),e.jsxs("div",{className:"mt-3 grid gap-2 lg:grid-cols-4",children:[e.jsx("input",{className:"rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"date","aria-label":"Start date",title:"Start date (inclusive). Leave blank to use the window above.",value:w.startDate,onChange:d=>B(P=>({...P,startDate:d.target.value}))}),e.jsx("input",{className:"rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"date","aria-label":"End date",title:"End date (inclusive).",value:w.endDate,onChange:d=>B(P=>({...P,endDate:d.target.value}))}),e.jsx(Ss,{value:w.query,onChange:d=>B(P=>({...P,query:d})),label:"Filter search queries",placeholder:"Contains query…"}),e.jsx(Ss,{value:w.page,onChange:d=>B(P=>({...P,page:d})),label:"Filter page URLs",placeholder:"Contains page URL…"})]}),e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Query and page filters match case-insensitive substrings. Click Apply filters to run. Filtering and sorting examine up to ",wn.toLocaleString()," matching rows while the table stays at ",Tt," rows per page."]}),h.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Date"}),e.jsx("th",{className:"text-left",children:"Query"}),e.jsx("th",{className:"text-left",children:"Page"}),Object.values(hs).map(d=>e.jsx("th",{className:"text-right","aria-sort":Ge?.key===d?Ge.dir==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"w-full cursor-pointer select-none text-right hover:text-strong focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-400 rounded px-1 -mx-1",onClick:()=>{wt.setPage(1),ot(P=>P?.key===d?P.dir==="desc"?{key:d,dir:"asc"}:null:{key:d,dir:"desc"})},children:[ro[d],Ge?.key===d?Ge.dir==="desc"?" ↓":" ↑":""]})},d))]})}),e.jsx("tbody",{children:os.map((d,P)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:d.date}),e.jsx("td",{className:"max-w-xs truncate text-strong",children:d.query}),e.jsx("td",{className:"max-w-xs text-secondary",children:e.jsx(Js,{value:d.page})}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:d.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:d.impressions.toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[(Number.isFinite(d.ctr)?d.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:d.position.toFixed(1)})]},`${d.date}:${d.query}:${d.page}:${P}`))})]})}),e.jsx(gs,{page:q?wt.page:Math.floor(oe/Tt)+1,pageSize:Tt,visibleRows:os.length,totalRows:q?le:void 0,hasNextPage:q?void 0:U,disabled:Te,itemLabel:q?"matches":"rows",onPageChange:d=>{if(q){wt.setPage(d);return}const P=(d-1)*Tt;ee(P),Us(P)}}),q&&le>=wn?e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Results are capped at ",wn.toLocaleString(),"; narrow the filters to search beyond this set."]}):null]}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No performance rows match the current filters yet."})]}),e.jsxs(te,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Coverage"}),e.jsx("h3",{children:"Index coverage"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[X&&X.notIndexed.length>0&&e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:ls,onClick:()=>{Pi()},children:ls?"Requesting…":`Request indexing (${X.notIndexed.length})`}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:Ie,onClick:()=>{Ga(!0)},children:Ie?"Loading…":"Reload saved coverage"})]})]}),X&&X.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const d=X.summary.indexed+X.summary.notIndexed,P=d>0?X.summary.indexed/d:0,z=d>0?X.summary.notIndexed/d:0,J=54,je=2*Math.PI*J,we=je*(1-P),Ce=je*z,Oe=je*P;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative h-48 w-48",children:[e.jsxs("svg",{viewBox:"0 0 128 128",className:"h-full w-full","aria-hidden":"true",children:[e.jsx("circle",{cx:"64",cy:"64",r:J,fill:"none",stroke:at.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:J,fill:"none",stroke:Ht.positiveDeep,strokeWidth:"14",strokeDasharray:je,strokeDashoffset:we,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),X.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:J,fill:"none",stroke:at.textFaint,strokeWidth:"14",strokeDasharray:`${Ce} ${je-Ce}`,strokeDashoffset:-Oe,transform:"rotate(-90 64 64)",style:{transition:"stroke-dasharray 0.6s ease, stroke-dashoffset 0.6s ease"}})]}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[e.jsxs("span",{className:"text-3xl font-bold tabular-nums text-primary",children:[(P*100).toFixed(0),"%"]}),e.jsx("span",{className:"text-xs uppercase tracking-widest text-muted mt-0.5",children:"Indexed"})]})]}),e.jsxs("div",{className:"mt-4 flex items-center justify-center gap-8",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-positive-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:X.summary.indexed.toLocaleString()}),e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:"Indexed"})]})]}),e.jsx("div",{className:"h-8 w-px bg-mono-800"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-mono-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:X.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:["Not indexed",(X.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-faint",children:["· ",(X.reasonGroups??[]).length," ",(X.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),X.summary.deindexed>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-8 w-px bg-mono-800"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-negative-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:X.summary.deindexed.toLocaleString()}),e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:"Deindexed"})]})]})]})]})]})})()}),e.jsx("div",{className:"mt-3 flex border-b border-default",role:"tablist","aria-label":"Coverage status",children:["indexed","notIndexed","deindexed"].map(d=>{const P=d==="indexed"?X.indexed.length:d==="notIndexed"?X.notIndexed.length:X.deindexed.length,z=d==="indexed"?"Indexed":d==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",role:"tab","aria-selected":Ee===d,className:`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${Ee===d?"border-accent text-heading":"border-transparent text-secondary hover:border-mono-600 hover:text-strong"}`,onClick:()=>{Os(d),He(null)},children:[z," (",P,")"]},d)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[Ee==="indexed"&&X.indexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Verdict"}),e.jsx("th",{className:"text-left",children:"Last Crawl"}),e.jsx("th",{className:"text-left",children:"Mobile"})]})}),e.jsx("tbody",{children:un.map(d=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:d.url}),e.jsx("td",{className:"text-secondary",children:d.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:d.crawlTime?d.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:d.isMobileFriendly===!0?"Yes":d.isMobileFriendly===!1?"No":"—"})]},d.id))})]}),Ee==="notIndexed"&&!lt&&(X.reasonGroups??[]).length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Reason"}),e.jsx("th",{className:"text-right",children:"Pages"})]})}),e.jsx("tbody",{children:(X.reasonGroups??[]).map(d=>e.jsxs("tr",{className:"cursor-pointer hover:bg-surface-inset-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>He(d.reason),onKeyDown:P=>{(P.key==="Enter"||P.key===" ")&&(P.preventDefault(),He(d.reason))},tabIndex:0,role:"button","aria-label":`View ${d.reason} pages`,children:[e.jsx("td",{className:"text-strong",children:d.reason}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:d.count})]},d.reason))})]}),Ee==="notIndexed"&&!lt&&(X.reasonGroups??[]).length===0&&X.notIndexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Indexing State"}),e.jsx("th",{className:"text-left",children:"Coverage"})]})}),e.jsx("tbody",{children:mn.map(d=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:d.url}),e.jsx("td",{className:"text-secondary",children:d.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:d.coverageState??"Unknown"})]},d.id))})]}),Ee==="notIndexed"&<&&(()=>{const d=(X.reasonGroups??[]).find(P=>P.reason===lt);return d?e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsxs("button",{type:"button",className:"text-xs text-secondary hover:text-strong transition-colors",onClick:()=>He(null),children:["←"," Back to reasons"]})}),e.jsxs("div",{className:"mb-3 flex items-center justify-between rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:d.reason}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[d.count," affected page",d.count!==1?"s":""]})]}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:ls,onClick:()=>{Qa(d.urls.map(P=>P.url))},children:ls?"Requesting…":`Request indexing (${d.count})`})]}),e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Last Crawl"}),e.jsx("th",{className:"w-8"})]})}),e.jsx("tbody",{children:_n.map(P=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:P.url}),e.jsx("td",{className:"text-secondary",children:P.crawlTime?P.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-strong transition-colors",disabled:ls,onClick:()=>{Qa([P.url])},title:"Request indexing",children:"Index"})})]},P.id))})]})]}):null})(),Ee==="deindexed"&&X.deindexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Previous"}),e.jsx("th",{className:"text-left",children:"Current"}),e.jsx("th",{className:"text-left",children:"Detected"})]})}),e.jsx("tbody",{children:Fn.map((d,P)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:d.url}),e.jsx("td",{className:"text-secondary",children:d.previousState}),e.jsx("td",{className:"text-secondary",children:d.currentState}),e.jsx("td",{className:"text-secondary",children:d.transitionDate.split("T")[0]})]},`${d.url}-${P}`))})]}),(Ee==="indexed"&&X.indexed.length===0||Ee==="notIndexed"&&!lt&&X.notIndexed.length===0||Ee==="deindexed"&&X.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),e.jsx(gs,{page:Fs,pageSize:Zt,visibleRows:Math.min(Zt,Ve.length-et),totalRows:Ve.length,onPageChange:St,itemLabel:"URLs"})]}),e.jsx("p",{className:"mt-3 text-xs text-muted",children:"Google's Indexing API is intended for eligible JobPosting and BroadcastEvent pages. Sitemap resubmission is the general-site bulk path."}),e.jsxs("div",{className:"mt-4 border-t border-default pt-3",children:[e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between text-left text-xs text-secondary hover:text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400","aria-expanded":ue,onClick:()=>ie(d=>!d),children:[e.jsx("span",{children:"Coverage history"}),e.jsx("span",{children:ue?"Hide snapshots":gt.length>0?`View ${gt.length} snapshots`:"View history"})]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["Current: ",X.summary.indexed.toLocaleString()," indexed, ",X.summary.notIndexed.toLocaleString()," not indexed.",ft&&e.jsxs(e.Fragment,{children:[" Since the last snapshot: ",ft.indexed>=0?"+":"",ft.indexed.toLocaleString()," indexed, ",ft.notIndexed>=0?"+":"",ft.notIndexed.toLocaleString()," not indexed."]})]}),ue&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:gt.length>0?e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Date"}),e.jsx("th",{className:"text-right",children:"Indexed"}),e.jsx("th",{className:"text-right",children:"Not indexed"})]})}),e.jsx("tbody",{children:gt.map(d=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:d.date}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:d.indexed.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:d.notIndexed.toLocaleString()})]},d.date))})]}):e.jsx("p",{className:"text-sm text-muted",children:"No saved coverage snapshots yet."})})]})]}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:Ie?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),e.jsxs(te,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Sitemaps"}),e.jsx("h3",{children:"Sitemap operations"})]}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:L||!qe?.propertyId,onClick:()=>{Qn()},children:L?"Reloading…":"Reload from Google"})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"url",placeholder:"https://example.com/sitemap.xml",value:$e,onChange:d=>Jt(d.target.value),onKeyDown:d=>d.key==="Enter"&&void js([$e.trim()])}),e.jsx(A,{type:"button",size:"sm",disabled:!_t||pt||!$e.trim(),onClick:()=>{js([$e.trim()])},children:pt?"Submitting…":"Submit sitemap to Google"})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:!_t||pt||Ue.length===0,onClick:()=>{js(Ue)},children:pt?"Resubmitting…":pn}),e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:!_t||pt||!De?.length,onClick:()=>{Li()},children:"Resubmit all files"}),Re&&e.jsxs("span",{className:"text-xs text-muted",children:["Top level: ",Re.indexes," index",Re.indexes===1?"":"es",", ",Re.files," file",Re.files===1?"":"s"]}),he&&e.jsxs("span",{className:"text-xs text-secondary",children:["Submitting ",he.completed,"/",he.total]})]}),e.jsx("p",{className:"mt-2 text-xs text-muted",children:"Google is asked to refetch these sitemaps. Indexing is not guaranteed."}),!_t&&qe&&e.jsxs("div",{className:"mt-2 flex items-center gap-2 text-xs text-caution",children:[e.jsx("span",{children:"Reconnect to let Canonry submit sitemaps. Your current Canonry OAuth grant is read-only."}),e.jsx("button",{type:"button",className:"text-secondary underline hover:text-strong",onClick:ye(Ya),children:"Reconnect"})]}),De&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:De.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Ss,{value:S,onChange:d=>{re(d),Ft.setPage(1)},label:"Filter sitemaps",placeholder:"Filter sitemaps…"}),e.jsxs("table",{className:"data-table mt-3 w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Sitemap"}),e.jsx("th",{className:"text-left",children:"Type"}),e.jsx("th",{className:"text-left",children:"Google status"}),e.jsx("th",{className:"text-left",children:"Last submitted"}),e.jsx("th",{className:"text-left",children:"Last read"}),e.jsx("th",{className:"text-right",children:"Discovered URLs"}),e.jsx("th",{className:"text-left",children:"Issues"}),e.jsx("th",{className:"text-left",children:"Actions"})]})}),e.jsx("tbody",{children:Ft.rows.flatMap(d=>{const P=xr(d),z=pr(d),J=gr(d),je=Nt[d.path]??[],we=ut.has(d.path),Ce=e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs text-strong",children:e.jsx(Js,{value:d.path})}),e.jsx("td",{className:"text-secondary",children:d.isSitemapsIndex?e.jsx("button",{type:"button",className:"text-secondary hover:text-strong","aria-expanded":we,"aria-label":`${we?"Collapse":"Expand"} files in ${d.path}`,onClick:()=>{Ri(d.path)},children:Ze.has(d.path)?"Loading…":`${we?"▾":"▸"} Index${Nt[d.path]?` (${je.length})`:""}`}):"Sitemap"}),e.jsx("td",{className:"text-secondary",children:J}),e.jsx("td",{className:"text-secondary",children:d.lastSubmitted?d.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:d.lastDownloaded?d.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:P.toLocaleString()}),e.jsx("td",{className:"max-w-48 text-secondary",children:z||"—"}),e.jsx("td",{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:!_t||pt,onClick:()=>{js([d.path])},children:d.lastSubmitted?"Resubmit to Google":"Submit to Google"}),qe?.sitemapUrl===d.path?e.jsx("span",{className:"text-xs text-muted",title:"Used when no sitemap URL is provided for Canonry GSC operations.",children:"Default sitemap"}):e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:rs,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{za(d.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Bn.isPending,onClick:()=>{Ha(d.path)},children:"Inspect URLs"})]})})]},d.path),Oe=d.isSitemapsIndex&&we?je.map(fe=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs pl-6 text-secondary",children:e.jsx(Js,{value:fe.path})}),e.jsx("td",{className:"text-secondary",children:"File"}),e.jsx("td",{className:"text-secondary",children:gr(fe)}),e.jsx("td",{className:"text-secondary",children:fe.lastSubmitted?fe.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:fe.lastDownloaded?fe.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:xr(fe).toLocaleString()}),e.jsx("td",{className:"text-secondary",children:pr(fe)||"—"}),e.jsx("td",{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:!_t||pt,onClick:()=>{js([fe.path])},children:"Resubmit"}),qe?.sitemapUrl===fe.path?e.jsx("span",{className:"text-xs text-muted",title:"Used when no sitemap URL is provided for Canonry GSC operations.",children:"Default sitemap"}):e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:rs,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{za(fe.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Bn.isPending,onClick:()=>{Ha(fe.path)},children:"Inspect URLs"})]})})]},`${d.path}:${fe.path}`)):[];return[Ce,...Oe]})})]}),e.jsx(gs,{page:Ft.page,pageSize:Tt,visibleRows:Ft.rows.length,totalRows:Ft.totalRows,onPageChange:Ft.setPage,itemLabel:"sitemaps"})]}):e.jsx("p",{className:"text-sm text-muted",children:"No sitemaps found for this property."})})]}),e.jsxs(te,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Inspection"}),e.jsx("h3",{children:"Inspect a URL"})]})}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"url",placeholder:"https://example.com/page",value:x,onChange:d=>$(d.target.value),onKeyDown:d=>d.key==="Enter"&&void Ja()}),e.jsx(A,{type:"button",size:"sm",disabled:Xe||!qe?.propertyId||!x.trim(),onClick:ye(Ja),children:Xe?"Inspecting…":"Inspect URL"})]}),D&&e.jsxs("div",{className:"mt-3 grid gap-3 md:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Indexing state"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:D.indexingState??"Unknown"})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Verdict"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:D.verdict??"Unknown"})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Mobile friendly"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:Xa(D.isMobileFriendly??null)})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Last crawl"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:Dt(D.crawlTime)})]})]})]}),e.jsxs(te,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Inspection log"})]}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:Se,onClick:()=>{gn(!0)},children:Se?"Loading…":"Refresh history"})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"text",placeholder:"Filter exact URL",value:Y,onChange:d=>me(d.target.value)}),e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:Se,onClick:()=>{gn(!0)},children:"Apply filter"})]}),k.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Indexing"}),e.jsx("th",{className:"text-left",children:"Verdict"}),e.jsx("th",{className:"text-left",children:"Coverage"}),e.jsx("th",{className:"text-left",children:"Mobile"}),e.jsx("th",{className:"text-left",children:"Inspected"})]})}),e.jsx("tbody",{children:k.map(d=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:d.url}),e.jsx("td",{className:"text-neutral",children:d.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:d.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:d.coverageState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:Xa(d.isMobileFriendly??null)}),e.jsx("td",{className:"text-secondary",children:Dt(d.inspectedAt)})]},d.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No inspection history yet."})]}),e.jsxs(te,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Deindexed"}),e.jsx("h3",{children:"Recent indexing losses"})]})}),v.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Previous"}),e.jsx("th",{className:"text-left",children:"Current"}),e.jsx("th",{className:"text-left",children:"Changed at"})]})}),e.jsx("tbody",{children:v.map(d=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:d.url}),e.jsx("td",{className:"text-secondary",children:d.previousState??"Unknown"}),e.jsx("td",{className:"text-neutral",children:d.currentState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:Dt(d.transitionDate)})]},`${d.url}:${d.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No deindexed transitions recorded."})]})]}),qe&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-default pt-3",children:e.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 text-left",onClick:()=>ge(d=>!d),children:[e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",className:`h-4 w-4 text-muted transition-transform ${I?"rotate-90":""}`,"aria-hidden":"true",children:e.jsx("path",{fillRule:"evenodd",d:"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z",clipRule:"evenodd"})}),e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted",children:"Setup & Configuration"})]})}),I&&e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(te,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Property"}),e.jsx("h3",{children:"Pick the Search Console property"})]})}),e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:`gsc-property-${t}`,children:"Property URL"}),e.jsx("select",{id:`gsc-property-${t}`,className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none",value:E,disabled:ne||u.length===0,onChange:d=>F(d.target.value),children:u.length===0?e.jsx("option",{value:"",children:ne?"Loading properties…":"No properties available"}):u.map(d=>e.jsxs("option",{value:d.siteUrl,children:[d.siteUrl," · ",d.permissionLevel]},d.siteUrl))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:ne,onClick:()=>{Ba(qe,!0)},children:ne?"Refreshing…":"Refresh properties"}),e.jsx(A,{type:"button",size:"sm",disabled:!E||Ae,onClick:ye(Di),children:Ae?"Saving…":"Save property"})]}),e.jsx("p",{className:"text-xs text-muted",children:"The selected property is used for future syncs and URL inspections for this project."})]})]}),e.jsxs(te,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Sync"}),e.jsx("h3",{children:"Import GSC performance data"})]})}),e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-[160px_1fr]",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:`gsc-sync-days-${t}`,children:"Days"}),e.jsx("input",{id:`gsc-sync-days-${t}`,type:"number",min:"1",className:"mt-0.5 w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:M,onChange:d=>se(d.target.value)})]}),e.jsxs("label",{className:"flex items-center gap-2 rounded border border-default bg-surface-subtle px-3 py-2 text-sm text-neutral",children:[e.jsx("input",{type:"checkbox",checked:de,onChange:d=>C(d.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(A,{type:"button",size:"sm",disabled:_s.isPending||!qe.propertyId,onClick:ye(Ei),children:_s.isPending?"Queueing…":"Queue sync"}),!qe.propertyId&&e.jsx("p",{className:"text-xs text-caution-400",children:"Select a Search Console property before queueing a sync."})]})]})]})})]})]})]})}const gd=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function fd({projectName:t,projectId:s}){const n=as(),[a,r]=l.useState(null),[i,c]=l.useState(null),[u,o]=l.useState(!1),h=Ne(Ra({client:V,path:{name:t}})),p=h.data?.find(T=>T.connectionType==="gbp"),m=!!p,g=a?{locationName:a}:void 0,k=Ne({...yo({client:V,path:{name:t}}),enabled:m}),R=Ne({...vo({client:V,path:{name:t},query:g}),enabled:m}),v=Ne({...No({client:V,path:{name:t},query:g}),enabled:m}),j=Ne({...wo({client:V,path:{name:t},query:g}),enabled:m}),D=Ne({...So({client:V,path:{name:t},query:g}),enabled:m}),O=Ne({...Co({client:V,path:{name:t},query:g}),enabled:m}),E=Ne({queryKey:["gbp-section-insights",t],queryFn:()=>ko(t),enabled:m});function F(){ze(n,"gbp")}const x=en({...$o(),onSuccess:T=>{Ao({id:T.runId,projectId:s,kind:fs["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),xe({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),$=l.useSyncExternalStore(Hr,Ln,Ln),M=Object.values($.runs).some(T=>T.kind===fs["gbp-sync"]&&T.projectId===s),se=x.isPending||M,de=en({...To(),onSuccess:()=>F()});if(l.useEffect(()=>{if(!a||!k.data)return;const T=k.data.locations.filter(ne=>ne.selected);(T.length<=1||!T.some(ne=>ne.locationName===a))&&r(null)},[a,k.data]),l.useEffect(()=>{if(!i||!k.data)return;(a?[a]:k.data.locations.filter(ne=>ne.selected).map(ne=>ne.locationName)).includes(i)||c(null)},[i,k.data,a]),h.isLoading)return null;if(!p){const T=[{title:"Connect your Google account",command:`canonry gbp connect ${t}`,note:"Opens Google OAuth. Grant Business Profile (business.manage) access."},{title:"Choose the account",command:`canonry gbp accounts ${t}`,note:"Pick which Business Profile account this project tracks."},{title:"Select locations",command:`canonry gbp locations discover ${t}`,note:e.jsxs(e.Fragment,{children:["Then adopt the ones to sync: ",e.jsxs("code",{className:"rounded bg-bg-elevated/80 px-1 py-0.5 font-mono text-[11px] text-secondary",children:["canonry gbp locations select ",t," <location>"]})]})},{title:"Sync, and keep it fresh",command:`canonry gbp sync ${t}`,note:e.jsxs(e.Fragment,{children:["Schedule it: ",e.jsxs("code",{className:"rounded bg-bg-elevated/80 px-1 py-0.5 font-mono text-[11px] text-secondary",children:["canonry schedule set ",t," --kind gbp-sync --preset daily"]})]})}];return e.jsx("section",{className:"page-section-divider",children:e.jsxs(te,{className:"surface-card",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Local presence"}),e.jsx("h2",{children:"Connect Google Business Profile"}),e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-muted",children:"Track local performance, search terms, place-action CTAs, and how your public Maps listing compares to the profile you control. Four steps from the CLI:"}),e.jsx("ol",{className:"mt-5 space-y-4",children:T.map((ne,ce)=>e.jsxs("li",{className:"grid grid-cols-[1.5rem_1fr] gap-x-3",children:[e.jsx("span",{className:"mt-0.5 inline-flex h-6 w-6 items-center justify-center rounded-full bg-mono-800 text-xs font-medium tabular-nums text-neutral","aria-hidden":"true",children:ce+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:ne.title}),e.jsx("code",{className:"mt-1.5 inline-block w-fit max-w-full overflow-x-auto rounded bg-bg-elevated/80 px-2 py-1 font-mono text-xs text-neutral",children:ne.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:ne.note})]})]},ne.title))})]})})}const C=R.data,b=k.data?.locations??[],_=b.filter(T=>T.selected),w=v.data?.keywords??[],B=j.data?.lodging??[],oe=D.data?.placeActions??[],ee=O.data?.places??[],U=b.length>0?b[0].accountName:p.domain,pe=a?b.find(T=>T.locationName===a)?.displayName??null:null,le=a?b.filter(T=>T.locationName===a):_,K=new Set(le.map(T=>T.locationName)),q=B.filter(T=>K.has(T.locationName)),y=oe.filter(T=>K.has(T.locationName)),Y=ee.filter(T=>K.has(T.locationName)),me=new Set(_.map(T=>T.locationName)),N=a?w:w.filter(T=>me.has(T.locationName)),G=!a&&_.length>1,Q=(E.data??[]).filter(T=>!T.dismissed&&gd.has(T.type)&&(!pe||T.query===pe||T.query===a||T.title.startsWith(pe)));return e.jsx("section",{className:"page-section-divider",children:e.jsxs(te,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Local presence"}),e.jsxs("h2",{className:"flex items-center gap-2",children:["Google Business Profile",e.jsx(Ke,{text:"How AI answer engines and Maps surface this business: performance, search terms, and how your public listing compares to the profile you control."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Z,{tone:"positive",children:"Connected"}),!H()&&e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:se,onClick:()=>x.mutate({client:V,path:{name:t},body:{}}),children:se?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-muted",children:[U?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-secondary",children:U})," · "]}):null,k.data?`${k.data.totalSelected} of ${k.data.totalDiscovered} locations tracked`:"Loading locations…"]}),_.length>1&&e.jsxs("div",{className:"mb-5 max-w-xs",children:[e.jsx("label",{htmlFor:"local-presence-location",className:"mb-1 block text-sm font-medium text-secondary",children:"Location"}),e.jsxs("select",{id:"local-presence-location",value:a??"",onChange:T=>r(T.target.value||null),className:"w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-strong focus:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:[e.jsx("option",{value:"",children:"All locations"}),_.map(T=>e.jsx("option",{value:T.locationName,children:T.displayName},T.id))]})]}),_.length===0?e.jsxs("p",{className:"text-sm text-muted",children:["No locations are tracked yet. Open ",e.jsx("span",{className:"font-medium text-neutral",children:"Manage locations"})," below to track the one(s) for this business."]}):e.jsxs(e.Fragment,{children:[Q.length>0&&e.jsxs("div",{className:"mb-6 grid gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Needs attention"}),Q.map(T=>e.jsx("div",{className:["insight-card",Pd(T.severity),"rounded-r-lg border border-default bg-surface p-3 pl-4"].filter(Boolean).join(" "),children:e.jsxs("p",{className:"flex items-center gap-2 text-sm font-medium text-strong",children:[T.title,T.recommendation?.reason&&e.jsx(Ke,{text:T.recommendation.reason})]})},T.id))]}),C&&e.jsx(Dd,{performance:C.performance,freshness:C.freshness,timeseries:C.timeseries}),C?.profileCompleteness&&e.jsx(bd,{summary:C.profileCompleteness}),le.length>0&&e.jsx(jd,{locations:le,lodging:q,places:Y,placeActions:y,expandedLocation:i,onToggleExpanded:T=>{c(ne=>ne===T?null:T)}}),e.jsxs("div",{className:"mb-2",children:[e.jsxs("div",{className:"section-head section-head-inline mb-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search terms"}),v.data&&v.data.total>0&&e.jsxs("span",{className:"text-[11px] text-faint",children:[v.data.thresholdedPct,"% privacy-thresholded"]})]}),N.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No keyword impressions stored yet."}):e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Search term"}),G&&e.jsx("th",{className:"text-left",children:"Location"}),e.jsx("th",{className:"text-right",children:"Impressions"}),e.jsx("th",{className:"text-right",children:"Window"})]})}),e.jsx("tbody",{children:N.slice(0,25).map(T=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-neutral",children:T.keyword}),G&&e.jsx("td",{className:"text-muted",children:b.find(ne=>ne.locationName===T.locationName)?.displayName??T.locationName}),e.jsx("td",{className:"text-right font-mono text-strong",children:T.valueCount!==null?T.valueCount.toLocaleString():e.jsxs("span",{className:"text-muted",title:"Privacy floor — Google withheld the exact count",children:["<",T.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-faint",children:[T.periodStart,"–",T.periodEnd]})]},`${T.locationName}:${T.keyword}`))})]})]})]}),e.jsxs("div",{className:"mt-6 border-t border-default pt-4",children:[e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 text-xs font-medium text-secondary hover:text-strong",onClick:()=>o(T=>!T),"aria-expanded":u,children:[e.jsx("span",{"aria-hidden":"true",children:u?"▾":"▸"})," Manage locations (",b.length,")"]}),u&&e.jsx("div",{className:"mt-3",children:b.length===0?e.jsxs("p",{className:"text-sm text-muted",children:["No locations discovered. Run ",e.jsx("span",{className:"font-mono",children:"canonry gbp locations discover"}),"."]}):e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Location"}),e.jsx("th",{className:"text-left",children:"Address"}),e.jsx("th",{className:"text-left",children:"Status"}),!H()&&e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:b.map(T=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:T.displayName}),e.jsx("td",{className:"text-muted",children:T.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(Z,{tone:T.selected?"positive":"neutral",children:T.selected?"Tracked":"Not tracked"})}),!H()&&e.jsx("td",{className:"text-right",children:e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:de.isPending,onClick:()=>de.mutate({client:V,path:{name:t,locationName:T.locationName},body:{selected:!T.selected}}),children:T.selected?"Untrack":"Track"})})]},T.id))})]})})]})]})})}function bd({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:zs(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:zs(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:zs(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:zs(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:zs(t.withSecondaryCategories,s,"caution")},{label:"Closed",value:String(t.permanentlyClosed+t.temporarilyClosed),detail:t.permanentlyClosed||t.temporarilyClosed?`${t.permanentlyClosed} permanent, ${t.temporarilyClosed} temporary`:"reported open",tone:t.permanentlyClosed>0?"negative":t.temporarilyClosed>0?"caution":"positive"}];return e.jsxs("div",{className:"mb-6 border-y border-default py-3",children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Owner profile · Business Information"}),e.jsx(Ke,{text:"Counts selected locations where Google Business Information returned the owner-authored field. A missing value means it was not returned by this API response, not that every Google surface is empty."})]}),e.jsx("div",{className:"grid gap-x-5 gap-y-3 sm:grid-cols-2 lg:grid-cols-3",children:n.map(a=>e.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_auto] items-baseline gap-3",children:[e.jsx("span",{className:"text-xs text-muted",children:a.label}),e.jsx("span",{className:`font-mono text-sm tabular-nums ${Td(a.tone)}`,children:a.value}),a.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-faint",children:a.detail})]},a.label))})]})}function jd({locations:t,lodging:s,places:n,placeActions:a,expandedLocation:r,onToggleExpanded:i}){const c=new Map(s.map(h=>[h.locationName,h])),u=new Map(n.map(h=>[h.locationName,h])),o=new Map;for(const h of a){const p=o.get(h.locationName)??[];p.push(h),o.set(h.locationName,p)}return e.jsxs("div",{className:"mb-6",children:[e.jsxs("div",{className:"section-head section-head-inline mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Source evidence"}),e.jsx(Ke,{text:H()?"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest sync, not that every Google product lacks the information.":"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest Canonry sync, not that every Google product lacks the information."})]}),e.jsxs("span",{className:"text-[11px] text-faint",children:[t.length," location",t.length===1?"":"s"]})]}),e.jsx("div",{className:"data-table-wrapper",children:e.jsxs("table",{className:"data-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"min-w-[14rem]",children:"Location"}),e.jsx("th",{className:"min-w-[15rem]",children:"Owner profile"}),e.jsx("th",{className:"min-w-[11rem]",children:"Hotel data"}),e.jsx("th",{className:"min-w-[11rem]",children:"Public Maps"}),e.jsx("th",{className:"min-w-[10rem]",children:"CTAs"}),e.jsx("th",{className:"text-right",children:"Detail"})]})}),e.jsx("tbody",{children:t.map(h=>{const p=c.get(h.locationName)??null,m=u.get(h.locationName)??null,g=o.get(h.locationName)??[],k=r===h.locationName;return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-strong",children:h.displayName}),e.jsx("p",{className:"mt-1 text-xs text-faint",children:h.primaryCategoryDisplayName??"Primary category not returned"}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[e.jsx(Z,{tone:h.selected?"positive":"neutral",children:h.selected?"Tracked":"Not tracked"}),h.openStatus&&h.openStatus!=="OPEN"&&e.jsx(Z,{tone:h.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:yi(h.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(vd,{location:h})}),e.jsx("td",{children:e.jsx(Nd,{lodging:p})}),e.jsx("td",{children:e.jsx(Sd,{place:m,mapsUri:h.mapsUri})}),e.jsx("td",{children:e.jsx(kd,{actions:g})}),e.jsx("td",{className:"text-right",children:e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>i(h.locationName),children:k?"Hide":"Details"})})]}),k&&e.jsx("tr",{className:"bg-mono-950/35 hover:bg-mono-950/35",children:e.jsx("td",{colSpan:6,className:"px-4 py-4",children:e.jsx($d,{location:h,lodging:p,place:m,placeActions:g})})})]},h.id)})})]})})]})}function yd(t){return[{label:"Description",tone:ms(t.description)?"positive":"neutral",value:ms(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:ms(t.primaryPhone)?"positive":"neutral",value:ms(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:ms(t.websiteUri)?"positive":"neutral",value:ms(t.websiteUri)?"set":"not returned"},{label:"Secondary",tone:t.additionalCategories.length>0?"positive":"neutral",value:t.additionalCategories.length>0?String(t.additionalCategories.length):"not returned"},{label:"Service area",tone:t.serviceArea?"positive":"neutral",value:t.serviceArea?"set":"not returned"}]}function vd({location:t}){const s=yd(t);return e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>e.jsxs(Z,{tone:n.tone,children:[n.label," ",n.value]},n.label))})}function Nd({lodging:t}){return e.jsx(qa,{...wd(t)})}function wd(t){return t?t.populatedGroupCount===0?{tone:"neutral",label:"0 groups returned",detail:"Lodging API returned no readable groups; verify Hotel details."}:{tone:"positive",label:`${t.populatedGroupCount} group${t.populatedGroupCount===1?"":"s"} returned`,detail:"Owner lodging attributes."}:{tone:"neutral",label:"No Lodging API snapshot",detail:"Not returned for this scoped location."}}function Sd({place:t,mapsUri:s}){return e.jsx(qa,{...Cd(t,s)})}function Cd(t,s){if(!t)return{tone:"neutral",label:"Public listing not checked",detail:s?"Maps link available.":"No Places snapshot."};const n=t.amenities.length;return{tone:n>0?"positive":"neutral",label:n>0?`${n} signal${n===1?"":"s"} detected`:"0 supported signals detected",detail:`Places tier: ${t.tier}`}}function kd({actions:t}){return e.jsx(qa,{...Ad(t)})}function Ad(t){if(t.length===0)return{tone:"neutral",label:"No CTAs stored",detail:"No placeActionLinks returned."};const s=t.filter(n=>n.providerType==="MERCHANT").length;return s===0?{tone:"neutral",label:`${t.length} aggregator CTA${t.length===1?"":"s"}`,detail:"No merchant-owned CTA returned."}:{tone:"positive",label:`${s} merchant CTA${s===1?"":"s"}`,detail:`${t.length} total returned.`}}function qa({tone:t,label:s,detail:n}){return e.jsxs("div",{children:[e.jsx(Z,{tone:t,children:s}),e.jsx("p",{className:"mt-1.5 text-xs leading-5 text-faint",children:n})]})}function $d({location:t,lodging:s,place:n,placeActions:a}){const r=s?Ld(s.attributes):[];return e.jsxs("div",{className:"grid gap-5 text-xs lg:grid-cols-3",children:[e.jsxs(Xn,{title:"Owner profile · Business Information",children:[e.jsx(st,{label:"Primary category",value:t.primaryCategoryDisplayName??"Not returned"}),e.jsx(st,{label:"Secondary categories",value:t.additionalCategories.length>0?t.additionalCategories.join(", "):"Not returned"}),e.jsx(st,{label:"Description",value:ms(t.description)?t.description:"Not returned"}),e.jsx(st,{label:"Hours",value:t.regularHours?"Returned by Google":"Not returned"}),e.jsx(st,{label:"Service area",value:t.serviceArea?"Returned by Google":"Not returned"}),e.jsx(st,{label:"Phone",value:t.primaryPhone??"Not returned"}),e.jsx(st,{label:"Website",value:t.websiteUri??"Not returned"}),e.jsx(st,{label:"Open status",value:yi(t.openStatus)}),e.jsx(st,{label:"Opening date",value:t.openingDate??"Not returned"})]}),e.jsx(Xn,{title:"Hotel data · Lodging API",children:s?e.jsxs(e.Fragment,{children:[e.jsx(st,{label:"Last checked",value:fr(s.syncedAt)}),e.jsx(st,{label:"Groups returned",value:String(s.populatedGroupCount)}),e.jsx(st,{label:"Populated groups",value:r.length>0?r.join(", "):"None returned"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Lodging API snapshot was stored for this location."})}),e.jsxs(Xn,{title:"Public listing + CTAs",children:[n?e.jsxs(e.Fragment,{children:[e.jsx(st,{label:"Places tier",value:n.tier}),e.jsx(st,{label:"Last checked",value:fr(n.syncedAt)}),e.jsx(st,{label:"Public signals",value:n.amenities.length>0?n.amenities.join(", "):"No supported signals detected"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Places Details snapshot was stored for this location."}),t.mapsUri&&e.jsx("a",{href:t.mapsUri,target:"_blank",rel:"noopener noreferrer",className:"inline-block text-muted hover:text-neutral",children:"View on Google Maps →"}),e.jsx("div",{className:"mt-3 border-t border-default pt-3",children:a.length===0?e.jsx("p",{className:"leading-5 text-muted",children:"No placeActionLinks returned."}):e.jsx("div",{className:"grid gap-2",children:a.map(i=>e.jsxs("div",{className:"grid gap-0.5",children:[e.jsxs("span",{className:"font-medium text-neutral",children:[En(i.placeActionType),i.isPreferred?" · preferred":""]}),e.jsxs("span",{className:"text-faint",children:[En(i.providerType),i.uri?` · ${Rd(i.uri)}`:""]})]},i.placeActionLinkName))})})]})]})}function Xn({title:t,children:s}){return e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-[11px] font-semibold uppercase tracking-[0.14em] text-muted",children:t}),e.jsx("div",{className:"grid gap-2",children:s})]})}function st({label:t,value:s}){return e.jsxs("div",{className:"grid grid-cols-[7.25rem_minmax(0,1fr)] gap-3",children:[e.jsx("span",{className:"text-faint",children:t}),e.jsx("span",{className:"min-w-0 break-words text-secondary",children:s})]})}function zs(t,s,n){return t===s?"positive":t===0?n:"caution"}function Td(t){switch(t){case"positive":return"text-positive";case"caution":return"text-caution";case"negative":return"text-negative";case"neutral":return"text-neutral"}}function Pd(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function ms(t){return typeof t=="string"&&t.trim().length>0}function yi(t){return t?En(t):"Not returned"}function En(t){return t?t.toLowerCase().split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"Unknown"}function Rd(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function fr(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Ld(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&Id(n)).map(([s])=>En(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function Id(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function Dd({performance:t,freshness:s,timeseries:n}){const a=t.totals,r=Po.filter(R=>(a[R]??0)>0),i=Ro.filter(R=>(a[R]??0)>0),c=Object.keys(a).filter(R=>(a[R]??0)>0&&Lo(R)==="other").sort((R,v)=>(a[v]??0)-(a[R]??0)),u=Object.keys(a).filter(R=>(a[R]??0)===0).sort(),o=n.map(R=>{const v={date:R.date};for(const[j,D]of Object.entries(R.metrics))v[j]=D;return v}),h=n.find(R=>R.pending)?.date,p=n.length>0?n[n.length-1].date:void 0,m=o.length>0,g=s.dataThroughDate?`Data through ${Dn(s.dataThroughDate)}${s.pendingDays>0?` · ${s.pendingDays}d pending`:""}`:null,k=[...r,...c];return e.jsxs("div",{className:"mb-6 grid gap-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Profile actions · daily"}),g&&e.jsx("span",{className:"text-[11px] text-muted",children:g})]}),!m||r.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No profile action activity yet — run a sync."}):e.jsxs(e.Fragment,{children:[e.jsx(br,{data:o,metrics:r,kind:"line",firstPending:h,lastDate:p}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-x-5 gap-y-1",children:k.map(R=>e.jsxs("span",{className:"text-sm text-secondary",children:[In(R)," ",e.jsx("span",{className:"font-mono text-heading",children:(a[R]??0).toLocaleString()})]},R))})]})]}),m&&i.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(br,{data:o,metrics:i,kind:"area",firstPending:h,lastDate:p})]}),u.length>0&&e.jsxs("p",{className:"text-xs text-faint",children:["Not active: ",u.map(R=>In(R)).join(", ")]})]})}function br({data:t,metrics:s,kind:n,firstPending:a,lastDate:r}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(Rs,{width:"100%",height:"100%",children:e.jsxs(Ls,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Ea,{stroke:Ia,vertical:!1}),e.jsx(Is,{dataKey:"date",tick:vt,tickLine:!1,axisLine:{stroke:Wt},tickFormatter:fa,minTickGap:24}),e.jsx(Ds,{tick:vt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Es,{...ps,labelFormatter:Dn,formatter:(i,c)=>[typeof i=="number"?i.toLocaleString():String(i??0),In(String(c??""))]}),e.jsx(ai,{wrapperStyle:{fontSize:11,color:at.text},formatter:i=>In(i)}),a&&r&&e.jsx(fc,{x1:a,x2:r,fill:at.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:at.textDim,fontSize:10}}),s.map((i,c)=>n==="line"?e.jsx(Ma,{type:"monotone",dataKey:i,stroke:nt[c%nt.length],strokeWidth:2,dot:!1,isAnimationActive:!1},i):e.jsx(Ns,{type:"monotone",dataKey:i,stackId:"reach",stroke:nt[c%nt.length],fill:nt[c%nt.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},i))]})})})}function Ed(t){return Da(Et(String(t)))}function Md(t){return ns(Et(String(t)))}function Zn({children:t,label:s="More info",placement:n="top",className:a}){const r=l.useId(),[i,c]=l.useState(!1);return e.jsxs("span",{className:`relative inline-flex ${a??""}`,children:[e.jsx("button",{type:"button","aria-label":s,"aria-describedby":i?r:void 0,className:"inline-flex h-4 w-4 items-center justify-center rounded-full text-muted hover:text-strong focus:text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),onFocus:()=>c(!0),onBlur:()=>c(!1),children:e.jsx(jc,{className:"h-3.5 w-3.5","aria-hidden":!0})}),i&&e.jsx("span",{id:r,role:"tooltip",className:`absolute z-50 w-64 rounded border border-strong bg-bg-elevated px-3 py-2 text-xs font-normal leading-relaxed text-strong shadow-lg ${n==="top"?"bottom-full mb-2":"top-full mt-2"} left-1/2 -translate-x-1/2 whitespace-normal`,children:t})]})}const Sn=Tt;function vs(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function ea(t){return t.toLocaleString()}function qd(t){const s=Number(t);return Number.isFinite(s)?`${(s*100).toFixed(1)}%`:"—"}function Od(t){const s=Date.now()-new Date(t).getTime(),n=Math.floor(s/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const a=Math.floor(n/60);return a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`}function Kd(t){const s=t.filter(n=>n.kind===fs["backlink-extract"]&&!Vr(n.status));return s.length===0?null:s.reduce((n,a)=>n.createdAt>a.createdAt?n:a)}function Fd(t,s){const n=new Date(t??s).getTime(),a=Math.max(0,Math.floor((Date.now()-n)/1e3));if(a<60)return`${a}s`;const r=Math.floor(a/60),i=a%60;return i===0?`${r}m`:`${r}m ${i}s`}function _d({projectName:t}){const[s,n]=l.useState(null),[a,r]=l.useState(null),[i,c]=l.useState([]),[u,o]=l.useState(null),[h,p]=l.useState(null),[m,g]=l.useState(null),[k,R]=l.useState(Date.now()),[v,j]=l.useState(0),[D,O]=l.useState(!0),[E,F]=l.useState(!1),[x,$]=l.useState(null),M=l.useCallback(async()=>{O(!0),$(null);try{const[U,pe,le,K,q]=await Promise.all([Io().catch(()=>null),Do(t,{excludeCrawlers:!0}).catch(()=>null),Eo(t,{limit:Sn,offset:v,excludeCrawlers:!0}).catch(Y=>{if(Y instanceof pa&&Y.code==="NOT_FOUND")return null;throw Y}),Mo(t).catch(()=>[]),qo(t).catch(()=>[])]);o(U),n(pe),r(le),c(K);const y=Kd(q);p(y)}catch(U){$(U instanceof Error?U.message:"Failed to load backlinks")}finally{O(!1)}},[t,v]);l.useEffect(()=>{M()},[M]),l.useEffect(()=>{if(!h)return;const U=h.id;let pe=!1;const le=async()=>{try{const q=await Wr(U);if(pe)return;Vr(q.status)?(p(null),g(q),await M()):p(y=>y?.id===q.id?{...y,...q}:y)}catch{}},K=window.setInterval(()=>{le()},3e3);return()=>{pe=!0,window.clearInterval(K)}},[h,M]),l.useEffect(()=>{if(!h)return;const U=window.setInterval(()=>R(Date.now()),1e3);return()=>window.clearInterval(U)},[h]),l.useEffect(()=>{if(!m||m.status==="failed")return;const U=window.setTimeout(()=>g(null),1e4);return()=>window.clearTimeout(U)},[m]);async function se(){F(!0),$(null);try{const U=await Fo(t);p(U)}catch(U){U instanceof pa&&U.code==="MISSING_DEPENDENCY"?$("DuckDB is not installed. Visit the Backlinks admin page to install it."):$(U instanceof Error?U.message:"Failed to trigger extract")}finally{F(!1)}}const de=l.useMemo(()=>i.slice().sort((U,pe)=>U.queriedAt.localeCompare(pe.queriedAt)).map(U=>({date:U.queriedAt,linkingDomains:U.totalLinkingDomains})),[i]),C=a?.rows??[],b=a?.total??0,_=s?.excludedLinkingDomains??0,w=Math.floor(v/Sn)+1;return l.useEffect(()=>{v>0&&v>=b&&j(0)},[v,b]),e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Backlinks"}),e.jsx("h2",{children:"Referring domains"})]})}),x&&e.jsx(te,{className:"surface-card p-4 mb-4 border-negative-800/60",children:e.jsx("p",{className:"text-sm text-negative",children:x})}),h&&e.jsx(te,{className:"surface-card p-4 mb-4 border-info-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ga,{className:"h-5 w-5 text-info-400 animate-spin shrink-0 mt-0.5","aria-hidden":!0}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"Extract running"}),e.jsx(Z,{tone:"neutral",children:h.status}),e.jsxs("span",{className:"text-sm text-secondary tabular-nums",children:[Fd(h.startedAt??null,h.createdAt)," elapsed · refreshing every 3s"]}),e.jsxs("span",{className:"sr-only",children:["now=",k]})]}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Refreshing this project from the current Common Crawl release."})]})]})}),m&&!h&&e.jsx(te,{className:`surface-card p-4 mb-4 ${m.status==="failed"?"border-negative-800/60":"border-positive-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[m.status==="failed"?e.jsx("span",{className:"h-5 w-5 shrink-0 mt-0.5 text-negative-400 text-lg leading-none","aria-hidden":!0,children:"!"}):e.jsx(ii,{className:"h-5 w-5 text-positive-400 shrink-0 mt-0.5","aria-hidden":!0}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:`text-sm font-medium ${m.status==="failed"?"text-negative":"text-positive"}`,children:m.status==="failed"?"Extract failed":"Extract complete"}),m.error?e.jsx("p",{className:"text-sm text-secondary mt-1",children:Oo(m.error)}):m.status!=="failed"?e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),B()]});function B(){return D?e.jsx(te,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading backlinks…"})}):oe()}function oe(){const U=s!==null&&s.totalLinkingDomains>0,pe=m?.status==="failed",le=s!==null&&s.totalLinkingDomains===0&&!pe,K=u?.status==="ready",q=u?.status==="failed",y=u&&(u.status==="downloading"||u.status==="querying"||u.status==="queued");return U?ee(e.jsxs(e.Fragment,{children:[!H()&&e.jsxs(e.Fragment,{children:[e.jsxs(A,{type:"button",variant:"outline",size:"sm",disabled:E||h!==null,onClick:ye(se),children:[e.jsx(ri,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":E?"Queuing…":"Re-run extract"]}),e.jsx(Zn,{label:"About re-running",children:"Re-queries the current release for this project without downloading it again."})]}),!H()&&e.jsx(A,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:vs("/backlinks"),children:"Open admin"})})]})):e.jsx(te,{className:"surface-card p-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-bg-elevated text-secondary",children:e.jsx(Ko,{className:"h-5 w-5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1",children:[!u&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No release sync yet"}),e.jsx("p",{className:"text-sm text-muted mt-1",children:"Run a workspace release sync to populate backlinks for every project in this workspace."}),!H()&&e.jsx("div",{className:"mt-4",children:e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:vs("/backlinks"),children:"Set up backlinks"})})})]}),y&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Sync in progress"}),e.jsxs("p",{className:"text-sm text-muted mt-1",children:["A workspace release sync is running (",u.status,u.phaseDetail?` — ${u.phaseDetail}`:"","). Backlinks will appear here once it finishes."]}),!H()&&e.jsx("div",{className:"mt-4",children:e.jsx(A,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:vs("/backlinks"),children:"View sync status"})})})]}),q&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Last sync failed"}),e.jsx("p",{className:"text-sm text-muted mt-1",children:u.error??"The workspace release sync failed. Retry from the Backlinks admin page."}),!H()&&e.jsx("div",{className:"mt-4",children:e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:vs("/backlinks"),children:"Go to Backlinks admin"})})})]}),K&&!y&&!le&&!pe&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No backlinks yet for this project"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["Release ",e.jsx("code",{className:"text-neutral",children:u.release})," is ready. Run an extract for this project."]}),!H()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(A,{type:"button",size:"sm",disabled:E||h!==null,onClick:ye(se),children:[e.jsx(Ps,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":E?"Queuing…":"Run extract"]}),e.jsx(Zn,{label:"About extraction",children:"Queries the current release for this project without downloading it again."})]})]}),pe&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Last extract failed"}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"See the error above, then check the workspace source before retrying."}),!H()&&e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:vs("/backlinks"),children:"Go to Backlinks admin"})})})]}),le&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No referring domains found"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["The latest release found no referring domains for ",s.targetDomain,". Try a newer release or re-run this extract."]}),!H()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:vs("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(A,{type:"button",variant:"outline",size:"sm",disabled:E||h!==null,onClick:ye(se),children:[e.jsx(Ps,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":E?"Queuing…":"Re-run extract"]}),e.jsxs(Zn,{label:"What does Re-run extract do?",children:[e.jsxs("span",{className:"block",children:["Re-queries the cached release for ",e.jsx("span",{className:"text-strong",children:s.targetDomain}),". Only useful if the cache files were incomplete last time."]}),e.jsx("span",{className:"mt-2 block text-secondary",children:"No re-download. ~5 min. If the release genuinely has no links for your domain, this won’t help — sync a different release instead."})]})]})]})]})]})})}function ee(U){if(!s)return null;const pe="Linking hosts",le="linking hosts",K="release";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"gauge-row",children:[e.jsxs("div",{className:"metric-card",children:[e.jsx("p",{className:"metric-card-eyebrow",children:"Referring domains"}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:ea(s.totalLinkingDomains)})}),e.jsxs("p",{className:"metric-card-sub",children:["unique domains linking to ",s.targetDomain]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("p",{className:"metric-card-eyebrow",children:["Total ",le]}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:ea(s.totalHosts)})}),e.jsxs("p",{className:"metric-card-sub",children:["aggregate ",le," across referring domains"]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsx("p",{className:"metric-card-eyebrow",children:"Top-10 concentration"}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:qd(s.top10HostsShare)})}),e.jsxs("p",{className:"metric-card-sub",children:["share of ",le," from the 10 largest linking domains"]})]})]}),e.jsxs("p",{className:"text-xs text-muted mt-2",children:[e.jsx("span",{className:"text-secondary",children:"Common Crawl"})," · ",K," ",e.jsx("code",{className:"text-secondary",children:s.release})," · queried ",Od(s.queriedAt),_>0&&e.jsxs(e.Fragment,{children:[" · ",_," excluded domain",_===1?"":"s"]})]}),de.length>=2&&e.jsxs(te,{className:"surface-card p-4 mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Referring domains over time"}),e.jsx("div",{className:"h-40 mt-2",children:e.jsx(Rs,{width:"100%",height:"100%",children:e.jsxs(Ls,{data:de,margin:{top:8,right:12,bottom:0,left:12},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"bl-gradient",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:nt[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:nt[0],stopOpacity:0})]})}),e.jsx(Is,{dataKey:"date",tick:vt,stroke:Wt,tickFormatter:Ed}),e.jsx(Ds,{tick:vt,stroke:Wt,allowDecimals:!1}),e.jsx(Es,{contentStyle:ps.contentStyle,labelStyle:ps.labelStyle,itemStyle:ps.itemStyle,labelFormatter:Md}),e.jsx(Ns,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:nt[0],fill:"url(#bl-gradient)",strokeWidth:2})]})})})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Top referring domains"}),e.jsx(te,{className:"surface-card overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base text-left text-xs uppercase tracking-wide text-faint",children:[e.jsx("th",{className:"px-4 py-2 font-medium",children:"Domain"}),e.jsx("th",{className:"px-4 py-2 text-right font-medium",children:pe})]})}),e.jsxs("tbody",{children:[C.map(q=>e.jsxs("tr",{className:"border-b border-mono-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-strong",children:q.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-secondary tabular-nums",children:ea(q.numHosts)})]},q.linkingDomain)),C.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-muted",colSpan:2,children:_>0&&b===0?`Every referring domain in this ${K} was a crawler/proxy host (${_} hidden).`:`No referring domains in this ${K}.`})})]})]})}),e.jsx(gs,{page:w,pageSize:Sn,visibleRows:C.length,totalRows:b,onPageChange:q=>j((q-1)*Sn)})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:U})]})}}function Ud({projectName:t}){const s=Ne({..._o({client:V,path:{name:t}}),staleTime:Yr}),n=s.data??null,a=s.error;if(s.isLoading&&!n)return null;if(a)return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsx("h2",{children:"Citation + answer-mention coverage"})]})}),e.jsx("p",{className:"text-sm text-negative-400",children:a instanceof Error?a.message:String(a)})]});if(!n)return null;if(n.status==="no-data")return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsx("h2",{children:"Citation + answer-mention coverage"})]})}),e.jsx("p",{className:"text-sm text-muted",children:n.reason==="no-queries"?"Add queries to start tracking AI citations.":"Run a sweep to see which engines cite this project."})]});const{providersCiting:r,providersMentioning:i,providersConfigured:c}=n.summary;return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsxs("h2",{className:"flex items-center gap-2",children:["Cited by ",r," of ",c," engines",e.jsx(Ke,{text:"An engine is ‘citing’ when our domain appears in its grounding source list (the structured citation/search-result attribution it returns alongside the answer). Counts each configured engine that cites the project on at least one tracked query in the latest snapshot per (query × provider)."})]}),e.jsxs("p",{className:"text-base text-neutral flex items-center gap-2",children:["Mentioned in ",i," of ",c," engine answers",e.jsx(Ke,{text:"An engine is ‘mentioning’ when our brand or domain appears inside the prose of the answer text — independent of whether it’s in the citation list. Models often name-drop from training without citing a fresh page."})]})]}),n.summary.latestRunAt&&e.jsxs("p",{className:"supporting-copy",children:["Latest run ",new Date(n.summary.latestRunAt).toLocaleString()]})]}),e.jsx(Bd,{data:n}),e.jsx(Gd,{data:n}),n.competitorGaps.length>0&&e.jsx(Vd,{data:n})]})}function Bd({data:t}){const{totalQueries:s,queriesCitedAndMentioned:n,queriesCitedOnly:a,queriesMentionedOnly:r,queriesInvisible:i}=t.summary;return e.jsxs("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4 mb-4",children:[e.jsx(Cn,{label:"Cited + mentioned",value:`${n} / ${s}`,helper:"In sources AND named in answer",tone:n>0?"positive":"neutral"}),e.jsx(Cn,{label:"Cited only",value:`${a} / ${s}`,helper:"In sources, not named in answer",tone:a>0?"positive-dim":"neutral"}),e.jsx(Cn,{label:"Mentioned only",value:`${r} / ${s}`,helper:"Named in answer, no source link",tone:r>0?"caution":"neutral"}),e.jsx(Cn,{label:"Invisible",value:`${i} / ${s}`,helper:"No engine cites or mentions",tone:i>0?"negative":"neutral"})]})}function Cn({label:t,value:s,helper:n,tone:a}){const r=a==="positive"?"text-positive":a==="positive-dim"?"text-positive-400/70":a==="caution"?"text-caution":a==="negative"?"text-negative":"text-heading";return e.jsxs("div",{className:"rounded-md border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:t}),e.jsx("p",{className:`mt-1 text-2xl font-semibold tabular-nums ${r}`,children:s}),e.jsx("p",{className:"text-[11px] text-muted",children:n})]})}function Gd({data:t}){const s=l.useMemo(()=>{const n=new Set;for(const a of t.byQuery)for(const r of a.providers)n.add(r.provider);return Array.from(n).sort()},[t.byQuery]);return t.byQuery.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No query coverage rows."}):e.jsxs("div",{children:[e.jsx(Qd,{}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),s.map(n=>e.jsx("th",{className:"text-center",children:e.jsx(Ts,{provider:n})},n)),e.jsx("th",{className:"text-right",children:"Cite"}),e.jsx("th",{className:"text-right",children:"Ment"})]})}),e.jsx("tbody",{children:t.byQuery.map(n=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:n.query}),s.map(a=>{const r=n.providers.find(i=>i.provider===a);return e.jsx("td",{className:"text-center",children:r==null?e.jsx(Cc,{className:"inline h-3.5 w-3.5 text-mono-700","aria-label":"no data"}):e.jsx(zd,{provider:r})},a)}),e.jsx("td",{className:"text-right tabular-nums",children:e.jsxs("span",{className:n.totalProviders>0&&n.citedCount===n.totalProviders?"text-positive":n.citedCount>0?"text-positive-400/70":"text-muted",children:[n.citedCount,"/",n.totalProviders]})}),e.jsx("td",{className:"text-right tabular-nums",children:e.jsxs("span",{className:n.totalProviders>0&&n.mentionedCount===n.totalProviders?"text-info-300":n.mentionedCount>0?"text-info-400/70":"text-muted",children:[n.mentionedCount,"/",n.totalProviders]})})]},n.queryId))})]})})]})}function Qd(){return e.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-3 text-[11px] text-muted",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ws,{active:!0,tone:"cited"}),e.jsx("span",{children:"cited (in sources)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ws,{active:!0,tone:"mentioned"}),e.jsx("span",{children:"mentioned (in answer)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ws,{active:!1,tone:"cited"}),e.jsx(ws,{active:!1,tone:"mentioned"}),e.jsx("span",{children:"neither"})]})]})}function zd({provider:t}){const s=Hd(t);return e.jsxs("span",{className:"inline-flex items-center justify-center gap-1",title:s,children:[e.jsx(ws,{active:t.cited,tone:"cited"}),e.jsx(ws,{active:t.mentioned,tone:"mentioned"})]})}function Hd(t){return t.cited&&t.mentioned?"Cited in sources and mentioned in answer":t.cited?"Cited in sources, not mentioned in answer":t.mentioned?"Mentioned in answer, not in sources":"Not cited and not mentioned"}function ws({active:t,tone:s}){if(!t)return e.jsx("span",{className:"inline-block h-2 w-2 rounded-full border border-strong bg-transparent","aria-hidden":"true"});const n=s==="cited"?"inline-block h-2 w-2 rounded-full bg-positive-400 shadow-[0_0_0_1px_rgba(16,185,129,0.25)]":"inline-block h-2 w-2 rounded-full bg-info-400 shadow-[0_0_0_1px_rgba(56,189,248,0.25)]";return e.jsx("span",{className:n,"aria-hidden":"true"})}function Vd({data:t}){return e.jsxs("div",{className:"mt-4",children:[e.jsxs("h3",{className:"text-sm font-semibold text-strong mb-2 flex items-center gap-2",children:["Competitor gaps",e.jsx(Ke,{text:"Queries where the project is not cited but a configured competitor is. Each row maps to one (query, engine) pair — the same query may surface for multiple engines."}),e.jsxs("span",{className:"text-[10px] font-normal uppercase tracking-wide text-muted",children:[t.competitorGaps.length," ",t.competitorGaps.length===1?"gap":"gaps"]})]}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Engine"}),e.jsx("th",{children:"Competitors cited"})]})}),e.jsx("tbody",{children:t.competitorGaps.map(s=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:s.query}),e.jsx("td",{children:e.jsx(Ts,{provider:s.provider})}),e.jsx("td",{className:"text-neutral",children:s.citingCompetitors.join(", ")})]},`${s.queryId}::${s.provider}`))})]})})]})}const on="__cited__",ln="__mentioned__",jt="__mentionShare__";function vi(t){const s=t,{dataStartDate:n,dataEndDate:a}=s;return typeof n!="string"||typeof a!="string"?null:{start:Et(n),end:Et(a),sweepCount:s.sweepCount??1}}function Mn(t){const s=vi(t);if(!s)return"Sweep date unavailable";const n=ns(s.start),a=ns(s.end);return n===a?n:`${n} – ${a} · ${s.sweepCount} sweeps combined`}function Wd(t){const s=vi(t);return s?Da(s.start):""}function qs(t){return t.trim().toLowerCase()}function va(t){return Math.round(t*1e3)/10}function Na(t){return t.byProvider??{}}function Yd(t,s,n){const a=t.buckets.length>0,r=t.buckets.length===1;if(n==="overall"){const o=s==="cited"?on:ln,h=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(m=>({date:m.startDate,[o]:va(m[h])})),series:[o],hasData:a,singleBucket:r}}const i=s==="mentioned"?"mentionRate":"citationRate",c=[...new Set(t.buckets.flatMap(o=>Object.keys(Na(o))))].sort();return{rows:t.buckets.map(o=>{const h={date:o.startDate},p=Na(o);for(const m of c){const g=p[m];h[m]=g?va(g[i]):null}return h}),series:c,hasData:a,singleBucket:r}}function Ni(t){const s=t;return Object.hasOwn(s,"modelEvidenceByProvider")?s.modelEvidenceByProvider??{}:null}function Jd(t){const s=t;return Object.hasOwn(s,"modelAttribution")?s.modelAttribution??{}:null}function Xd(t){return t.servedModelAttribution??{}}function Zd(t){return t.modelServiceMismatch??{}}function eu(t){return t.modelPointerChanges??{}}function tu(t){return t.length>0?t.join(", "):null}function jr(t,s){const n=qs(s);return Object.entries(t).find(([a])=>qs(a)===n)?.[1]}function Gt(t){switch(t.status){case"known":return t.model;case"unknown":return"Unknown model";case"mixed":return`Mixed: ${t.models.join(", ")}${t.includesUnknown?" + unknown":""}`}}function su(t,s){for(let n=t.length-1;n>=0;n-=1){const a=t[n];if(!jr(Na(a),s))continue;const r=Ni(a);return r?jr(r,s)??null:null}return null}function nu(t){const s=new Map;for(const[n,a]of Object.entries(t))for(const r of a.events){const i=s.get(r.bucketStartDate)??[];i.push({provider:n,event:r}),s.set(r.bucketStartDate,i)}return[...s.entries()].sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>({bucketStartDate:n,events:[...a].sort((r,i)=>r.provider.localeCompare(i.provider)||r.event.observedAt.localeCompare(i.event.observedAt))}))}function au(t){const s={},n=[];for(const[a,r]of Object.entries(t)){const i=r.events.filter(c=>!c.fromPreWindowAnchor);for(const c of r.events)c.fromPreWindowAnchor&&n.push({provider:a,event:c});i.length>0&&(s[a]={...r,events:i})}return{buckets:nu(s),beforeWindow:n.sort((a,r)=>a.event.observedAt.localeCompare(r.event.observedAt)||a.provider.localeCompare(r.provider))}}function ru(t){let s=0,n=0;for(const a of Object.values(t))s+=a.events.length,n+=a.eventTotal??a.events.length;return{shown:s,total:n}}function iu(t){const s=[];for(const[n,a]of Object.entries(t)){const r=a.eventTotal??a.events.length;r>a.events.length&&s.push({provider:n,shown:a.events.length,total:r})}return s.sort((n,a)=>n.provider.localeCompare(a.provider))}function ou(t){const s=t.buckets.map(a=>{const r=a.mentionShare;return{date:a.startDate,[jt]:r?.rate==null?null:va(r.rate)}}),n=s.map(a=>a[jt]).filter(a=>typeof a=="number"&&Number.isFinite(a));return{rows:s,series:[jt],hasData:n.length>0,singleBucket:n.length===1}}function lu(t,s,n){return s==="mentionShare"?ou(t):Yd(t,s,n)}function yr(t,s){for(let n=t.length-1;n>=0;n--){const a=t[n][s];if(typeof a=="number"&&Number.isFinite(a))return a}return null}function vr(t){const[,s,n]=t.slice(0,10).split("-");return!s||!n?t:`${s}/${n}`}function Nr(t){return t>0?`+${t}`:`${t}`}function cu(t){if(t.length===0)return null;if(t.length<=2)return`Query set changed: ${t.map(n=>`${Nr(n.delta)} on ${vr(n.date)}`).join(", ")}`;const s=[...t].sort((n,a)=>a.date.localeCompare(n.date))[0];return`Query set changed ${t.length} times (latest ${Nr(s.delta)} on ${vr(s.date)})`}const du=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],uu=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],mu=[{value:"mentioned",label:"Mentioned",description:"Your brand or domain appears in the answer text."},{value:"cited",label:"Cited",description:"Your domain appears in source or grounding links."},{value:"mentionShare",label:"Mention share",description:"Of all answer-text brand mentions for you and tracked competitors, the share that were you."}],Oa=nt[2],hu="var(--chart-tooltip-bg)",xu={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",local:"Local"};function Qt(t){const s=qs(t);return xu[s]??t.charAt(0).toUpperCase()+t.slice(1)}function ss(t){return Math.round(t*10)/10}function pu(t){return t===on||t===ln||t===jt}function wi(t){return t===on?"Cited":t===ln?"Mentioned":t===jt?"Mention share":Qt(t)}function Vs(t,s){return t===on?Ht.positive:t===ln?nt[1]:t===jt?Oa:hc(qs(t),s)}function gu(t,s){for(const n of t){const a=n[s];if(typeof a=="number"&&Number.isFinite(a))return a}return null}function fu(t){return t.map(s=>s.trim().toLowerCase()).filter(Boolean).sort().join(`
|
|
5
|
+
`)}function Rn(t){return t==="cited"?"Cited":t==="mentionShare"?"Mention share":"Mentioned"}function nn(t){return t==="cited"?"citationRate":"mentionRate"}function Si(t,s){return s==="cited"?t.cited:t.mentionedCount}function Ci(t,s,n){const a=t.byProvider[s];return a?{count:n==="cited"?a.cited:a.mentionedCount,total:a.total,rate:n==="cited"?a.citationRate:a.mentionRate}:null}function ki(t,s){if(s===void 0)return null;const n=String(s);return t.find(a=>a.startDate===n)??null}function wa(t){const s=Ni(t);if(s===null)return"Model attribution unavailable for this bucket.";const n=Object.entries(s).sort(([a],[r])=>qs(a).localeCompare(qs(r))).map(([a,r])=>`${Qt(a)}: ${Gt(r)}`);return n.length>0?`Model evidence: ${n.join("; ")}`:"No model evidence in this bucket."}function bu(t){return t.some(({event:s})=>s.to.status==="mixed")?Ht.caution:t.some(({event:s})=>s.to.status==="unknown")?Ht.negative:t.every(({event:s})=>s.from.status==="known"&&s.to.status==="known")?nt[4]:Ht.positive}function ju(t,s,n){const a=ki(t,s);return a?Mn(a):ns(Et(n))}function yu({partition:t,available:s,counts:n,truncated:a,incompleteHistory:r,served:i,mismatch:c,buckets:u}){const o=l.useId(),h=Object.entries(i).sort(([m],[g])=>m.localeCompare(g)),p=t.buckets.length>0||t.beforeWindow.length>0;return e.jsxs("aside",{className:"trend-model-evidence","aria-labelledby":"trend-model-evidence-title","aria-describedby":o,children:[e.jsxs("div",{className:"trend-model-evidence-head",children:[e.jsx("p",{id:"trend-model-evidence-title",className:"trend-model-evidence-title",children:"Model evidence changes"}),e.jsx("span",{className:"trend-model-evidence-key","aria-hidden":"true",children:"Dashed chart markers"})]}),e.jsxs("p",{id:o,className:"sr-only",children:["Model evidence is recorded from the exact snapshots that produced each trend bucket. It is not the project’s configured provider model.",n.total>0?` ${n.shown} of ${n.total} recorded changes are listed.`:""]}),s?p?e.jsxs(e.Fragment,{children:[t.buckets.length>0&&e.jsx("ul",{className:"trend-model-evidence-list",children:t.buckets.flatMap(({bucketStartDate:m,events:g})=>g.map(({provider:k,event:R})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:ju(u,m,R.observedAt)}),e.jsxs("span",{children:[Qt(k),": ",Gt(R.from)," → ",Gt(R.to)]})]},`${k}-${R.observedAt}-${R.bucketStartDate}`)))}),t.beforeWindow.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"trend-model-evidence-note",children:"Changed before this date range"}),e.jsx("ul",{className:"trend-model-evidence-list",children:t.beforeWindow.map(({provider:m,event:g})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsxs("span",{className:"trend-model-evidence-date",children:["on or before ",ns(Et(g.observedAt))]}),e.jsxs("span",{children:[Qt(m),": ",Gt(g.from)," → ",Gt(g.to),g.anchorObservedAt?` (last seen ${Gt(g.from)} on ${ns(Et(g.anchorObservedAt))})`:""]})]},`before-${m}-${g.observedAt}`))})]}),a.map(m=>e.jsxs("p",{className:"trend-model-evidence-note",children:[Qt(m.provider),": showing the most recent ",m.shown," of ",m.total," changes."]},`truncated-${m.provider}`)),r.map(m=>e.jsxs("p",{className:"trend-model-evidence-note",children:["We did not look far enough back to be sure this is every ",Qt(m)," change."]},`incomplete-${m}`))]}):e.jsx("p",{className:"trend-model-evidence-empty",children:"No model evidence changes in this window."}):e.jsx("p",{className:"trend-model-evidence-empty",children:"Attribution unavailable from this API version."}),h.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"trend-model-evidence-note",children:"What the engines answered with"}),e.jsx("ul",{className:"trend-model-evidence-list",children:h.map(([m,g])=>{const k=tu(g.latestServedModelIds),R=c[m];return e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:ns(Et(g.latestObservation.observedAt))}),e.jsxs("span",{children:[Qt(m),": ",k??Gt(g.latestObservation.state),R?` — not the ${Gt(R.configured)} you selected`:""]})]},`served-${m}`)})})]})]})}function wr(t){return t===null?"no data":`${t}%`}function ta(t){return t==null?"undefined":`${ss(t*100)}%`}function vu({active:t,label:s,payload:n,metric:a,mode:r,buckets:i}){if(!t)return null;const c=ki(i,s);if(!c)return null;if(a==="mentionShare"){const o=c.mentionShare.projectMentionSnapshots,h=c.mentionShare.competitorMentionSnapshots,p=o+h,m=c.mentionShare.rate==null?null:ss(c.mentionShare.rate*100);return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:Mn(c)}),e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch trend-tooltip-swatch-ring",style:{borderColor:Oa},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:"Mention share"}),e.jsx("span",{className:"trend-tooltip-value",children:wr(m)})]}),p>0?e.jsxs("p",{className:"trend-tooltip-detail",children:["You ",o," / ",p," brand mentions. Competitors ",h,"."]}):e.jsx("p",{className:"trend-tooltip-detail",children:"No project or competitor brand mentions in this bucket."}),e.jsx("p",{className:"trend-tooltip-detail",children:wa(c)})]})}const u=r==="byProvider"?(n??[]).filter(o=>o.dataKey!==void 0):[{dataKey:a==="cited"?on:ln,value:ss(c[nn(a)]*100)}];return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:Mn(c)}),u.map((o,h)=>{const p=String(o.dataKey??o.name??""),m=r==="byProvider"?Ci(c,p,a):null,g=m?.count??Si(c,a),k=m?.total??c.total,R=typeof o.value=="number"?o.value:ss(m?m.rate*100:c[nn(a)]*100),v=o.color??Vs(p,h);return e.jsxs("div",{className:"trend-tooltip-block",children:[e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch",style:{backgroundColor:v},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:wi(p)}),e.jsx("span",{className:"trend-tooltip-value",children:wr(R)})]}),e.jsxs("p",{className:"trend-tooltip-detail",children:[g," / ",k," snapshots, ",a==="cited"?"source links":"answer text"]})]},`${p}-${h}`)}),e.jsx("p",{className:"trend-tooltip-detail",children:wa(c)})]})}function Nu({buckets:t,metric:s,mode:n,series:a}){return e.jsxs("table",{className:"sr-only",children:[e.jsxs("caption",{children:[Rn(s)," trend data"]}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Bucket"}),e.jsx("th",{scope:"col",children:"Values"})]})}),e.jsx("tbody",{children:t.map(r=>{let i;if(s==="mentionShare"){const c=r.mentionShare.projectMentionSnapshots,u=r.mentionShare.competitorMentionSnapshots,o=c+u;i=o>0?`${ta(r.mentionShare.rate)} mention share, ${c} of ${o} brand mentions were you`:"mention share undefined, no project or competitor brand mentions"}else n==="byProvider"?i=a.map(c=>{const u=Ci(r,c,s);return u?`${Qt(c)} ${ta(u.rate)} ${Rn(s).toLowerCase()}, ${u.count} of ${u.total} snapshots`:`${Qt(c)} no data`}).join("; "):i=`${ta(r[nn(s)])} ${Rn(s).toLowerCase()}, ${Si(r,s)} of ${r.total} snapshots`;return i+=`; ${wa(r)}`,e.jsxs("tr",{children:[e.jsx("th",{scope:"row",children:Mn(r)}),e.jsx("td",{children:i})]},r.startDate)})})]})}function sa({options:t,value:s,onChange:n,ariaLabel:a,className:r}){const i=l.useId();return e.jsx("div",{role:"group","aria-label":a,className:`segmented ${r??""}`,children:t.map(c=>{const u=s===c.value,o=c.description?`${i}-${c.value}-description`:void 0;return e.jsxs(l.Fragment,{children:[e.jsx("button",{type:"button","aria-pressed":u,"aria-describedby":o,className:`segmented-option ${u?"segmented-option-active":""}`,onClick:()=>n(c.value),children:c.label}),c.description&&e.jsx("span",{id:o,className:"sr-only",children:c.description})]},c.value)})})}function wu({projectName:t,competitorDomains:s=[],analyticsRevision:n="none"}){const[a,r]=l.useState("all"),[i,c]=l.useState("mentioned"),[u,o]=l.useState("byProvider"),h=l.useMemo(()=>fu(s),[s]),p=Ne({queryKey:["analytics-metrics",t,a,h,n],queryFn:()=>Uo(t,a),staleTime:Yr}),m=p.data??null,g=p.error,k=i==="mentionShare"?"overall":u,R=l.useMemo(()=>m?lu(m,i,k):null,[m,i,k]),v=m?Jd(m):null,j=l.useMemo(()=>au(v??{}),[v]),D=l.useMemo(()=>ru(v??{}),[v]),O=l.useMemo(()=>iu(v??{}),[v]),E=l.useMemo(()=>Object.entries(v??{}).filter(([,K])=>K.anchorUnavailable).map(([K])=>K).sort(),[v]),F=l.useMemo(()=>m?Xd(m):{},[m]),x=l.useMemo(()=>m?Zd(m):{},[m]),$=l.useMemo(()=>m?Bo(eu(m)):null,[m]),M=i!=="mentionShare"&&k==="byProvider",se=Rn(i),de=i==="cited"?Ht.positive:i==="mentionShare"?Oa:nt[1],C=M?at.textDim:de,b=m?.buckets??[],_=l.useMemo(()=>{const K=new Map(b.map(q=>[q.startDate,Wd(q)]));return q=>K.get(String(q))??""},[b]),w=i==="mentionShare"?R?yr(R.rows,jt):null:b.length>0?ss(b[b.length-1][nn(i)]*100):null,B=i==="mentionShare"?R?gu(R.rows,jt):null:b.length>0?ss(b[0][nn(i)]*100):null,oe=i==="mentionShare"?R?.rows.filter(K=>typeof K[jt]=="number").length??0:b.length,ee=w!==null&&B!==null&&oe>1?ss(w-B):null,U=s.length,pe=e.jsxs(e.Fragment,{children:[$?.kind==="change"&&e.jsx("p",{className:"mb-3 rounded-lg border border-caution-800/60 bg-caution-950/20 px-3 py-2 text-[11px] leading-snug text-secondary",children:$.text}),e.jsxs("div",{className:"visibility-trend-head",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsxs("h2",{className:"visibility-trend-title",children:["Answer-engine trend",e.jsx(Ke,{text:"Three separate signals over sweep buckets: answer text mentions, source citations, and your answer-text mention share against tracked competitors. Mentioned and Cited use query-provider snapshot rates; Mention share uses project plus competitor brand mentions."})]})]}),w!==null&&e.jsxs("div",{className:"visibility-trend-current",children:[e.jsx("span",{className:"visibility-trend-current-dot",style:{backgroundColor:C},"aria-hidden":"true"}),e.jsx("span",{className:"visibility-trend-current-label",children:se}),M&&e.jsx("span",{className:"visibility-trend-current-qualifier",children:"avg"}),e.jsxs("span",{className:"visibility-trend-current-value",children:[w,"%"]}),ee!==null&&e.jsxs("span",{className:`visibility-trend-current-delta ${ee>0?"text-positive-400":ee<0?"text-negative-400":"text-muted"}`,children:[ee>0?"+":"",ee.toFixed(1)," pts"]})]})]}),e.jsxs("div",{className:"visibility-trend-controls",children:[e.jsx(sa,{options:mu,value:i,onChange:c,ariaLabel:"Metric",className:"visibility-trend-metric-control"}),i!=="mentionShare"&&e.jsx(sa,{options:uu,value:u,onChange:o,ariaLabel:"Series"}),e.jsx(sa,{options:du,value:a,onChange:r,ariaLabel:"Time window",className:"sm:ml-auto"})]}),$?.kind==="no-known-change"&&e.jsxs("p",{className:"mt-3 text-[11px] leading-snug text-muted",children:[$.text,e.jsx(Ke,{text:$.detail})]})]});let le;if(g)le=e.jsx("p",{className:"text-sm text-negative-400",children:g instanceof Error?g.message:String(g)});else if(p.isLoading&&!m)le=e.jsx("div",{className:"visibility-trend-chart animate-pulse rounded-lg bg-bg-elevated/40","aria-hidden":"true"});else if(i==="mentionShare"&&U===0)le=e.jsx("p",{className:"text-sm text-secondary",children:"Add tracked competitors to measure mention share over time."});else if(!m||!R)le=null;else{const{rows:K,series:q,hasData:y,singleBucket:Y}=R,me=cu(m.queryChanges);if(!y)le=e.jsx("p",{className:"text-sm text-secondary",children:i==="mentionShare"?"No answer-text brand mentions for you or tracked competitors in this window yet.":"Run a sweep to start tracking citations and mentions over time."});else if(M&&q.length===0)le=e.jsxs("p",{className:"text-sm text-secondary",children:["No per-engine breakdown for this data yet. Switch to ",e.jsx("span",{className:"text-strong",children:"All engines"})," to see the trend."]});else{const N=`${se} rate across ${K.length} ${K.length===1?"sweep":"sweeps"}. Latest ${w}%${ee!==null?`, ${ee>=0?"up":"down"} ${Math.abs(ee).toFixed(1)} points over the period`:""}.`;le=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"sr-only",children:N}),e.jsx(Nu,{buckets:b,metric:i,mode:k,series:q}),M&&q.length>0&&e.jsx("ul",{className:"trend-legend","aria-label":"Engines",children:q.map((G,Q)=>{const T=yr(K,G),ne=su(b,G),ce=v===null?"Attribution unavailable":ne?Gt(ne):"No observed model evidence";return e.jsxs("li",{className:"trend-legend-item",children:[e.jsx("span",{className:"trend-legend-swatch",style:{backgroundColor:Vs(G,Q)},"aria-hidden":"true"}),e.jsxs("span",{className:"trend-legend-label",children:[e.jsx("span",{className:"trend-legend-name",children:wi(G)}),e.jsxs("span",{className:"trend-legend-model",children:[e.jsx("span",{"aria-hidden":"true",children:"· "}),ce]})]}),T!==null&&e.jsxs("span",{className:"trend-legend-value",children:[T,"%"]})]},G)})}),e.jsx("div",{className:"visibility-trend-chart",role:"img","aria-label":`${se} trend chart over ${K.length} ${K.length===1?"bucket":"buckets"}`,children:e.jsx(Rs,{width:"100%",height:"100%",children:e.jsxs(Ls,{data:K,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Ea,{stroke:Ia,vertical:!1}),e.jsx(Is,{dataKey:"date",tick:vt,tickLine:!1,axisLine:{stroke:Wt},tickFormatter:_,minTickGap:24}),e.jsx(Ds,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:G=>`${G}%`,tick:vt,tickLine:!1,axisLine:!1,width:40}),e.jsx(Es,{cursor:{stroke:Wt,strokeWidth:1},content:e.jsx(vu,{metric:i,mode:k,buckets:b})}),j.buckets.map(({bucketStartDate:G,events:Q})=>e.jsx(bc,{x:G,stroke:bu(Q),strokeDasharray:"4 4",strokeWidth:1.5,ifOverflow:"extendDomain"},`model-evidence-${G}`)),q.map((G,Q)=>e.jsx(Ma,{type:"monotone",dataKey:G,name:G,stroke:Vs(G,Q),strokeDasharray:G===jt?"5 4":void 0,strokeWidth:pu(G)?2.5:2,dot:G===jt?{r:2.75,fill:"var(--chart-tooltip-bg)",stroke:Vs(G,Q),strokeWidth:1.5}:{r:2.5,fill:Vs(G,Q),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:hu},connectNulls:G!==jt,isAnimationActive:!1},G))]})})}),e.jsx(yu,{partition:j,available:v!==null,counts:D,truncated:O,incompleteHistory:E,served:F,mismatch:x,buckets:b}),Y&&e.jsx("p",{className:"visibility-trend-note",children:i==="mentionShare"?"Only one competitive mention-share point so far. The trend line fills in after another sweep with brand mentions.":"Only one sweep so far. The trend line fills in after the next run."}),me&&e.jsx("p",{className:"visibility-trend-note",children:me})]})}}return e.jsxs("section",{className:"visibility-trend",children:[pe,le]})}const Sr=new Set([Ys.queued,Ys.running]);function Su({projectName:t}){const s=as(),[n,a]=l.useState(""),[r,i]=l.useState(""),[c,u]=l.useState(""),[o,h]=l.useState("__default__"),[p,m]=l.useState(null),g=Ne({...Go({client:V,path:{name:t}}),staleTime:6e4}),k=Ne({...Jr({client:V}),staleTime:6e4}),R=Ne({...Qo({client:V,path:{name:t},query:{limit:20}}),refetchInterval:C=>C.state.data?.runs.some(b=>Sr.has(b.status))?3e3:!1}),v=R.data?.runs??[];l.useEffect(()=>{!p&&v[0]&&m(v[0].id)},[v,p]);const j=v.find(C=>C.id===p)??null,D=Ne({...zo({client:V,path:{name:t,runId:p??""}}),enabled:!!p,refetchInterval:j&&Sr.has(j.status)?3e3:!1}),O=D.data??null,E=l.useMemo(()=>Au(n),[n]),F=g.data?.locations??[],x=l.useMemo(()=>{const C=new Map((k.data?.providerCatalog??[]).map(b=>[b.name,b]));return(k.data?.providers??[]).filter(b=>b.configured&&C.get(b.name)?.mode==="api").map(b=>({...b,catalog:C.get(b.name)}))},[k.data]),$=!k.isLoading&&x.length===0,M=x.find(C=>C.name===r)??null;l.useEffect(()=>{r&&!M&&(i(""),u(""))},[r,M]);const se=en({...Ho(),onSuccess:async C=>{m(C.id),a(""),u(""),await Ru(s),xe({title:"Research batch saved",detail:`${C.totalQueries} quer${C.totalQueries===1?"y is":"ies are"} in research history. Nothing was added to tracked queries.`,tone:"positive",dedupeKey:`research:start:${C.id}`,dedupeMode:"replace"})},onError:C=>{xe({title:"Could not start research",detail:C instanceof Error?C.message:"Check the provider, model, and location, then try again.",tone:"negative"})}});function de(){if(E.length===0||E.length>50||$||se.isPending||H())return;const C=o==="__default__"?void 0:o==="__none__"?null:F.find(b=>b.label===o)??void 0;se.mutate({client:V,path:{name:t},body:{queries:E,...r?{provider:r}:{},...r&&c.trim()?{model:c.trim()}:{},...C!==void 0?{location:C}:{}}})}return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.85fr)_minmax(360px,1.15fr)]",children:[e.jsxs(te,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"New batch"}),e.jsx("h3",{children:"Research queries"}),e.jsx("p",{className:"mt-1 max-w-xl text-sm leading-6 text-muted",children:"Run specific questions against one API model and keep the answers as a separate research record."})]})}),e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("label",{className:"block",htmlFor:"research-queries",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Queries"}),e.jsx("textarea",{id:"research-queries",className:"mt-1 min-h-36 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:`one query per line
|
|
6
|
+
e.g. What is the best way to choose an AEO platform?`,value:n,onChange:C=>a(C.target.value),"aria-describedby":"research-query-count"}),e.jsxs("span",{id:"research-query-count",className:`mt-1 block text-[11px] ${E.length>50?"text-negative":"text-faint"}`,children:[E.length," ",E.length===1?"query":"queries",", duplicates and blank lines are removed. Maximum 50."]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"block",htmlFor:"research-provider",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"API provider"}),e.jsxs("select",{id:"research-provider",className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none",value:r,onChange:C=>{i(C.target.value),u("")},children:[e.jsx("option",{value:"",children:"Project default"}),x.map(C=>e.jsx("option",{value:C.name,children:C.displayName??C.name},C.name))]})]}),e.jsxs("label",{className:"block",htmlFor:"research-location",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Location"}),e.jsxs("select",{id:"research-location",className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none",value:o,onChange:C=>h(C.target.value),children:[e.jsx("option",{value:"__default__",children:"Project default"}),e.jsx("option",{value:"__none__",children:"No location"}),F.map(C=>e.jsx("option",{value:C.label,children:C.label},C.label))]})]})]}),e.jsxs("label",{className:"block",htmlFor:"research-model",children:[e.jsxs("span",{className:"text-xs font-medium text-secondary",children:["Exact model ",e.jsx("span",{className:"font-normal text-muted",children:"(optional)"})]}),e.jsx("input",{id:"research-model",list:"research-known-models",className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none disabled:cursor-not-allowed disabled:opacity-50",placeholder:M?`Default: ${M.model??M.defaultModel??M.catalog.defaultModel}`:"Choose a provider to select an exact model",value:c,disabled:!M,onChange:C=>u(C.target.value)}),e.jsx("datalist",{id:"research-known-models",children:(M?.catalog.knownModels??[]).map(C=>e.jsx("option",{value:C.id,children:C.displayName},C.id))})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 border-t border-default pt-4",children:[!H()&&e.jsxs(A,{type:"button",size:"sm",disabled:E.length===0||E.length>50||$||se.isPending,onClick:de,children:[e.jsx(Ps,{size:14}),se.isPending?"Starting research…":`Run ${E.length||""} research ${E.length===1?"query":"queries"}`]}),e.jsx("p",{className:"text-xs leading-5 text-muted",children:"Saved to research history. Nothing is added to tracked queries."})]}),$&&e.jsx("p",{className:"rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2 text-sm text-caution",children:"Configure an API provider in Settings before starting research. Browser engines are not available for this workflow."})]})]}),e.jsxs(te,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Saved research batches"})]}),R.isFetching&&e.jsx(Z,{tone:"neutral",children:"Loading"})]}),v.length===0?e.jsx("p",{className:"mt-4 text-sm text-muted",children:"No research batches yet. Add one or more questions to begin."}):e.jsx("div",{className:"mt-4 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[680px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Run"}),e.jsx("th",{children:"Model"}),e.jsx("th",{children:"Location"}),e.jsx("th",{children:"Progress"}),e.jsx("th",{children:"Status"})]})}),e.jsx("tbody",{children:v.map(C=>e.jsxs("tr",{className:p===C.id?"bg-bg-elevated/40":void 0,children:[e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-left font-medium text-heading hover:text-link focus:outline-none focus:underline",onClick:()=>m(C.id),children:$u(C.createdAt)})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:C.provider}),e.jsx("span",{className:"font-mono text-[11px] text-muted",children:C.requestedModel??C.resolvedModel})]}),e.jsx("td",{className:"text-secondary",children:C.location?.label??"No location"}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[C.completedQueries+C.failedQueries,"/",C.totalQueries]}),e.jsx("td",{children:e.jsx(Z,{tone:Ai(C.status),children:C.status})})]},C.id))})]})})]})]}),e.jsx(Cu,{detail:O,isLoading:D.isFetching})]})}function Cu({detail:t,isLoading:s}){const[n,a]=l.useState(null);l.useEffect(()=>{a(t?.queries[0]?.id??null)},[t?.id]);const r=t?.queries.find(i=>i.id===n)??t?.queries[0]??null;return e.jsxs(te,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Results"}),e.jsx("h3",{children:t?`Research run ${Tu(t.id)}`:"Choose a research batch"})]}),t&&e.jsx(Z,{tone:Ai(t.status),children:t.status})]}),t?e.jsxs("div",{className:"mt-4 grid gap-4 xl:grid-cols-[minmax(0,1.15fr)_minmax(320px,0.85fr)]",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[680px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"})]})}),e.jsx("tbody",{children:t.queries.map(i=>e.jsxs("tr",{className:r?.id===i.id?"bg-bg-elevated/40":void 0,children:[e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-left font-medium text-heading hover:text-link focus:outline-none focus:underline",onClick:()=>a(i.id),children:i.query})}),e.jsx("td",{children:e.jsx(Z,{tone:Pu(i.status),children:i.status})}),e.jsx("td",{children:e.jsx(Z,{tone:i.answerMentioned===!0?"positive":i.answerMentioned===!1?"neutral":i.status===xs.failed?"negative":"caution",children:i.answerMentioned===null?i.status===xs.failed?"Unavailable":"Pending":i.answerMentioned?"Mentioned":"Not mentioned"})}),e.jsx("td",{children:e.jsx(Z,{tone:i.citationState==="cited"?"positive":i.citationState==="not-cited"?"neutral":i.status===xs.failed?"negative":"caution",children:i.citationState===null?i.status===xs.failed?"Unavailable":"Pending":i.citationState==="cited"?"Cited":"Not cited"})})]},i.id))})]})}),e.jsx(ku,{query:r,isLoading:s})]}):e.jsx("p",{className:"mt-4 text-sm text-muted",children:"Select a saved batch to inspect each answer and its source links."})]})}function ku({query:t,isLoading:s}){return t?e.jsxs("div",{className:"space-y-4 border-t border-default pt-4 xl:border-t-0 xl:border-l xl:pl-4 xl:pt-0",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Selected query"}),e.jsx("p",{className:"mt-1 text-sm font-medium leading-6 text-heading",children:t.query})]}),t.error?e.jsx("div",{className:"rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:t.error}):t.answerText?e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Answer"}),e.jsx("p",{className:"mt-1 whitespace-pre-wrap text-sm leading-6 text-secondary",children:t.answerText})]}):e.jsx("p",{className:"text-sm text-muted",children:t.status===xs.failed?"This query did not return an answer.":"The answer will appear here when this query finishes."}),t.namedCompetitors.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Named in answer"}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:t.namedCompetitors.map(n=>e.jsx("span",{className:"mention-chip mention-chip--competitor",children:n},n))})]}),t.citedCompetitorDomains.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Cited competitor domains"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:"Cited as a source, not merely named in the answer."}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:t.citedCompetitorDomains.map(n=>e.jsx("span",{className:"mention-chip mention-chip--competitor",children:n.replace(/^www\./,"")},n))})]}),t.groundingSources.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Source links"}),e.jsx("ul",{className:"mt-2 space-y-1",children:t.groundingSources.map((n,a)=>{const r=us(n.uri),i=n.title||n.uri;return e.jsxs("li",{className:"flex min-w-0 items-start gap-1.5 text-sm",children:[r?e.jsx("a",{href:r,target:"_blank",rel:"noopener noreferrer",className:"truncate text-secondary hover:text-link focus:outline-none focus:underline",children:i}):e.jsx("span",{className:"truncate text-secondary",children:i}),r&&e.jsx(yc,{className:"mt-0.5 size-3 shrink-0 text-muted","aria-hidden":"true"})]},`${n.uri}-${a}`)})})]})]}):e.jsx("p",{className:"text-sm text-muted",children:s?"Loading saved answers…":"Select a query to inspect its answer."})}function Au(t){const s=new Set;return t.split(/\r?\n/).map(n=>n.trim()).filter(n=>{const a=n.toLocaleLowerCase();return!n||s.has(a)?!1:(s.add(a),!0)})}function $u(t){const s=new Date(t);return Number.isNaN(s.valueOf())?t:new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(s)}function Tu(t){return t.length>8?t.slice(0,8):t}function Ai(t){return t===Ys.completed?"positive":t===Ys.partial?"caution":t===Ys.failed?"negative":"neutral"}function Pu(t){return t===xs.completed?"positive":t===xs.failed?"negative":"neutral"}async function Ru(t){await ze(t,"researchRuns")}const Sa=new Set(["queued","seeding","probing"]);function Lu({projectName:t}){const[s,n]=l.useState("find");return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Query discovery"}),e.jsx("h2",{children:"Discover or research queries"})]})}),e.jsxs("div",{className:"inline-flex rounded-md border border-default bg-surface p-1",role:"tablist","aria-label":"Query discovery workflow",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":s==="find",className:`rounded px-3 py-1.5 text-sm font-medium transition-colors ${s==="find"?"bg-bg-elevated text-heading shadow-sm":"text-muted hover:text-strong"}`,onClick:()=>n("find"),children:"Find queries"}),e.jsx("button",{type:"button",role:"tab","aria-selected":s==="research",className:`rounded px-3 py-1.5 text-sm font-medium transition-colors ${s==="research"?"bg-bg-elevated text-heading shadow-sm":"text-muted hover:text-strong"}`,onClick:()=>n("research"),children:"Research queries"})]}),e.jsx("div",{className:"mt-4",children:s==="find"?e.jsx(Iu,{projectName:t}):e.jsx(Su,{projectName:t})})]})}function Iu({projectName:t}){const s=as(),[n,a]=l.useState(null),[r,i]=l.useState(""),[c,u]=l.useState("100"),o=Ne({...Vo({client:V,path:{name:t},query:{limit:"10"}}),refetchInterval:x=>x.state.data?.some(M=>Sa.has(M.status))?3e3:!1}),h=o.data??[];l.useEffect(()=>{!n&&h[0]&&a(h[0].id)},[n,h]);const p=h.find(x=>x.id===n)??null,m=Ne({...Wo({client:V,path:{name:t,id:n??""}}),enabled:!!n,refetchInterval:p&&Sa.has(p.status)?3e3:!1}),g=m.data??null,k=Ne({...Yo({client:V,path:{name:t,id:n??""}}),enabled:!!(n&&p?.status==="completed")}),R=en({mutationFn:()=>{const x={},$=r.trim();$&&(x.icpDescription=$);const M=Number.parseInt(c,10);return Number.isFinite(M)&&M>0&&(x.maxProbes=M),Jo(t,x)},onSuccess:async x=>{a(x.sessionId),i(""),await kr(s,t,x.sessionId),xe({title:"Discovery started",detail:`Run ${na(x.sessionId)} is testing questions your customers might ask.`,tone:"neutral",dedupeKey:`discovery:start:${x.sessionId}`,dedupeMode:"replace"})},onError:x=>{xe({title:"Discovery failed to start",detail:x instanceof Error?x.message:"Could not start discovery.",tone:"negative"})}}),v=en({mutationFn:x=>{if(!n)throw new Error("Select a completed discovery session first.");return Xo(t,n,x)},onSuccess:async x=>{await kr(s,t,x.sessionId),s.invalidateQueries({queryKey:Xr({client:V})}),s.invalidateQueries({predicate:$=>Array.isArray($.queryKey)&&$.queryKey[0]==="projects"&&$.queryKey.length>1}),xe({title:"Queries added",detail:qu(x),tone:"positive",dedupeKey:`discovery:promote:${x.sessionId}`,dedupeMode:"replace"})},onError:x=>{xe({title:"Could not add queries",detail:x instanceof Error?x.message:"Could not add queries from this run.",tone:"negative"})}}),j=g??p,D=k.data??null,O=(D?.queriesByBucket.cited.length??0)+(D?.queriesByBucket.aspirational.length??0),E=l.useMemo(()=>(g?.probes??[]).slice(0,30),[g?.probes]);async function F(){try{const x=await o.refetch();if(x.error)throw x.error;const $=x.data?.length??0;xe({title:"Discovery sessions refreshed",detail:`${$} recent session${$===1?"":"s"} loaded.`,tone:"positive",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}catch(x){xe({title:"Discovery refresh failed",detail:x instanceof Error?x.message:"Could not reload discovery sessions.",tone:"negative",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}}return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 1"}),e.jsx("h2",{children:"Generate and check questions"}),e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-secondary",children:H()?"Generate customer questions and check whether your site is already visible.":"Generate customer questions, check current visibility, then choose what to track."})]}),e.jsxs(A,{type:"button",variant:"outline",size:"sm",disabled:o.isFetching,onClick:()=>{F()},children:[e.jsx(tn,{className:`size-3.5 ${o.isFetching?"animate-spin":""}`,"aria-hidden":"true"}),"Refresh"]})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[360px_minmax(0,1fr)]",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs(te,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 1"}),e.jsx("h3",{children:"Describe your customer"})]}),e.jsx(Z,{tone:"neutral",children:"Runs on Gemini"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm text-secondary",children:"Who is your ideal customer?"}),e.jsx("textarea",{className:"mt-1 min-h-24 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:"e.g. Small e-commerce stores that want AI-powered customer support. Leave blank to use the customer profile saved on this project.",value:r,onChange:x=>i(x.target.value)})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm text-secondary",children:"How many questions to test"}),e.jsx("input",{className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",inputMode:"numeric",value:c,onChange:x=>u(x.target.value)}),e.jsx("span",{className:"mt-1 block text-sm text-secondary",children:"More questions means broader coverage but a longer run. 100 is a good default."})]}),!H()&&e.jsxs(A,{type:"button",size:"sm",disabled:R.isPending,onClick:()=>R.mutate(),children:[e.jsx(Ps,{size:14}),R.isPending?"Starting…":"Find queries"]})]})]}),e.jsxs(te,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Recent runs"})]}),o.isFetching&&e.jsx(Z,{tone:"neutral",children:"Loading"})]}),h.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No discovery runs yet. Describe your customer above to start your first one."}):e.jsx("div",{className:"space-y-2",children:h.map(x=>e.jsxs("button",{type:"button",className:`w-full rounded-md border px-3 py-2 text-left transition-colors ${n===x.id?"border-mono-600 bg-bg-elevated/70":"border-default bg-bg/40 hover:border-strong hover:bg-bg-elevated/40"}`,onClick:()=>a(x.id),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:na(x.id)}),e.jsx(Z,{tone:Cr(x.status),children:x.status})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-sm text-secondary",children:[e.jsxs("span",{children:["Cited queries ",x.citedCount??0]}),e.jsxs("span",{children:["Worth tracking ",x.aspirationalCount??0]}),e.jsxs("span",{children:["Skip ",x.wastedCount??0]})]})]},x.id))})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(te,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Run detail"}),e.jsx("h3",{children:j?na(j.id):"No run selected"})]}),j&&e.jsx(Z,{tone:Cr(j.status),children:j.status})]}),j?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(es,{label:"Questions tested",value:j.probeCount??0}),e.jsx(es,{label:"Cited queries",value:j.citedCount??0,tone:"positive"}),e.jsx(es,{label:"Worth tracking",value:j.aspirationalCount??0,tone:"caution"}),e.jsx(es,{label:"Skip",value:j.wastedCount??0,tone:"negative"})]}),j.error&&e.jsx("div",{className:"rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:j.error}),j.warning&&e.jsx("div",{className:"rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2 text-sm text-caution",children:j.warning}),j.icpDescription&&e.jsxs("div",{className:"rounded-md border border-default bg-surface px-3 py-2",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Customer profile"}),e.jsx("p",{className:"mt-1 text-sm text-neutral",children:j.icpDescription})]}),j.competitorMap.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-sm font-medium text-secondary",children:"Sites that keep getting cited"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:j.competitorMap.slice(0,8).map(x=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[x.domain," ",e.jsx("span",{className:"text-muted",children:x.hits})]},x.domain))})]})]}):e.jsx("p",{className:"text-sm text-secondary",children:"Start a run above, or pick one from Recent runs to see its progress."})]}),j?.status==="completed"&&e.jsxs(te,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 2"}),e.jsx("h3",{children:"Choose queries to track"})]}),!H()&&e.jsxs(A,{type:"button",size:"sm",disabled:v.isPending||O===0,onClick:()=>v.mutate(void 0),children:[e.jsx(ii,{size:14}),v.isPending?"Adding…":"Add recommended queries"]})]}),k.isLoading?e.jsx("p",{className:"text-sm text-muted",children:"Loading recommendations…"}):D?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(es,{label:"Queries to add",value:O,tone:"positive"}),e.jsx(es,{label:"Cited queries",value:D.queriesByBucket.cited.length,tone:"positive"}),e.jsx(es,{label:"Worth tracking",value:D.queriesByBucket.aspirational.length,tone:"caution"}),e.jsx(es,{label:"Skip",value:D.queriesByBucket["wasted-surface"].length,tone:"negative"})]}),e.jsx("p",{className:"text-sm leading-6 text-secondary",children:"Adds Cited queries and Worth tracking queries, plus recurring competitor sites. Skip items remain available for review only."}),D.suggestedCompetitors.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-secondary",children:"Competitor sites that will be added"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:D.suggestedCompetitors.map(x=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[x.domain," ",e.jsx("span",{className:"text-muted",children:x.hits})]},x.domain))})]})]}):e.jsx("p",{className:"text-sm text-muted",children:"No recommendations available for this run."})]}),e.jsxs(te,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"All results"}),e.jsx("h3",{children:"Every question we tested"})]}),m.isFetching&&e.jsx(Z,{tone:"neutral",children:"Loading"})]}),E.length===0?e.jsx("p",{className:"text-sm text-muted",children:"Results show up here once the run starts testing questions."}):e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Question"}),e.jsx("th",{children:"Result"}),e.jsx("th",{children:"Sites cited"})]})}),e.jsx("tbody",{children:E.map(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:x.query}),e.jsx("td",{children:e.jsx(Z,{tone:Du(x.bucket),children:Mu(x.bucket)})}),e.jsx("td",{className:"text-secondary",children:x.citedDomains.length>0?x.citedDomains.slice(0,3).join(", "):"-"})]},x.id))})]})})]})]})]})]})}function es({label:t,value:s,tone:n="neutral"}){const a=n==="positive"?"text-positive":n==="caution"?"text-caution":n==="negative"?"text-negative":"text-heading";return e.jsxs("div",{className:"rounded-md border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:t}),e.jsx("p",{className:`mt-1 text-2xl font-semibold tabular-nums ${a}`,children:s})]})}function Cr(t){return t==="completed"?"positive":t==="failed"?"negative":Sa.has(t)?"caution":"neutral"}function Du(t){return t==="cited"?"positive":t==="aspirational"?"caution":t==="wasted-surface"?"negative":"neutral"}const Eu={cited:"Cited queries",aspirational:"Worth tracking","wasted-surface":"Skip"};function Mu(t){return t?Eu[t]:"Not classified"}function na(t){return t.length>8?t.slice(0,8):t}function qu(t){const s=t.promoted.queries.length,n=t.promoted.competitors.length,a=t.skipped.queries.length+t.skipped.competitors.length;return`${s} quer${s===1?"y":"ies"} and ${n} competitor${n===1?"":"s"} added${a>0?`; ${a} already tracked`:""}.`}async function kr(t,s,n){await Promise.all([ze(t,"discovery"),t.invalidateQueries({queryKey:Zo({client:V})})])}const Ou=100,aa=12,Ku=[];function Fu(t){return mi(t.url)}function ra(t){return t>=70?"positive":t>=40?"caution":"negative"}function ia(t){return t>=70?"text-positive-400":t>=40?"text-caution-400":"text-negative-400"}function _u(t){return t==="pass"?"positive":t==="partial"?"caution":"negative"}function kn(t){return t>=70?"Pass":t>=40?"Partial":"Fail"}function Uu(t){return Da(Et(String(t)))}function Bu(t){return ns(Et(String(t)))}function Gu({projectName:t,projectId:s}){const[n,a]=l.useState(!1),[r,i]=l.useState(null),[c,u]=l.useState(null),[o,h]=l.useState(!1),p=l.useRef(null),m=Ne(el({client:V,path:{name:t},...c?{query:{runId:c}}:{}})),g=Ne(tl({client:V,path:{name:t},query:{limit:30}})),k=Ne(sl({client:V,path:{name:t},query:{limit:Ou,sort:"score-asc",...c?{runId:c}:{}}})),R=Ne({...Zr({client:V,path:{name:t},query:{kind:fs["site-audit"],limit:10}}),refetchOnWindowFocus:"always",refetchInterval:N=>N.state.data?.some(Q=>Q.status==="queued"||Q.status==="running")?3e3:1e4}),v=nl(),j=l.useSyncExternalStore(Hr,Ln,Ln),D=Object.values(j.runs).find(N=>N.kind===fs["site-audit"]&&N.projectId===s),O=R.data??[],E=O.find(N=>N.status==="queued"||N.status==="running"),F=O.at(-1),x=v.isPending||!!D||!!E,$=v.isPending?"starting":E?.status??D?.lastAnnouncedStatus,M=l.useCallback(async()=>{const N=await Promise.all([m.refetch(),g.refetch(),k.refetch()]),G=N.find(Q=>Q.error);if(G?.error)throw G.error;return N[0]},[k.refetch,m.refetch,g.refetch]);l.useEffect(()=>{c||!F||F.status!=="completed"&&F.status!=="partial"||m.data?.runId===F.id||p.current===F.id||(p.current=F.id,M().catch(N=>{xe({title:"Technical AEO auto-refresh failed",detail:N instanceof Error?N.message:"Could not load the completed audit.",tone:"negative",dedupeKey:`technical-aeo:auto-refresh:${t}`,dedupeMode:"replace"})}))},[F?.id,F?.status,t,M,m.data?.runId,c]);const se=async()=>{h(!0);try{const N=await M();xe({title:"Technical AEO refreshed",detail:x?"The audit is still running. This view will refresh again when it finishes.":N.data?.hasData?`Latest score is ${N.data.aggregateScore}/100 from ${N.data.pagesAudited} audited page${N.data.pagesAudited===1?"":"s"}.`:"No audit data yet. Run an audit to crawl the sitemap.",tone:N.data?.hasData?"positive":"caution",dedupeKey:`technical-aeo:refresh:${t}`,dedupeMode:"replace"})}catch(N){xe({title:"Technical AEO refresh failed",detail:N instanceof Error?N.message:"Could not reload technical audit data.",tone:"negative",dedupeKey:`technical-aeo:refresh:${t}`,dedupeMode:"replace"})}finally{h(!1)}},de=()=>v.mutate({projectName:t,projectId:s}),C=$==="running"?"Audit running":$==="queued"?"Audit queued":"Starting audit",b=m.data,_=k.data?.pages??Ku,w=(b?.pagesErrored??0)>0,B=n&&w,oe=l.useMemo(()=>B?_.filter(N=>N.status==="error"):_,[_,B]),ee=sn({rows:oe,getSearchText:Fu}),U=b?b.pagesAudited>_.length:!1;if(l.useEffect(()=>{a(!1),i(null)},[c]),m.isLoading)return e.jsx("p",{className:"supporting-copy mt-6",children:"Loading technical audit…"});if(!b||!b.hasData)return e.jsxs(te,{className:"surface-card mt-6 p-8 text-center",children:[e.jsx(Ac,{className:"mx-auto mb-3 h-8 w-8 text-muted","aria-hidden":"true"}),e.jsx("h2",{className:"text-base font-semibold text-heading",children:"No technical audit yet"}),e.jsx("p",{className:"supporting-copy mx-auto mt-2 max-w-md",children:"A technical AEO audit crawls your sitemap and scores every page for structured data, AI-readable content, crawler access, freshness, and more, then rolls it up into one site score."}),!H()&&e.jsx("div",{className:"mt-5 flex items-center justify-center gap-3",children:e.jsxs(A,{type:"button",onClick:de,disabled:x,children:[x?e.jsx(ga,{className:"mr-1.5 h-4 w-4 motion-safe:animate-spin","aria-hidden":"true"}):e.jsx(Ps,{className:"mr-1.5 h-4 w-4","aria-hidden":"true"}),x?C:"Run first audit"]})}),x?e.jsx("p",{className:"mt-3 text-xs text-muted",role:"status","aria-live":"polite",children:"The dashboard will refresh automatically when the audit finishes."}):null,e.jsxs("p",{className:"mt-3 text-xs text-faint",children:["Or from the CLI: ",e.jsxs("code",{className:"text-secondary",children:["canonry technical-aeo run ",t," --wait"]})]})]});const pe=b.deltaScore==null?null:`${b.deltaScore>=0?"+":""}${b.deltaScore} vs previous`,le=b.trend==="up"?"positive":b.trend==="down"?"negative":"neutral",K=g.data?.points??[],q=K.map(N=>({runId:N.runId,date:N.auditedAt,score:N.aggregateScore})),y=c!==null,Y=_.filter(N=>N.status==="success");function me(N){const G=[];for(const Q of Y){const T=Q.factors.find(ne=>ne.id===N);T&&T.score<70&&G.push({url:Q.url,score:T.score})}return G.sort((Q,T)=>Q.score-T.score)}return e.jsxs("div",{className:"mt-6",children:[e.jsxs("section",{className:"surface-card flex flex-wrap items-start justify-between gap-6 rounded-lg border border-default bg-surface p-6",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:y?"Technical AEO history":"Technical AEO"}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-baseline gap-3",children:[e.jsx("span",{className:`text-4xl font-semibold tabular-nums ${ia(b.aggregateScore)}`,children:b.aggregateScore}),e.jsx("span",{className:"text-lg text-muted",children:"/ 100"}),e.jsx(Z,{tone:ra(b.aggregateScore),children:kn(b.aggregateScore)}),pe?e.jsx(Z,{tone:le,children:pe}):null,x?e.jsx(Z,{tone:"neutral",children:C}):null]}),e.jsxs("p",{className:"supporting-copy mt-2 tabular-nums",children:[b.pagesDiscovered," URL",b.pagesDiscovered===1?"":"s"," in sitemap · ",b.pagesAudited," audited · ",b.pagesSkipped," skipped · ",b.pagesErrored," errored"]}),e.jsxs("p",{className:"mt-1 flex flex-wrap items-center gap-x-1.5 text-xs text-muted",children:[e.jsx("span",{className:"text-faint",children:"Sitemap:"}),e.jsx("a",{href:b.sitemapUrl??"#",target:"_blank",rel:"noreferrer",className:"max-w-[22rem] truncate text-secondary underline decoration-mono-700 underline-offset-2 hover:text-strong",children:b.sitemapUrl}),e.jsx(Ke,{text:"Every audit re-reads this sitemap, so pages you add or remove are picked up on the next run. Discovered/audited counts and the score reflect the sitemap at the time of the latest run. Override it with `canonry technical-aeo run <project> --sitemap-url <url>`."})]}),b.auditedAt?e.jsxs("p",{className:"mt-0.5 text-xs text-faint",children:["Audited ",new Date(b.auditedAt).toLocaleString()]}):null,x?e.jsx("p",{className:"mt-1 text-xs text-muted",role:"status","aria-live":"polite",children:"Results refresh automatically when this audit finishes."}):null]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[K.length>1?e.jsxs("select",{"aria-label":"View a Technical AEO audit",value:c??"",onChange:N=>u(N.target.value||null),className:"min-h-11 rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:[e.jsx("option",{value:"",children:"Latest audit"}),[...K].reverse().slice(1).map(N=>e.jsxs("option",{value:N.runId,children:[new Date(N.auditedAt).toLocaleDateString()," · ",N.aggregateScore,"/100"]},N.runId))]}):null,e.jsxs(A,{type:"button",variant:"outline",size:"sm",onClick:()=>{se()},disabled:o,children:[e.jsx(tn,{className:`mr-1.5 h-4 w-4 ${o?"motion-safe:animate-spin":""}`,"aria-hidden":"true"}),o?"Refreshing…":"Refresh"]}),!H()&&e.jsxs(A,{type:"button",size:"sm",onClick:de,disabled:x,children:[x?e.jsx(ga,{className:"mr-1.5 h-4 w-4 motion-safe:animate-spin","aria-hidden":"true"}):e.jsx(Ps,{className:"mr-1.5 h-4 w-4","aria-hidden":"true"}),x?C:"Re-run audit"]})]})]}),q.length>=2?e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h2",{children:"Site score over time"})]}),e.jsxs("div",{className:"mt-3 h-56",children:[e.jsxs("p",{className:"sr-only",children:["Technical AEO scores range from ",Math.min(...q.map(N=>N.score))," to ",Math.max(...q.map(N=>N.score))," across ",q.length," audits. Use the audit selector to inspect a previous scorecard."]}),e.jsx("div",{className:"h-full","aria-hidden":"true",children:e.jsx(Rs,{width:"100%",height:"100%",children:e.jsxs(Ls,{data:q,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Ea,{stroke:Ia,vertical:!1}),e.jsx(Is,{dataKey:"date",tick:vt,tickLine:!1,axisLine:{stroke:Wt},tickFormatter:Uu,minTickGap:24}),e.jsx(Ds,{domain:[0,100],ticks:[0,25,50,75,100],tick:vt,tickLine:!1,axisLine:!1,width:32}),e.jsx(Es,{...ps,cursor:{stroke:Wt,strokeWidth:1},labelFormatter:Bu,formatter:N=>[`${N}/100`,"Site score"]}),e.jsx(Ma,{type:"monotone",dataKey:"score",name:"score",stroke:Ht.positive,strokeWidth:2.5,dot:{r:2.5,fill:Ht.positive,strokeWidth:0},isAnimationActive:!1})]})})})]})]}):null,e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Scorecard"}),e.jsxs("h2",{className:"inline-flex items-center gap-1.5",children:["Ranking factors",e.jsx(Ke,{text:"Each factor is scored 0–100 per page (via the aeo-audit engine), then averaged across all successfully-audited pages. Pass ≥70, partial 40–69, fail <40. Expand a row to see which pages fall short and how to fix it."})]})]}),e.jsx("div",{className:"evidence-table-wrap mt-3",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Factor"}),e.jsx("th",{className:"text-right",children:"Weight"}),e.jsx("th",{className:"text-right",children:"Avg"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Pass / Partial / Fail"})]})}),e.jsx("tbody",{children:b.factors.map(N=>{const G=r===N.id,Q=b.crossCuttingIssues.find(ce=>ce.factorId===N.id),T=G?me(N.id):[],ne=N.pagesPartial+N.pagesFailing;return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:G?"bg-surface":void 0,children:[e.jsx("td",{children:e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 text-left font-medium text-strong hover:text-primary","aria-expanded":G,onClick:()=>i(G?null:N.id),children:[G?e.jsx(La,{className:"h-3.5 w-3.5 shrink-0 text-muted","aria-hidden":"true"}):e.jsx(Pa,{className:"h-3.5 w-3.5 shrink-0 text-muted","aria-hidden":"true"}),N.name]})}),e.jsxs("td",{className:"text-right tabular-nums text-muted",children:[N.weight,"%"]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:N.avgScore}),e.jsx("td",{children:e.jsx(Z,{tone:_u(N.status),children:kn(N.avgScore)})}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[e.jsx("span",{className:"text-positive-400",children:N.pagesPassing})," / ",e.jsx("span",{className:"text-caution-400",children:N.pagesPartial})," / ",e.jsx("span",{className:"text-negative-400",children:N.pagesFailing})]})]}),G?e.jsx("tr",{className:"bg-surface",children:e.jsx("td",{colSpan:5,className:"px-4 pb-4 pt-0",children:e.jsxs("div",{className:"space-y-4 border-l border-base pl-4",children:[Q&&Q.topRecommendations.length>0?e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-1.5 text-muted",children:"How to fix"}),e.jsx("ul",{className:"space-y-1",children:Q.topRecommendations.map((ce,Ae)=>e.jsxs("li",{className:"flex gap-2 text-sm text-neutral",children:[e.jsx("span",{className:"select-none text-faint",children:"→"}),e.jsx("span",{children:ce})]},Ae))})]}):ne===0?e.jsx("p",{className:"text-sm text-muted",children:"Every audited page passes this factor."}):null,ne>0?e.jsxs("div",{children:[e.jsxs("p",{className:"eyebrow eyebrow-soft mb-1.5 text-muted",children:["Pages below pass (",ne,")"]}),e.jsx("ul",{className:"space-y-1",children:T.slice(0,aa).map(ce=>e.jsxs("li",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:`w-8 shrink-0 text-right tabular-nums ${ia(ce.score)}`,children:ce.score}),e.jsx("a",{href:ce.url,target:"_blank",rel:"noreferrer",className:"truncate text-neutral hover:text-heading",title:ce.url,children:ce.url})]},ce.url))}),T.length>aa?e.jsxs("p",{className:"mt-1 text-xs text-faint",children:["+ ",T.length-aa," more below pass"]}):null,U?e.jsxs("p",{className:"mt-1 text-xs text-faint",children:["Showing the worst ",_.length," audited pages."]}):null]}):null]})})}):null]},N.id)})})]})})]}),b.crossCuttingIssues.length>0?e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Opportunities"}),e.jsxs("h2",{className:"inline-flex items-center gap-1.5",children:["Prioritized fixes",e.jsx(Ke,{text:"Factors scoring below pass across the most pages, ranked by site-wide impact. Fixing one of these typically lifts many pages at once."})]})]}),e.jsx("div",{className:"mt-3 divide-y divide-mono-800/60 overflow-hidden rounded-lg border border-default",children:b.crossCuttingIssues.map(N=>e.jsxs("div",{className:"p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:N.factorName}),e.jsx(Z,{tone:ra(N.avgScore),children:kn(N.avgScore)}),e.jsxs("span",{className:"text-xs tabular-nums text-muted",children:["avg ",N.avgScore," · affects ",N.affectedPages," of ",N.totalPages," pages (",N.affectedPct,"%)"]})]}),N.topRecommendations.length>0?e.jsx("ul",{className:"mt-2 space-y-1",children:N.topRecommendations.map((G,Q)=>e.jsxs("li",{className:"flex gap-2 text-sm text-secondary",children:[e.jsx("span",{className:"select-none text-faint",children:"→"}),e.jsx("span",{children:G})]},Q))}):null]},N.factorId))})]}):null,e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Pages"}),e.jsx("h2",{children:"Per-page breakdown"})]}),w?e.jsxs("div",{className:"segmented",role:"group","aria-label":"Filter pages",children:[e.jsxs("button",{type:"button",onClick:()=>{a(!1),ee.setPage(1)},"aria-pressed":!B,className:`segmented-option min-h-11 tabular-nums ${B?"":"segmented-option-active"}`,children:["All ",b.pagesAudited]}),e.jsxs("button",{type:"button",onClick:()=>{a(!0),ee.setPage(1)},"aria-pressed":B,className:`segmented-option min-h-11 tabular-nums ${B?"segmented-option-active text-negative":""}`,children:["Errors ",b.pagesErrored]})]}):null]}),_.length>0?e.jsx(Ss,{value:ee.query,onChange:ee.setQuery,label:"Filter audited page URLs",placeholder:"Filter page URL or query parameters",className:"mt-3 max-w-md"}):null,ee.totalRows===0?e.jsx("p",{className:"supporting-copy mt-3",children:ee.hasQuery?"No pages match this filter.":"No pages recorded."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"evidence-table-wrap mt-3",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-right",children:"Score"}),e.jsx("th",{children:"Status"}),e.jsx("th",{className:"w-full",children:"URL"})]})}),e.jsx("tbody",{children:ee.rows.map(N=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-right tabular-nums",children:N.status==="error"?e.jsxs("span",{className:"inline-flex items-center gap-1 text-negative-400",children:[e.jsx(al,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"err"]}):e.jsx("span",{className:ia(N.overallScore),children:N.overallScore})}),e.jsx("td",{children:N.status==="error"?e.jsx(Z,{tone:"negative",children:"Error"}):e.jsx(Z,{tone:ra(N.overallScore),children:kn(N.overallScore)})}),e.jsx("td",{className:"w-full max-w-0",children:e.jsx("a",{href:N.url,target:"_blank",rel:"noreferrer",className:"block truncate text-neutral hover:text-heading",title:N.status==="error"?N.error??N.url:N.url,children:e.jsx(Js,{value:N.url,headLength:54,tailLength:20,title:N.status==="error"?N.error??N.url:N.url})})})]},N.url))})]})}),e.jsx(gs,{page:ee.page,pageSize:ee.pageSize,visibleRows:ee.rows.length,totalRows:ee.totalRows,onPageChange:ee.setPage,itemLabel:ee.hasQuery?"matches":"rows"}),U?e.jsxs("p",{className:"mt-2 text-xs text-faint",children:["Showing the worst ",_.length," of ",b.pagesAudited," audited pages."]}):null]})]})]})}function Ar(t){return`${(t*100).toFixed(1)}%`}function Qu({projectName:t}){const[s,n]=l.useState("changes"),[a,r]=l.useState(null),[i,c]=l.useState(null),u=Ne({...rl({client:V,path:{name:t},query:{limit:30}}),enabled:s==="health"}),o=Ne({...Zr({client:V,path:{name:t},query:{kind:"answer-visibility",limit:100}}),enabled:s==="compare"}),h=(o.data??[]).filter(j=>(j.status==="completed"||j.status==="partial")&&j.trigger!=="probe").reverse(),p=i??h[0]?.id??"",m=a??h.find(j=>j.id!==p)?.id??"",g=!!(m&&p&&m!==p),k=Ne({...il({client:V,path:{name:t},query:{run1:m,run2:p}}),enabled:s==="compare"&&g}),R=u.data??[],v=k.data?.diff.filter(j=>j.changed||j.visibilityChanged)??[];return e.jsxs("div",{className:"mt-6",children:[e.jsx("div",{className:"filter-row",role:"tablist","aria-label":"Project history views",children:[["changes","Changes"],["health","Coverage history"],["compare","Compare runs"]].map(([j,D])=>e.jsx("button",{type:"button",role:"tab","aria-selected":s===j,className:`filter-chip ${s===j?"filter-chip-active":""}`,onClick:()=>n(j),children:D},j))}),s==="changes"?e.jsx(Nc,{projectName:t}):null,s==="health"?e.jsxs("section",{className:"mt-6","aria-labelledby":"coverage-history-heading",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Query evidence"}),e.jsx("h2",{id:"coverage-history-heading",children:"Mention and citation coverage"}),e.jsx("p",{className:"supporting-copy mt-1",children:"Independent answer-text mentions and source citations across completed sweeps."})]}),u.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Loading coverage history…"}):null,!u.isLoading&&R.length===0?e.jsxs(te,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No coverage history yet"}),e.jsx("p",{children:"Complete an answer visibility sweep to create the first snapshot."})]}):null,R.length>0?e.jsx("div",{className:"evidence-table-wrap mt-4",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date"}),e.jsx("th",{className:"text-right",children:"Mentioned"}),e.jsx("th",{className:"text-right",children:"Mention coverage"}),e.jsx("th",{className:"text-right",children:"Cited"}),e.jsx("th",{className:"text-right",children:"Citation coverage"})]})}),e.jsx("tbody",{children:R.map(j=>e.jsxs("tr",{children:[e.jsx("td",{className:"whitespace-nowrap tabular-nums text-secondary",children:new Date(j.createdAt).toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[j.mentionedPairs,"/",j.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:Ar(j.overallMentionRate)}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[j.citedPairs,"/",j.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:Ar(j.overallCitedRate)})]},j.id))})]})}):null]}):null,s==="compare"?e.jsxs("section",{className:"mt-6","aria-labelledby":"compare-runs-heading",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Evidence diff"}),e.jsx("h2",{id:"compare-runs-heading",children:"Compare answer visibility runs"}),e.jsx("p",{className:"supporting-copy mt-1",children:"See which tracked queries changed mention or citation state between two sweeps."})]}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"text-xs text-muted",children:["Earlier run",e.jsx("select",{value:m,onChange:j=>r(j.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:h.map(j=>e.jsx("option",{value:j.id,children:new Date(j.createdAt).toLocaleString()},j.id))})]}),e.jsxs("label",{className:"text-xs text-muted",children:["Later run",e.jsx("select",{value:p,onChange:j=>c(j.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:h.map(j=>e.jsx("option",{value:j.id,children:new Date(j.createdAt).toLocaleString()},j.id))})]})]}),o.isLoading||k.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Comparing runs…"}):null,!o.isLoading&&h.length<2?e.jsxs(te,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"Two completed sweeps are required"}),e.jsx("p",{children:"Run another answer visibility sweep before comparing historical evidence."})]}):null,k.data&&v.length===0?e.jsxs(te,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No mention or citation changes"}),e.jsx("p",{children:"The selected sweeps have the same states for every comparable tracked query."})]}):null,v.length>0?e.jsx("div",{className:"evidence-table-wrap mt-4",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Citation"}),e.jsx("th",{children:"Mention"})]})}),e.jsx("tbody",{children:v.map(j=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:j.query??"Archived query"}),e.jsx("td",{children:e.jsxs(Z,{tone:j.changed?"caution":"neutral",children:[j.run1State??"none"," → ",j.run2State??"none"]})}),e.jsx("td",{children:e.jsxs(Z,{tone:j.visibilityChanged?"caution":"neutral",children:[j.run1MentionState??"none"," → ",j.run2MentionState??"none"]})})]},j.queryId??j.query??"unknown"))})]})}):null]}):null]})}const Xs="{target.label}";function Je(t,s){return t<s?-1:t>s?1:0}function Pt(t){return[...new Set(t)].sort(Je)}function $r(t){if(!(!t||Object.keys(t).length===0))return Object.fromEntries(Object.entries(t).sort(([s],[n])=>Je(s,n)))}function As(t){return t.kind==="host"?{kind:"host",host:er(t.host)}:t.kind==="prefix"?{kind:"prefix",host:er(t.host),pathPrefix:ol(t.pathPrefix),pathCase:t.pathCase}:{kind:"exact",url:ll(t.url),pathCase:t.pathCase}}function Vt(t){const s=As(t);return s.kind==="host"?`host\0${s.host}`:s.kind==="prefix"?`prefix\0${s.host}\0${s.pathPrefix}\0${s.pathCase}`:`exact\0${s.url}\0${s.pathCase}`}function yt(t){const s=new Map;for(const a of t){const r=As(a);s.set(Vt(r),r)}const n=a=>{if(a.kind==="host")return{host:a.host,path:"",specificity:1};if(a.kind==="prefix")return{host:a.host,path:a.pathPrefix,specificity:2};const r=new URL(a.url);return{host:r.hostname,path:r.pathname,specificity:3}};return[...s.values()].sort((a,r)=>{const i=n(a),c=n(r);return Je(i.host,c.host)||c.specificity-i.specificity||Je(i.path,c.path)||Je(Vt(a),Vt(r))})}function oa(t,s){const n=yt(t),a=yt(s);return n.length===a.length&&n.every((r,i)=>Vt(r)===Vt(a[i]))}function Tr(t){const s=new URL(t);if(s.protocol!=="http:"&&s.protocol!=="https:")throw new Error("Discovery returned a non-HTTP URL");return As({kind:"prefix",host:s.hostname,pathPrefix:s.pathname||"/",pathCase:"insensitive"})}function Mt(t){return t==null?t:{label:t.label.trim(),city:t.city.trim(),region:t.region.trim(),country:t.country.trim(),...t.timezone?{timezone:t.timezone.trim()}:{}}}function $s(t){if(t===void 0)return"inherit";if(t===null)return"none";const s=Mt(t);return["location",s?.label,s?.city,s?.region,s?.country,s?.timezone??""].join("\0")}function zu(t){return`${t.targetKey}\0${t.queryId}\0${$s(t.context)}`}function Hu(t){const s=new Map;for(const n of t){const a={targetKey:n.targetKey.trim(),queryId:n.queryId.trim(),context:Mt(n.context)};s.set(zu(a),a)}return[...s.values()].sort((n,a)=>Je(n.targetKey,a.targetKey)||Je(n.queryId,a.queryId)||Je($s(n.context),$s(a.context)))}function On(t){const s=Pt(t.competitors??[]).map(n=>n.toLowerCase());return{stableKey:t.stableKey.trim(),label:t.label.trim(),targetKeys:Pt(t.targetKeys.map(n=>n.trim())),...s.length>0?{competitors:s}:{}}}function rt(t){return{schemaVersion:1,targets:[...t.targets].map(s=>({stableKey:s.stableKey.trim(),label:s.label.trim(),status:s.status,urls:yt(s.urls),aliases:Pt(s.aliases.map(n=>n.trim()).filter(Boolean)),...$r(s.metadata)?{metadata:$r(s.metadata)}:{}})).sort((s,n)=>Je(s.stableKey,n.stableKey)),exceptions:[...t.exceptions].map(s=>({...s,...s.targetKey?{targetKey:s.targetKey.trim()}:{},...s.duplicateOf?{duplicateOf:s.duplicateOf}:{}})).sort((s,n)=>Je(s.key,n.key)),coverageReviews:[...t.coverageReviews].map(s=>({targetKey:s.targetKey.trim(),existingUrls:yt(s.existingUrls),importedUrls:yt(s.importedUrls),previousStatus:s.previousStatus,resolution:s.resolution})).sort((s,n)=>Je(s.targetKey,n.targetKey)),querySets:[...t.querySets].map(s=>({key:s.key.trim(),label:s.label.trim(),queryIds:Pt(s.queryIds.map(n=>n.trim()).filter(Boolean)),context:Mt(s.context)})).sort((s,n)=>Je(s.key,n.key)),queryTemplates:[...t.queryTemplates].map(s=>({key:s.key.trim(),label:s.label.trim(),template:s.template.trim(),context:Mt(s.context)})).sort((s,n)=>Je(s.key,n.key)),assignments:Hu(t.assignments),groups:[...t.groups].map(On).sort((s,n)=>Je(s.stableKey,n.stableKey))}}function Ca(t,s,n){return`${t}\0${s}\0${n}`}function ka(t){const s=t.proposed.map(a=>({stableKey:a.stableKey,label:a.label,status:"proposed",urls:yt([Tr(a.primaryUrl),...a.aliasCoverageUrls.map(Tr)]),aliases:[a.label]})),n=[];for(const a of["excluded","shared","unmatched"])for(const r of t[a])n.push({key:Ca(a,r.reason,r.url),bucket:a,url:r.url,canonicalUrl:r.canonicalUrl,reason:r.reason,status:"unreviewed"});for(const a of t.diagnostics)n.push({key:Ca("diagnostic",a.kind,a.url),bucket:"diagnostic",url:a.url,canonicalUrl:a.canonicalUrl,reason:a.kind,...a.duplicateOf?{duplicateOf:a.duplicateOf}:{},status:"unreviewed"});return rt({targets:s,exceptions:n,coverageReviews:[],querySets:[],queryTemplates:[],assignments:[],groups:[]})}function Vu(t,s){const n=ka(s),a=new Map(n.targets.map(g=>[g.stableKey,g])),r=new Map(t.targets.map(g=>[g.stableKey,g])),i=new Map(t.coverageReviews.map(g=>[g.targetKey,g])),c=[],u=[],o=[],h=(g,k,R="url-not-rediscovered")=>{const v=i.get(g.stableKey),j=v?.resolution==="keep-existing"?v.existingUrls:v?.resolution==="replace-with-imported"?v.importedUrls:v?yt([...v.existingUrls,...v.importedUrls]):null,D=v!==void 0&&oa(v.importedUrls,k)&&j!==null&&oa(g.urls,j);if(D&&v.resolution==="replace-with-imported")return{...g,status:v.previousStatus,urls:yt(k)};const O=v?.resolution==="pending"||D?v.existingUrls:g.urls;if(oa(O,k))return{...g,status:D?v.previousStatus:g.status,urls:yt(k)};const E=D?v:{targetKey:g.stableKey,existingUrls:yt(O),importedUrls:yt(k),previousStatus:v?.resolution==="pending"?v.previousStatus:g.status,resolution:"pending"};o.push(E);const F=new Set(k.map(Vt));for(const x of E.existingUrls){if(F.has(Vt(x)))continue;const $=Yu(x);u.push({key:Ca("diagnostic",R,`${g.stableKey}:${$}`),bucket:"diagnostic",url:$,canonicalUrl:$,reason:R,targetKey:g.stableKey,status:"unreviewed"})}return E.resolution==="keep-existing"?{...g,status:E.previousStatus,urls:E.existingUrls}:{...g,status:E.previousStatus==="confirmed"?"proposed":E.previousStatus,urls:yt([...E.existingUrls,...E.importedUrls])}};for(const g of n.targets){const k=r.get(g.stableKey);if(!k){c.push(g);continue}c.push(h(k,g.urls))}for(const g of t.targets)a.has(g.stableKey)||c.push(h(g,[],"target-not-rediscovered"));const p=new Map(t.exceptions.map(g=>[g.key,g])),m=[...n.exceptions,...u].map(g=>p.get(g.key)?.status==="reviewed"?{...g,status:"reviewed"}:g);return rt({...t,targets:c,exceptions:m,coverageReviews:o})}function Wu(t,s,n){const a=new Set(Pt(s.map(h=>h.trim()).filter(Boolean)));if(a.size===0)throw new Error("Choose at least one Target coverage review");const r=new Map(t.coverageReviews.map(h=>[h.targetKey,h])),i=[...a].filter(h=>!r.has(h));if(i.length>0)throw new Error(`Target coverage review not found: ${i.join(", ")}`);const c=t.targets.map(h=>{if(!a.has(h.stableKey))return h;const p=r.get(h.stableKey);return{...h,status:p.previousStatus,urls:n==="keep-existing"?p.existingUrls:p.importedUrls}}),u=t.coverageReviews.map(h=>a.has(h.targetKey)?{...h,resolution:n}:h),o=t.exceptions.map(h=>h.targetKey&&a.has(h.targetKey)&&(h.reason==="url-not-rediscovered"||h.reason==="target-not-rediscovered")?{...h,status:"reviewed"}:h);return rt({...t,targets:c,coverageReviews:u,exceptions:o})}function Yu(t){return t.kind==="exact"?t.url:t.kind==="prefix"?`https://${t.host}${t.pathPrefix}`:`https://${t.host}`}function Pr(t){const s=[];for(const n of t.targetQuerySelections)for(const a of n.queryIds)s.push({targetKey:n.targetKey,queryId:a,context:n.context});return rt({targets:t.targets.map(n=>({stableKey:n.stableKey,label:n.label,status:"confirmed",urls:n.urls,aliases:n.aliases,...n.metadata?{metadata:n.metadata}:{}})),exceptions:[],coverageReviews:[],querySets:[],queryTemplates:[],assignments:s,groups:t.groups})}function Ka(t,s,n){if(!t.targets.some(r=>r.stableKey===s))throw new Error(`Target not found: ${s}`);const a=t.targets.map(r=>r.stableKey!==s?r:n(r));return rt({...t,targets:a})}function Ju(t,s){return Ka(t,s,n=>({...n,status:"confirmed"}))}function Rr(t,s){return Ka(t,s,n=>({...n,status:"rejected"}))}function Xu(t,s,n){const a=Vt(n);return Ka(t,s,r=>({...r,urls:r.urls.filter(i=>Vt(i)!==a)}))}function $i(t,s){const n=new Set(s),a=[...n].filter(i=>!t.exceptions.some(c=>c.key===i));if(a.length>0)throw new Error(`Review item not found: ${a.join(", ")}`);const r=t.exceptions.map(i=>n.has(i.key)?{...i,status:"reviewed"}:i);return rt({...t,exceptions:r})}function Zu(t){return $i(t,t.exceptions.map(s=>s.key))}function em(t,s){const n={key:s.key.trim(),label:s.label.trim(),queryIds:Pt(s.queryIds.map(a=>a.trim()).filter(Boolean)),context:Mt(s.context)};if(!n.key||!n.label)throw new Error("Query set name is required");return rt({...t,querySets:[...t.querySets.filter(a=>a.key!==n.key),n]})}function tm(t,s){const n=Pt(s.targetKeys.map(u=>u.trim()).filter(Boolean)),a=Pt(s.queryIds.map(u=>u.trim()).filter(Boolean)),r=new Set(t.targets.filter(u=>u.status==="confirmed").map(u=>u.stableKey)),i=n.filter(u=>!r.has(u));if(i.length>0)throw new Error(`Confirm targets before assigning queries: ${i.join(", ")}`);if(n.length===0||a.length===0)throw new Error("Choose targets and queries before applying");const c=n.flatMap(u=>a.map(o=>({targetKey:u,queryId:o,context:Mt(s.context)})));return rt({...t,assignments:[...t.assignments,...c]})}function sm(t,s,n){const a=t.querySets.find(r=>r.key===s);if(!a)throw new Error(`Query set not found: ${s}`);return tm(t,{targetKeys:n,queryIds:a.queryIds,context:a.context})}function nm(t,s){const n=new Set(s);return rt({...t,assignments:t.assignments.filter(a=>!n.has(a.targetKey))})}function Lr(t,s){const n={key:s.key.trim(),label:s.label.trim(),template:s.template.trim(),context:Mt(s.context)};if(!n.key||!n.label||!n.template)throw new Error("Query template name and text are required");return rt({...t,queryTemplates:[...t.queryTemplates.filter(a=>a.key!==n.key),n]})}function am(t,s,n){const a=t.queryTemplates.find(i=>i.key===s);if(!a)throw new Error(`Query template not found: ${s}`);if(!a.template.includes(Xs))throw new Error(`Template must include ${Xs}`);const r=new Map(t.targets.map(i=>[i.stableKey,i]));return Pt(n).map(i=>{const c=r.get(i);if(!c||c.status!=="confirmed")throw new Error(`Confirm target before generating queries: ${i}`);return{targetKey:i,queryText:a.template.replaceAll(Xs,c.label).replace(/\s+/g," ").trim(),context:Mt(a.context)}})}function rm(t,s,n){const a=new Map(n.map(c=>[c.query,c.id])),r=Pt(s.filter(c=>!a.has(c.queryText)).map(c=>c.queryText));if(r.length>0)throw new Error(`Generated queries were not saved: ${r.join(", ")}`);const i=s.map(c=>({targetKey:c.targetKey,queryId:a.get(c.queryText),context:Mt(c.context)}));return rt({...t,assignments:[...t.assignments,...i]})}function im(t,s){const n=On(s);if(!n.stableKey||!n.label)throw new Error("Group name is required");return rt({...t,groups:[...t.groups.filter(a=>a.stableKey!==n.stableKey),n]})}function Ti(t){const s=[],n=t.targets.filter(o=>o.status==="confirmed"),a=new Set(n.map(o=>o.stableKey)),r=new Map(t.targets.map(o=>[o.stableKey,o.status])),i=t.groups.filter(o=>o.targetKeys.length===0||o.targetKeys.some(h=>r.get(h)!=="rejected")),c=t.targets.filter(o=>o.status!=="rejected").map(o=>o.stableKey).concat(i.map(o=>o.stableKey)),u=new Set;for(const o of c){if(u.has(o)){s.push({severity:"error",code:"duplicate-stable-key",message:"Each target and group needs a unique identity."});break}u.add(o)}n.length===0&&s.push({severity:"error",code:"no-confirmed-targets",message:"Confirm at least one target before publishing."});for(const o of t.targets)o.status==="proposed"&&s.push({severity:"error",code:"target-review-required",message:`Confirm or reject ${o.label}.`,targetKey:o.stableKey}),o.status==="confirmed"&&o.urls.length===0&&s.push({severity:"error",code:"target-url-required",message:`${o.label} needs at least one URL.`,targetKey:o.stableKey});t.exceptions.some(o=>o.status==="unreviewed")&&s.push({severity:"error",code:"exception-review-required",message:"Review the URLs that were not added to targets."});for(const o of t.coverageReviews)o.resolution==="pending"&&r.get(o.targetKey)!=="rejected"&&s.push({severity:"error",code:"coverage-review-required",message:"Choose whether to keep existing URL coverage or replace it with the latest import.",targetKey:o.targetKey});for(const o of t.assignments)r.get(o.targetKey)!=="rejected"&&(a.has(o.targetKey)||s.push({severity:"error",code:"assignment-target-unavailable",message:"A query is assigned to a target that is not confirmed.",targetKey:o.targetKey}));for(const o of t.groups){o.targetKeys.length===0&&s.push({severity:"error",code:"group-target-required",message:`${o.label} needs at least one target.`});for(const h of o.targetKeys)r.get(h)!=="rejected"&&(a.has(h)||s.push({severity:"error",code:"group-target-unavailable",message:`${o.label} includes a target that is not confirmed.`,targetKey:h}))}for(const o of t.querySets)o.queryIds.length===0&&s.push({severity:"error",code:"query-set-empty",message:`${o.label} needs at least one query.`});for(const o of t.queryTemplates)o.template.includes(Xs)||s.push({severity:"error",code:"template-placeholder-required",message:`${o.label} must include ${Xs}.`});return s}function om(t){const s=rt(t),n=Ti(s);if(n.length>0)throw new Error(`This setup is not ready to publish: ${n.map(i=>i.message).join(" ")}`);const a=new Set(s.targets.filter(i=>i.status==="confirmed").map(i=>i.stableKey)),r=new Map;for(const i of s.assignments){if(!a.has(i.targetKey))continue;const c=`${i.targetKey}\0${$s(i.context)}`,u=r.get(c)??{targetKey:i.targetKey,queryIds:[],context:i.context};u.queryIds.push(i.queryId),r.set(c,u)}return{schemaVersion:1,targets:s.targets.filter(i=>i.status==="confirmed").map(i=>({stableKey:i.stableKey,label:i.label,urls:i.urls,aliases:i.aliases,...i.metadata?{metadata:i.metadata}:{}})),groups:s.groups.map(i=>On({...i,targetKeys:i.targetKeys.filter(c=>a.has(c))})).filter(i=>i.targetKeys.length>0),targetQuerySelections:[...r.values()].map(i=>({targetKey:i.targetKey,queryIds:Pt(i.queryIds),...i.context===void 0?{}:{context:i.context}})).sort((i,c)=>Je(i.targetKey,c.targetKey)||Je($s(i.context),$s(c.context)))}}function $t(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function An(t){return Array.isArray(t)&&t.every(s=>typeof s=="string")}function la(t){if(t!==void 0){if(t===null)return null;if(!$t(t))throw new Error("Invalid context");if(typeof t.label!="string"||typeof t.city!="string"||typeof t.region!="string"||typeof t.country!="string")throw new Error("Invalid context");if(t.timezone!==void 0&&typeof t.timezone!="string")throw new Error("Invalid context");return Mt({label:t.label,city:t.city,region:t.region,country:t.country,...typeof t.timezone=="string"?{timezone:t.timezone}:{}})}}function ca(t){if(!$t(t)||typeof t.kind!="string")throw new Error("Invalid target URL");if(t.kind==="host"&&typeof t.host=="string")return As({kind:"host",host:t.host});if(t.kind==="prefix"&&typeof t.host=="string"&&typeof t.pathPrefix=="string"&&(t.pathCase==="sensitive"||t.pathCase==="insensitive"))return As({kind:"prefix",host:t.host,pathPrefix:t.pathPrefix,pathCase:t.pathCase});if(t.kind==="exact"&&typeof t.url=="string"&&(t.pathCase==="sensitive"||t.pathCase==="insensitive"))return As({kind:"exact",url:t.url,pathCase:t.pathCase});throw new Error("Invalid target URL")}function lm(t){if(!$t(t)||t.schemaVersion!==1)throw new Error("Invalid version");if(!Array.isArray(t.targets)||!Array.isArray(t.exceptions)||!Array.isArray(t.querySets)||!Array.isArray(t.queryTemplates)||!Array.isArray(t.assignments)||!Array.isArray(t.groups)||t.coverageReviews!==void 0&&!Array.isArray(t.coverageReviews))throw new Error("Invalid collections");const s=t.targets.map(o=>{if(!$t(o)||typeof o.stableKey!="string"||typeof o.label!="string"||o.status!=="proposed"&&o.status!=="confirmed"&&o.status!=="rejected"||!Array.isArray(o.urls)||!An(o.aliases))throw new Error("Invalid target");let h;if(o.metadata!==void 0){if(!$t(o.metadata)||!Object.values(o.metadata).every(p=>typeof p=="string"))throw new Error("Invalid target metadata");h=o.metadata}return{stableKey:o.stableKey,label:o.label,status:o.status,urls:o.urls.map(ca),aliases:o.aliases,...h?{metadata:h}:{}}}),n=t.exceptions.map(o=>{if(!$t(o)||typeof o.key!="string"||o.bucket!=="shared"&&o.bucket!=="unmatched"&&o.bucket!=="excluded"&&o.bucket!=="diagnostic"||typeof o.url!="string"||o.canonicalUrl!==null&&typeof o.canonicalUrl!="string"||typeof o.reason!="string"||o.targetKey!==void 0&&typeof o.targetKey!="string"||o.duplicateOf!==void 0&&typeof o.duplicateOf!="string"||o.status!=="unreviewed"&&o.status!=="reviewed")throw new Error("Invalid review item");return{key:o.key,bucket:o.bucket,url:o.url,canonicalUrl:o.canonicalUrl,reason:o.reason,...typeof o.targetKey=="string"?{targetKey:o.targetKey}:{},...typeof o.duplicateOf=="string"?{duplicateOf:o.duplicateOf}:{},status:o.status}}),a=(t.coverageReviews??[]).map(o=>{if(!$t(o)||typeof o.targetKey!="string"||!Array.isArray(o.existingUrls)||!Array.isArray(o.importedUrls)||o.previousStatus!=="proposed"&&o.previousStatus!=="confirmed"&&o.previousStatus!=="rejected"||o.resolution!=="pending"&&o.resolution!=="keep-existing"&&o.resolution!=="replace-with-imported")throw new Error("Invalid coverage review");return{targetKey:o.targetKey,existingUrls:o.existingUrls.map(ca),importedUrls:o.importedUrls.map(ca),previousStatus:o.previousStatus,resolution:o.resolution}}),r=t.querySets.map(o=>{if(!$t(o)||typeof o.key!="string"||typeof o.label!="string"||!An(o.queryIds))throw new Error("Invalid query set");return{key:o.key,label:o.label,queryIds:o.queryIds,context:la(o.context)}}),i=t.queryTemplates.map(o=>{if(!$t(o)||typeof o.key!="string"||typeof o.label!="string"||typeof o.template!="string")throw new Error("Invalid query template");return{key:o.key,label:o.label,template:o.template,context:la(o.context)}}),c=t.assignments.map(o=>{if(!$t(o)||typeof o.targetKey!="string"||typeof o.queryId!="string")throw new Error("Invalid query assignment");return{targetKey:o.targetKey,queryId:o.queryId,context:la(o.context)}}),u=t.groups.map(o=>{if(!$t(o)||typeof o.stableKey!="string"||typeof o.label!="string"||!An(o.targetKeys)||o.competitors!==void 0&&!An(o.competitors))throw new Error("Invalid group");return On({stableKey:o.stableKey,label:o.label,targetKeys:o.targetKeys,...o.competitors?{competitors:o.competitors}:{}})});return rt({targets:s,exceptions:n,coverageReviews:a,querySets:r,queryTemplates:i,assignments:c,groups:u})}function cm(t){return JSON.stringify(rt(t))}function Ir(t){try{return lm(JSON.parse(t))}catch(s){const n=s instanceof Error?s.message:"unknown error";throw new Error(`The saved setup could not be read: ${n}`)}}const dm=["Import","Targets","Queries","Review & publish","Report"],Aa=new Map,um=50,Ws="__project_default__",$a="__no_location__";function Ta(t){return`canonry:portfolio-draft:${t}`}function mm(t){const s=Ta(t);if(typeof window>"u")return null;try{const n=window.localStorage.getItem(s)??Aa.get(s);return n?Ir(n):null}catch{const n=Aa.get(s);if(!n)return null;try{return Ir(n)}catch{return null}}}function hm(t,s){const n=cm(s);Aa.set(Ta(t),n);try{window.localStorage.setItem(Ta(t),n)}catch{}}function ds(t,s){return t instanceof Error?t.message:s}function da(t,s){if(t!==Ws)return t===$a?null:s.find(n=>n.label===t)}function Dr(t){return t===void 0?"Project default":t===null?"No location":t.label}function xm(t,s){return t===void 0||s===void 0||t===null||s===null?t===s:t.label===s.label}function pm(t){return{"invalid-authoring":"Plan details need attention","duplicate-identity":"Duplicate name or URL","unknown-target":"Target not found","unknown-query":"Tracked query not found","invalid-project-context":"Location is not available","unowned-target-url":"URL is outside this project","owned-competitor":"Competitor domain belongs to this project","target-query-context-conflict":"Query location conflict","target-url-ownership-tie":"Target URL conflict","target-alias-cross-target-collision":"Target name conflict","target-alias-project-brand-collision":"Project name conflict","target-alias-prefix-overlap":"Similar Target names"}[t]}function $n(t){return t.kind==="exact"?t.url:t.kind==="prefix"?`https://${t.host}${t.pathPrefix}`:`https://${t.host}`}function Tn(t,s,n=!0){return n?s.complete?t.rate!==null?`${Math.round(t.rate*100)}%`:t.reason==="incomplete"||t.reason==="evidence-incomplete"?`Incomplete: ${s.executed}/${s.expected}`:t.reason==="no-population"?"No tracked queries":"N/A":`Incomplete: ${s.executed}/${s.expected}`:"No stored result"}function Er(t,s=!0){return s?t.complete?`${t.executed}/${t.expected}`:`Incomplete: ${t.executed}/${t.expected}`:"Not measured"}function gm(t){return t==="assigned"?"positive":t==="external"?"neutral":t==="invalid"?"negative":"caution"}function fm(t){return{assigned:"Assigned",sibling:"Sibling",ownedUnmapped:"Owned, not mapped",external:"External",ambiguous:"Ambiguous",invalid:"Invalid URL"}[t]}function bm({activePlan:t,report:s,isLoading:n,isError:a,onRetry:r}){const[i,c]=l.useState(null);if(a&&!t)return e.jsxs("div",{className:"rounded-md border border-negative-800/40 bg-negative-950/20 p-4 text-sm text-negative",children:[e.jsx("p",{children:"Could not load measurement setup."}),r?e.jsx(A,{className:"mt-3",size:"sm",variant:"outline",onClick:r,children:"Try again"}):null]});if(!t)return e.jsx("p",{className:"text-sm text-secondary",children:"Publish a measurement plan before opening the report."});if(n&&!s)return e.jsx("div",{className:"h-28 animate-pulse rounded-md bg-surface-subtle","aria-label":"Loading report"});if(a&&!s)return e.jsxs("div",{className:"rounded-md border border-negative-800/40 bg-negative-950/20 p-4 text-sm text-negative",children:[e.jsxs("p",{children:["Could not load the report for revision ",t.revision,"."]}),r?e.jsx(A,{className:"mt-3",size:"sm",variant:"outline",onClick:r,children:"Try again"}):null]});if(!s)return e.jsxs("p",{className:"text-sm text-secondary",children:["No stored measurement result is available for revision ",t.revision,"."]});if(s.revision!==t.revision)return e.jsxs("div",{className:"rounded-md border border-caution-800/40 bg-caution-950/20 p-4 text-sm text-caution",children:[e.jsxs("p",{children:["The saved report does not match active revision ",t.revision,"."]}),r?e.jsx(A,{className:"mt-3",size:"sm",variant:"outline",onClick:r,children:"Refresh report"}):null]});const u=i?s.evidence.filter(p=>p.usageEdgeType==="target"&&p.matchedTargetIds.includes(i)):[],o=s.evidence.filter(p=>p.usageEdgeType==="target"&&(p.classification==="sibling"||p.classification==="ambiguous")),h=s.run!==null;return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Z,{tone:"neutral",children:["Revision ",s.revision]}),s.run?e.jsx(Z,{tone:s.run.status==="completed"?"positive":"caution",children:s.run.status==="completed"?"Complete":"Partial result"}):e.jsx(Z,{tone:"neutral",children:"No stored result"}),a?e.jsx("span",{className:"text-sm text-caution",children:"Refresh failed. Showing saved data."}):null]}),s.groups.length>0?e.jsxs("section",{"aria-labelledby":"group-report-title",children:[e.jsx("div",{className:"section-head",children:e.jsx("h3",{id:"group-report-title",children:"Reporting groups"})}),e.jsx("div",{className:"overflow-x-auto rounded-md border border-default",children:e.jsxs("table",{className:"evidence-table min-w-[780px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Targets"}),e.jsx("th",{children:"Completeness"}),e.jsx("th",{children:"Answer coverage"}),e.jsx("th",{children:"Target coverage"}),e.jsx("th",{children:"Competitor share of voice"})]})}),e.jsx("tbody",{children:s.groups.map(p=>{const m=p.sov.domains.filter(g=>!g.own);return e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:p.label}),e.jsx("td",{className:"tabular-nums text-secondary",children:p.targetIds.length}),e.jsx("td",{className:"tabular-nums text-secondary",children:Er(p.completeness,h)}),e.jsx("td",{className:"text-secondary",children:Tn(p.answerCoverage,p.completeness,h)}),e.jsx("td",{className:"text-secondary",children:Tn(p.targetCoverage,p.completeness,h)}),e.jsx("td",{className:"text-secondary",children:m.length===0?"No competitors":m.map(g=>`${g.domain} ${g.presentIn===null?"N/A":`${Math.round(g.presentIn/g.of*100)}%`}`).join(", ")})]},p.id)})})]})})]}):null,e.jsx("div",{className:"overflow-x-auto rounded-md border border-default",children:e.jsxs("table",{className:"evidence-table min-w-[760px]",children:[e.jsx("caption",{className:"sr-only",children:"Measurement results by Target"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Target"}),e.jsx("th",{children:"Completeness"}),e.jsx("th",{children:"Citation coverage"}),e.jsx("th",{children:"Mention coverage"}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Evidence"})})]})}),e.jsx("tbody",{children:s.targets.map(p=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:p.label}),e.jsx("td",{className:"tabular-nums text-secondary",children:Er(p.completeness,h)}),e.jsx("td",{className:"tabular-nums text-secondary",children:Tn(p.citationCoverage,p.completeness,h)}),e.jsx("td",{className:"tabular-nums text-secondary",children:Tn(p.mentionCoverage,p.completeness,h)}),e.jsx("td",{className:"text-right",children:e.jsxs(A,{size:"sm",variant:"outline",onClick:()=>c(p.id),children:["Show URLs matched to ",p.label]})})]},p.id))})]})}),o.length>0?e.jsxs("section",{"aria-labelledby":"evidence-review-title",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{id:"evidence-review-title",children:"Evidence requiring review"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Ambiguous evidence is not credited to a Target. Sibling evidence remains visible for context."})]})}),e.jsx(Mr,{evidence:o})]}):null,i?e.jsxs("section",{"aria-live":"polite","aria-labelledby":"target-evidence-title",children:[e.jsx("div",{className:"section-head",children:e.jsx("h3",{id:"target-evidence-title",children:"Matched URL evidence"})}),u.length>0?e.jsx(Mr,{evidence:u}):e.jsx("p",{className:"text-sm text-secondary",children:"No cited URL matched this Target."})]}):null]})}function Mr({evidence:t}){return e.jsx("div",{className:"overflow-x-auto rounded-md border border-default",children:e.jsxs("table",{className:"evidence-table min-w-[880px]",children:[e.jsx("caption",{className:"sr-only",children:"Stored citation evidence"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Engine"}),e.jsx("th",{children:"Tracked query"}),e.jsx("th",{children:"Location"}),e.jsx("th",{children:"Source URL"})]})}),e.jsx("tbody",{children:t.map(s=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx(Z,{tone:gm(s.classification),children:fm(s.classification)})}),e.jsx("td",{className:"text-secondary",children:s.provider}),e.jsx("td",{className:"text-secondary",children:s.queryText}),e.jsx("td",{className:"text-secondary",children:s.location??"No location"}),e.jsx("td",{className:"max-w-md break-all text-secondary",children:s.sourceUrl})]},`${s.observationId}:${s.usageEdgeId}:${s.sourceUrl}`))})]})})}function jm(t){const{projectName:s,locations:n,queries:a,isQueryLoading:r,isQueryError:i,onRetryQueries:c,activePlan:u,isPlanLoading:o,isPlanError:h,onRetryPlan:p,report:m,isReportLoading:g,isReportError:k,onRetryReport:R,onDiscover:v,onCreateQueries:j,onCompilePlan:D,onDiffPlan:O,onPublishPlan:E}=t,[F]=l.useState(()=>{const f=mm(s),W=!o&&u?Pr(u.plan):null;return{draft:f??W,source:f?"local":W?"active":"empty",activeKey:u&&!o?`${u.revision}:${u.checksum}`:null}}),[x,$]=l.useState(F.draft),[M,se]=l.useState(F.source),[de,C]=l.useState(()=>F.source==="active"?4:F.draft?1:0),[b,_]=l.useState(""),[w,B]=l.useState(""),[oe,ee]=l.useState(""),[U,pe]=l.useState(""),[le,K]=l.useState("/{slug}"),[q,y]=l.useState(""),[Y,me]=l.useState(null),[N,G]=l.useState(null),[Q,T]=l.useState(null),[ne,ce]=l.useState(null),[Ae,Fe]=l.useState(""),[Te,Me]=l.useState([]),[Se,ct]=l.useState([]),[Xe,_e]=l.useState([]),[X,Pe]=l.useState(""),[Ie,ht]=l.useState(Ws),[L,ve]=l.useState(""),[De,Rt]=l.useState(Ws),[Re,Yt]=l.useState([]),[dt,Be]=l.useState(""),[ut,qt]=l.useState(""),[Nt,xt]=l.useState([]),[Ze,Ot]=l.useState(null),[S,re]=l.useState(null),[he,it]=l.useState(null),[$e,Jt]=l.useState(u),rs=l.useRef(F.activeKey),is=l.useRef(null),pt=l.useRef("none"),Ye=l.useMemo(()=>[...new Map([...a,...Nt].map(W=>[W.id,W])).values()],[a,Nt]),I=l.useMemo(()=>new Map(Ye.map(f=>[f.id,f.query])),[Ye]),ge=x?.targets.filter(f=>f.status==="confirmed")??[],ue=new Set(ge.map(f=>f.stableKey)),ie=Te.filter(f=>ue.has(f)),Ee=new Set(ie),Os=x?.assignments.some(f=>Ee.has(f.targetKey))??!1,Ge=x?.targets.filter(f=>f.status==="proposed").map(f=>f.stableKey)??[],ot=x?.exceptions.filter(f=>f.status==="unreviewed")??[],Kt=ot.slice(0,20),Lt=x?.coverageReviews.filter(f=>f.resolution==="pending")??[],cn=new Set(Lt.map(f=>f.targetKey)),wt=Te.filter(f=>cn.has(f)),os=l.useMemo(()=>{if(!x)return[];const f=Ae.trim().toLocaleLowerCase();return x.targets.filter(W=>!f||`${W.label} ${W.stableKey}`.toLocaleLowerCase().includes(f))},[x,Ae]),Ft=os.slice(0,um),gt=new Set(Te),dn=new Set(Xe),lt=Ze?.checks.filter(f=>f.severity==="fail")??[],He=S?.ok?S.diff:null,Ks=x?Ti(x):[],St=x&&Ks.length===0?om(x):null,ft=St?JSON.stringify(St):null,It=u?`${u.revision}:${u.checksum}`:"none";is.current=ft,pt.current=It;function Ve(f){se("local"),$(f)}l.useEffect(()=>{x&&M==="local"&&!o&&!h&&hm(s,x)},[x,M,h,o,s]),l.useEffect(()=>{if(o||h||M==="local")return;const f=u?`${u.revision}:${u.checksum}`:null;!u||rs.current===f||($(Pr(u.plan)),se("active"),rs.current=f,C(4))},[u,M,h,o]),l.useEffect(()=>{Jt(u)},[u]),l.useEffect(()=>{Ot(null),re(null),it(null)},[It,x]);function Kn(f,W){Me(ae=>W?[...new Set([...ae,f])]:ae.filter(Le=>Le!==f))}function Fs(f){Me(W=>[...new Set([...W,...f])])}async function et(){if(!(!b.trim()||!w.trim()||!oe.trim())){T("discover"),ce(null);try{const f=await v({sitemapUrl:b.trim(),rule:{primary:{host:w.trim(),pathTemplate:oe.trim()},...U.trim()&&le.trim()?{aliases:[{host:U.trim(),pathTemplate:le.trim()}]}:{},...q.trim()?{excludedSlugPatterns:[...new Set(q.split(/[,\n]+/).map(Ue=>Ue.trim()).filter(Boolean))].map(Ue=>({kind:"exact",value:Ue}))}:{}}}),W=x?Vu(x,f):ka(f),ae=new Map((x?.targets??[]).map(Ue=>[Ue.stableKey,Ue])),Le=new Map(ka(f).targets.map(Ue=>[Ue.stableKey,Ue])),qe=[...Le.keys()].filter(Ue=>!ae.has(Ue)).length,_t=x?[...ae.entries()].filter(([Ue,xn])=>{const pn=Le.get(Ue);if(!pn)return!0;const Un=xn.urls.map($n).sort().join("\0"),_s=pn.urls.map($n).sort().join("\0");return Un!==_s}).length:0;me(f),G({newTargets:qe,changedTargets:_t,reviewItems:W.exceptions.filter(Ue=>Ue.status==="unreviewed").length}),Ve(W),Me([]),Fe("")}catch(f){ce(ds(f,"Could not import this sitemap."))}finally{T(null)}}}function un(f){x&&(Ve(Te.reduce((W,ae)=>f==="confirmed"?Ju(W,ae):Rr(W,ae),x)),Me([]))}function mn(f){if(!(!x||wt.length===0)){ce(null);try{Ve(Wu(x,wt,f)),Me([])}catch(W){ce(ds(W,"Could not resolve these URL coverage changes."))}}}function Fn(){if(!x||!X.trim()||Xe.length===0)return;const f=X.trim().toLocaleLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||`set-${x.querySets.length+1}`,W=da(Ie,n);Ve(em(x,{key:f,label:X.trim(),queryIds:[...new Set(Xe)],context:W})),Pe(""),_e([])}function _n(f){if(!(!x||ie.length===0)){ce(null);try{Ve(sm(x,f,ie))}catch(W){ce(ds(W,"Could not apply this query set."))}}}function ls(){if(!x||!L.trim()||!L.includes("{target.label}"))return;const f=da(De,n);if(ie.length!==0){ce(null);try{const W=Lr(x,{key:"current-template",label:"Current template",template:L.trim(),context:f});Ve(W),Yt(am(W,"current-template",ie).map(ae=>({targetKey:ae.targetKey,text:ae.queryText,context:ae.context})))}catch(W){ce(ds(W,"Could not preview these query drafts."))}}}async function bs(){if(!(!x||Re.length===0)){T("create"),ce(null);try{const f=await j(Re.map(ae=>ae.text));xt(ae=>[...ae,...f]);const W=Lr(x,{key:"current-template",label:"Current template",template:L.trim(),context:da(De,n)});Ve(rm(W,Re.map(ae=>({targetKey:ae.targetKey,queryText:ae.text,context:ae.context})),f)),Yt([]),ve("")}catch(f){ce(ds(f,"Could not create the reviewed queries."))}finally{T(null)}}}function hn(){if(!x||!dt.trim()||ie.length===0)return;const f=`group-${dt.trim().toLocaleLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}`;Ve(im(x,{stableKey:f,label:dt.trim(),targetKeys:[...ie],...ut.trim()?{competitors:[...new Set(ut.split(/[\s,]+/).map(W=>W.trim()).filter(Boolean))]}:{}})),Be(""),qt("")}async function be(){if(!St||!ft)return;const f=ft,W=It;T("check"),ce(null);try{const[ae,Le]=await Promise.all([D(St),O(St)]);if(is.current!==f||pt.current!==W)return;Ot(ae),re(Le),it({fingerprint:f,activeKey:W})}catch(ae){ce(ds(ae,"Could not check this plan."))}finally{T(ae=>ae==="check"?null:ae)}}async function Ct(){if(!(!St||!ft||!Ze?.ok||lt.length>0)){if(!he||he.fingerprint!==ft||he.activeKey!==It){ce("Check the current draft again before publishing.");return}T("publish"),ce(null);try{const f=await E(St,u?.revision??null);Jt(f.active)}catch(f){ce(ds(f,"Could not publish this plan."))}finally{T(null)}}}return o?e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h2",{children:"Portfolio setup"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Loading the active measurement setup."})]})}),e.jsx("div",{className:"h-32 animate-pulse rounded-md bg-surface-subtle","aria-label":"Loading measurement setup"})]}):h?e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{children:"Portfolio setup"})}),e.jsxs("div",{className:"rounded-md border border-negative-800/40 bg-negative-950/20 p-4 text-sm text-negative",children:[e.jsx("p",{children:"Could not load measurement setup. Setup and publishing are unavailable until this is resolved."}),p?e.jsx(A,{className:"mt-3",size:"sm",variant:"outline",onClick:p,children:"Try again"}):null]})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("h2",{children:"Portfolio setup"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Define Targets, URL coverage, and the tracked queries each Target measures."})]}),$e?e.jsxs(Z,{tone:"positive",children:["Active revision ",$e.revision]}):e.jsx(Z,{tone:"caution",children:"Draft"})]}),e.jsx("nav",{"aria-label":"Portfolio setup steps",className:"overflow-x-auto border-b border-default",children:e.jsx("ol",{className:"flex min-w-max gap-6",children:dm.map((f,W)=>e.jsx("li",{children:e.jsx("button",{type:"button",disabled:Q==="check"||Q==="publish",className:`min-h-11 border-b-2 px-1 text-sm font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400 ${de===W?"border-strong text-heading":"border-transparent text-secondary hover:text-primary"}`,onClick:()=>C(W),children:f})},f))})}),ne?e.jsx("p",{role:"alert",className:"rounded-md border border-negative-800/40 bg-negative-950/20 p-3 text-sm text-negative",children:ne}):null,de===0?e.jsxs("section",{"aria-labelledby":"portfolio-import-title",className:"space-y-5",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{id:"portfolio-import-title",children:"Import sitemap"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Canonry applies your URL rule and returns reviewable Target candidates. Nothing is published automatically."})]})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Bt,{label:"Sitemap URL",value:b,onChange:_,placeholder:"https://locations.example/sitemap.xml"}),e.jsx(Bt,{label:"Primary host",value:w,onChange:B,placeholder:"locations.example"}),e.jsx(Bt,{label:"Target path pattern",value:oe,onChange:ee,placeholder:"/locations/{slug}"}),e.jsx(Bt,{label:"Alias host (optional)",value:U,onChange:pe,placeholder:"directory.example"}),U?e.jsx(Bt,{label:"Alias path pattern",value:le,onChange:K,placeholder:"/{slug}"}):null,e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm font-medium text-secondary",children:"Excluded slugs (optional)"}),e.jsx("textarea",{"aria-label":"Excluded slugs (optional)",className:"mt-1 min-h-20 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:q,onChange:f=>y(f.target.value),placeholder:`region-page, archive-page
|
|
7
|
+
one value per line or comma-separated`})]})]}),e.jsx(A,{disabled:Q==="discover"||!b.trim()||!w.trim()||!oe.trim(),onClick:()=>{et()},children:Q==="discover"?"Importing…":"Import sitemap"}),Y?e.jsxs("div",{className:"border-t border-default pt-4","aria-live":"polite",children:[N?e.jsxs("p",{className:"mb-3 rounded-md border border-info-500/25 bg-info-950/20 p-3 text-sm text-secondary",children:["Import changes: ",N.newTargets," new ",N.newTargets===1?"Target":"Targets",", ",N.changedTargets," with URL changes, and ",N.reviewItems," review ",N.reviewItems===1?"item":"items","."]}):null,e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(Z,{tone:"caution",children:[Y.proposed.length," proposed ",Y.proposed.length===1?"Target":"Targets"]}),Y.shared.length>0?e.jsxs(Z,{tone:"caution",children:[Y.shared.length," shared ",Y.shared.length===1?"URL needs":"URLs need"," review"]}):null,Y.unmatched.length>0?e.jsxs(Z,{tone:"neutral",children:[Y.unmatched.length," unmatched"]}):null,Y.excluded.length>0?e.jsxs(Z,{tone:"neutral",children:[Y.excluded.length," excluded"]}):null,Y.diagnostics.length>0?e.jsxs(Z,{tone:"caution",children:[Y.diagnostics.length," import ",Y.diagnostics.length===1?"issue":"issues"]}):null]}),e.jsx(A,{className:"mt-4",variant:"secondary",onClick:()=>C(1),children:"Continue to Targets"})]}):x?e.jsxs("div",{className:"border-t border-default pt-4",children:[e.jsx("p",{className:"text-sm text-secondary",children:"A saved draft is ready to review."}),e.jsx(A,{className:"mt-3",variant:"secondary",onClick:()=>C(1),children:"Continue to Targets"})]}):null]}):null,de===1?e.jsxs("section",{"aria-labelledby":"portfolio-targets-title",className:"space-y-4",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("h3",{id:"portfolio-targets-title",children:"Targets"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Confirm the units you want to measure. URL coverage stays attached to each Target."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(A,{size:"sm",variant:"outline",onClick:()=>Fs(os.map(f=>f.stableKey)),children:"Select all matching Targets"}),e.jsx(A,{size:"sm",variant:"ghost",disabled:Te.length===0,onClick:()=>Me([]),children:"Clear selection"}),e.jsx(A,{size:"sm",variant:"outline",disabled:Te.length===0,onClick:()=>un("confirmed"),children:"Confirm selected Targets"}),e.jsx(A,{size:"sm",variant:"ghost",disabled:Te.length===0,onClick:()=>un("rejected"),children:"Reject selected"}),e.jsxs(A,{size:"sm",variant:"ghost",disabled:Ge.length===0,onClick:()=>{Ve(Ge.reduce((f,W)=>Rr(f,W),x)),Me([])},children:["Reject remaining proposed Targets (",Ge.length,")"]})]})]}),x?e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"block max-w-md",children:[e.jsx("span",{className:"text-sm font-medium text-secondary",children:"Search Targets"}),e.jsx("input",{"aria-label":"Search Targets",className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:Ae,onChange:f=>Fe(f.target.value),placeholder:"Target name"})]}),e.jsxs("p",{className:"text-sm text-secondary",children:["Showing ",Ft.length," of ",os.length," matching ",os.length===1?"Target":"Targets"," (",x.targets.length," total)"]}),Lt.length>0?e.jsxs("div",{className:"space-y-3 rounded-md border border-caution-800/40 bg-caution-950/20 p-4",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-medium text-caution",children:[Lt.length," ",Lt.length===1?"Target has":"Targets have"," URL coverage changes."]}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Select changed Targets, then keep their saved coverage or replace it with this import."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(A,{size:"sm",variant:"outline",onClick:()=>Me(Lt.map(f=>f.targetKey)),children:"Select all URL changes"}),e.jsx(A,{size:"sm",variant:"outline",disabled:wt.length===0,onClick:()=>mn("keep-existing"),children:"Keep existing coverage for selected"}),e.jsx(A,{size:"sm",variant:"outline",disabled:wt.length===0,onClick:()=>mn("replace-with-imported"),children:"Replace selected with imported coverage"})]})]}):null,e.jsx("div",{className:"overflow-x-auto rounded-md border border-default",children:e.jsxs("table",{className:"evidence-table min-w-[760px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Select"})}),e.jsx("th",{children:"Target"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"URL coverage"}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Details"})})]})}),e.jsx("tbody",{children:Ft.map(f=>{const W=Se.includes(f.stableKey);return[e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("input",{"aria-label":`Select ${f.label}`,type:"checkbox",checked:gt.has(f.stableKey),onChange:ae=>Kn(f.stableKey,ae.target.checked)})}),e.jsx("td",{className:"font-medium text-heading",children:f.label}),e.jsx("td",{children:e.jsx(Z,{tone:f.status==="confirmed"?"positive":f.status==="rejected"?"negative":"caution",children:f.status==="confirmed"?"Confirmed":f.status==="rejected"?"Rejected":"Proposed"})}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[f.urls.length," ",f.urls.length===1?"URL":"URLs"]}),e.jsx("td",{className:"text-right",children:e.jsxs(A,{size:"sm",variant:"ghost","aria-expanded":W,onClick:()=>ct(ae=>W?ae.filter(Le=>Le!==f.stableKey):[...ae,f.stableKey]),children:[W?"Hide":"Show"," URLs for ",f.label]})})]},f.stableKey),W?e.jsx("tr",{children:e.jsx("td",{colSpan:5,children:e.jsx("ul",{className:"space-y-2 py-2 text-sm text-secondary",children:f.urls.map((ae,Le)=>e.jsxs("li",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("span",{className:"break-all font-mono text-xs",children:$n(ae)}),e.jsx(A,{size:"sm",variant:"ghost","aria-label":`Remove ${$n(ae)} from ${f.label}`,onClick:()=>Ve(Xu(x,f.stableKey,ae)),children:"Remove"})]},`${f.stableKey}:${Le}`))})})},`${f.stableKey}:urls`):null]})})]})}),x.exceptions.length>0?e.jsxs("details",{className:"rounded-md border border-default p-3",children:[e.jsxs("summary",{className:"cursor-pointer text-sm font-medium text-heading",children:[ot.length," ",ot.length===1?"URL needs":"URLs need"," review"]}),e.jsxs("p",{className:"mt-3 text-sm text-secondary",children:["Showing ",Kt.length," of ",ot.length," unreviewed items"]}),e.jsx("ul",{className:"mt-2 space-y-2 text-sm text-secondary",children:Kt.map(f=>e.jsxs("li",{className:"break-all",children:[f.url," (",f.reason,")"]},f.key))}),ot.length>0?e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[ot.length>Kt.length?e.jsxs(A,{size:"sm",variant:"outline",onClick:()=>Ve($i(x,Kt.map(f=>f.key))),children:["Mark ",Kt.length," shown items complete"]}):null,e.jsxs(A,{size:"sm",variant:"outline",onClick:()=>Ve(Zu(x)),children:["Mark all ",ot.length," URL review items complete"]})]}):null]}):null,e.jsx(A,{disabled:ge.length===0,onClick:()=>C(2),children:"Continue to Queries"})]}):e.jsx("p",{className:"text-sm text-secondary",children:"Import a sitemap to review Targets."})]}):null,de===2?e.jsxs("section",{"aria-labelledby":"portfolio-queries-title",className:"space-y-5",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{id:"portfolio-queries-title",children:"Queries"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Apply reusable query sets to selected Targets. Templates create drafts for review before they enter the query library."})]})}),x?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(A,{size:"sm",variant:"outline",onClick:()=>Me(ge.map(f=>f.stableKey)),children:"Select all confirmed Targets"}),x.groups.map(f=>e.jsxs(A,{size:"sm",variant:"outline",onClick:()=>Fs(f.targetKeys),children:["Select members of ",f.label]},f.stableKey)),e.jsx(A,{size:"sm",variant:"ghost",disabled:Te.length===0,onClick:()=>Me([]),children:"Clear selection"}),e.jsxs("span",{className:"self-center text-sm text-secondary",children:[ie.length," confirmed selected"]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 rounded-md border border-default bg-surface-subtle px-3 py-2",children:[e.jsx(A,{size:"sm",variant:"outline",disabled:!Os,onClick:()=>Ve(nm(x,ie)),children:"Clear selected query assignments"}),e.jsx("p",{className:"text-xs text-muted",children:"This only changes the draft. It does not delete tracked queries."})]}),e.jsx("p",{className:"text-sm text-secondary",children:"Groups organize reporting and competitors only. Query assignments always belong to Targets."}),r?e.jsx("div",{className:"h-24 animate-pulse rounded-md bg-surface-subtle","aria-label":"Loading tracked queries"}):i?e.jsxs("div",{className:"rounded-md border border-negative-800/40 bg-negative-950/20 p-3 text-sm text-negative",children:["Could not load tracked queries.",c?e.jsx(A,{className:"ml-3",size:"sm",variant:"outline",onClick:c,children:"Try again"}):null]}):e.jsxs("div",{className:"grid gap-5 xl:grid-cols-2",children:[e.jsxs("div",{className:"space-y-4 border-t border-default pt-4",children:[e.jsx("h4",{className:"font-medium text-heading",children:"Save a query set"}),e.jsx(Bt,{label:"Query set name",value:X,onChange:Pe,placeholder:"Local intent"}),e.jsxs("fieldset",{children:[e.jsx("legend",{className:"text-sm font-medium text-secondary",children:"Tracked queries"}),e.jsx("div",{className:"mt-2 max-h-52 space-y-2 overflow-y-auto",children:Ye.map(f=>e.jsxs("label",{className:"flex min-h-11 items-center gap-3 rounded border border-default px-3 py-2 text-sm text-primary",children:[e.jsx("input",{type:"checkbox",checked:dn.has(f.id),onChange:W=>_e(ae=>W.target.checked?[...new Set([...ae,f.id])]:ae.filter(Le=>Le!==f.id))}),f.query]},f.id))})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm font-medium text-secondary",children:"Query set location"}),e.jsxs("select",{"aria-label":"Query set location",className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none",value:Ie,onChange:f=>ht(f.target.value),children:[e.jsx("option",{value:Ws,children:"Project default"}),e.jsx("option",{value:$a,children:"No location"}),n.map(f=>e.jsx("option",{value:f.label,children:f.label},f.label))]})]}),e.jsx(A,{size:"sm",disabled:!X.trim()||Xe.length===0,onClick:Fn,children:"Save query set"})]}),e.jsxs("div",{className:"space-y-4 border-t border-default pt-4",children:[e.jsx("h4",{className:"font-medium text-heading",children:"Saved query sets"}),x.querySets.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No draft query sets yet."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[480px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Set"}),e.jsx("th",{children:"Queries"}),e.jsx("th",{children:"Location"}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Apply"})})]})}),e.jsx("tbody",{children:x.querySets.map(f=>{const W=ge.filter(ae=>f.queryIds.every(Le=>x.assignments.some(qe=>qe.targetKey===ae.stableKey&&qe.queryId===Le&&xm(qe.context,f.context)))).length;return e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:f.label}),e.jsx("td",{className:"tabular-nums text-secondary",children:f.queryIds.length}),e.jsx("td",{className:"text-secondary",children:Dr(f.context)}),e.jsxs("td",{className:"text-right",children:[e.jsxs(A,{size:"sm",variant:"outline",disabled:ie.length===0,onClick:()=>_n(f.key),children:["Apply ",f.label]}),W>0?e.jsxs("span",{className:"mt-1 block text-xs text-muted",children:[W," Targets use this set"]}):null]})]},f.key)})})]})})]})]}),e.jsxs("div",{className:"space-y-3 border-t border-default pt-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium text-heading",children:"Query template"}),e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:["Use ","{target.label}"," once. Review every expanded query before creating it."]})]}),e.jsx(Bt,{label:"Query template",value:L,onChange:ve,placeholder:"reviews for {target.label}"}),e.jsxs("label",{className:"block max-w-md",children:[e.jsx("span",{className:"text-sm font-medium text-secondary",children:"Template location"}),e.jsxs("select",{"aria-label":"Template location",className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none",value:De,onChange:f=>Rt(f.target.value),children:[e.jsx("option",{value:Ws,children:"Project default"}),e.jsx("option",{value:$a,children:"No location"}),n.map(f=>e.jsx("option",{value:f.label,children:f.label},f.label))]})]}),e.jsx(A,{size:"sm",variant:"outline",disabled:!L.includes("{target.label}")||ie.length===0,onClick:ls,children:"Preview query drafts"}),Re.length>0?e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[560px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Target"}),e.jsx("th",{children:"Draft query"})]})}),e.jsx("tbody",{children:Re.map(f=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:x.targets.find(W=>W.stableKey===f.targetKey)?.label}),e.jsx("td",{className:"text-primary",children:f.text})]},f.targetKey))})]})}),e.jsx(A,{size:"sm",disabled:Q==="create",onClick:()=>{bs()},children:Q==="create"?"Creating…":`Create ${Re.length} tracked queries`})]}):null]}),e.jsxs("div",{className:"space-y-3 border-t border-default pt-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium text-heading",children:"Reporting group"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Create an optional reporting view for the selected Targets. The group does not own queries or locations."})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsx(Bt,{label:"Group name",value:dt,onChange:Be,placeholder:"North region"}),e.jsx(Bt,{label:"Competitor domains (optional)",value:ut,onChange:qt,placeholder:"one.example, two.example"})]}),e.jsx(A,{size:"sm",variant:"outline",disabled:!dt.trim()||ie.length===0,onClick:hn,children:"Save reporting group"}),x.groups.length>0?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[560px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Targets"}),e.jsx("th",{children:"Competitors"})]})}),e.jsx("tbody",{children:x.groups.map(f=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:f.label}),e.jsx("td",{className:"tabular-nums text-secondary",children:f.targetKeys.length}),e.jsx("td",{className:"text-secondary",children:f.competitors?.join(", ")||"None"})]},f.stableKey))})]})}):null]}),e.jsx(A,{onClick:()=>C(3),children:"Continue to Review & publish"})]}):e.jsx("p",{className:"text-sm text-secondary",children:"Confirm at least one Target first."})]}):null,de===3?e.jsxs("section",{"aria-labelledby":"portfolio-review-title",className:"space-y-5",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{id:"portfolio-review-title",children:"Review & publish"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Review assignments and resolve failed checks before publishing a new revision."})]})}),x?St?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto rounded-md border border-default",children:e.jsxs("table",{className:"evidence-table min-w-[720px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Target"}),e.jsx("th",{children:"URLs"}),e.jsx("th",{children:"Tracked queries"}),e.jsx("th",{children:"Location"})]})}),e.jsx("tbody",{children:ge.map(f=>{const W=x.assignments.filter(Le=>Le.targetKey===f.stableKey),ae=[...new Set(W.map(Le=>Dr(Le.context)))];return e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:f.label}),e.jsx("td",{className:"tabular-nums text-secondary",children:f.urls.length}),e.jsx("td",{className:"text-secondary",children:W.map(Le=>I.get(Le.queryId)??"Missing query").join(", ")||"None selected"}),e.jsx("td",{className:"text-secondary",children:ae.join(", ")||"Project default"})]},f.stableKey)})})]})}),Ks.length>0?e.jsx("p",{className:"text-sm text-caution",children:"The draft needs attention before it can pass server checks."}):null,e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(A,{variant:"outline",disabled:Q==="check",onClick:()=>{be()},children:Q==="check"?"Checking…":"Check plan"}),e.jsx("span",{className:"text-sm text-secondary",children:"Estimated cost is unavailable"})]}),Ze?e.jsx("div",{className:"space-y-2","aria-live":"polite",children:Ze.checks.length===0?e.jsx("p",{className:"text-sm text-positive",children:"No blocking checks."}):Ze.checks.map((f,W)=>e.jsxs("div",{className:`rounded-md border p-3 text-sm ${f.severity==="fail"?"border-negative-800/40 bg-negative-950/20 text-negative":"border-caution-800/40 bg-caution-950/20 text-caution"}`,children:[e.jsx("p",{className:"font-medium",children:pm(f.id)}),e.jsx("p",{className:"mt-1",children:f.message})]},`${f.id}:${W}`))}):null,He?e.jsx("div",{className:"overflow-x-auto rounded-md border border-default","aria-label":"Plan change summary",children:e.jsxs("table",{className:"evidence-table min-w-[560px]",children:[e.jsx("caption",{className:"px-3 py-2 text-left text-sm text-secondary",children:He.activeRevision===null?"Compared with a new setup":`Compared with revision ${He.activeRevision}`}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Area"}),e.jsx("th",{children:"Added"}),e.jsx("th",{children:"Removed"}),e.jsx("th",{children:"Changed"})]})}),e.jsxs("tbody",{children:[e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:"Targets"}),e.jsxs("td",{className:"tabular-nums text-secondary",children:["+",He.targets.added.length]}),e.jsxs("td",{className:"tabular-nums text-secondary",children:["−",He.targets.removed.length]}),e.jsxs("td",{className:"tabular-nums text-secondary",children:["~",He.targets.changed.length]})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:"Reporting groups"}),e.jsxs("td",{className:"tabular-nums text-secondary",children:["+",He.groups.added.length]}),e.jsxs("td",{className:"tabular-nums text-secondary",children:["−",He.groups.removed.length]}),e.jsxs("td",{className:"tabular-nums text-secondary",children:["~",He.groups.changed.length]})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:"Query assignments"}),e.jsxs("td",{className:"tabular-nums text-secondary",children:["+",He.querySelections.added.length]}),e.jsxs("td",{className:"tabular-nums text-secondary",children:["−",He.querySelections.removed.length]}),e.jsxs("td",{className:"tabular-nums text-secondary",children:["~",He.querySelections.changed.length]})]})]})]})}):null,e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(A,{disabled:!Ze?.ok||lt.length>0||Q==="publish"||he?.fingerprint!==ft||he?.activeKey!==It,onClick:()=>{Ct()},children:Q==="publish"?"Publishing…":"Publish plan"}),$e?e.jsxs("span",{className:"text-sm text-positive",children:["Revision ",$e.revision," is active."]}):null]}),e.jsx("p",{className:"text-xs text-muted",children:"Publishing saves configuration only. It does not start an engine run."})]}):e.jsxs("div",{role:"alert",className:"space-y-3 rounded-md border border-caution-800/40 bg-caution-950/20 p-4 text-sm text-caution",children:[e.jsx("p",{className:"font-medium",children:"Resolve these setup items before checking the plan."}),e.jsxs("ul",{className:"list-disc space-y-1 pl-5",children:[Ge.length>0?e.jsxs("li",{children:[Ge.length," ",Ge.length===1?"Target still needs":"Targets still need"," confirmation or rejection."]}):null,ot.length>0?e.jsxs("li",{children:[ot.length," ",ot.length===1?"URL still needs":"URLs still need"," review."]}):null,Lt.length>0?e.jsxs("li",{children:[Lt.length," ",Lt.length===1?"Target still needs":"Targets still need"," a URL coverage decision."]}):null,Ks.filter(f=>f.code!=="target-review-required"&&f.code!=="exception-review-required"&&f.code!=="coverage-review-required").map((f,W)=>e.jsx("li",{children:f.message},`${f.code}:${W}`))]}),e.jsx(A,{size:"sm",variant:"outline",onClick:()=>C(1),children:"Return to Targets"})]}):e.jsx("p",{className:"text-sm text-secondary",children:"Complete setup before publishing."})]}):null,de===4?e.jsxs("section",{"aria-labelledby":"portfolio-report-title",className:"space-y-4",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{id:"portfolio-report-title",children:"Report"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Stored evidence for the active revision."})]})}),e.jsx(bm,{activePlan:u,report:m,isLoading:g,isError:k,onRetry:R})]}):null]})}function Bt({label:t,value:s,onChange:n,placeholder:a}){return e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm font-medium text-secondary",children:t}),e.jsx("input",{"aria-label":t,className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:s,onChange:r=>n(r.target.value),placeholder:a})]})}const ym={critical:"negative",high:"negative",medium:"caution",low:"neutral"};function Qe(t){return Number.isFinite(t)?Math.abs(t)>=1e6?`${(t/1e6).toFixed(1)}M`:Math.abs(t)>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString("en-US"):"—"}function vm(t){if(!t)return"—";const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Nm(t){const s=[t.city,t.region,t.country].filter(Boolean).join(", ");return s?`${t.label} (${s})`:t.label}function wm({projectName:t}){const[s,n]=l.useState(!1),[a,r]=l.useState(null),[i,c]=l.useState(cl),u=Ne({...dl({client:V,path:{name:t},query:{period:i}}),placeholderData:Ki});async function o(){n(!0),r(null);try{await ml(t,"client",i)}catch(p){const m=p instanceof pa||p instanceof Error?p.message:"Download failed";r(m)}finally{n(!1)}}if(u.isLoading)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading report…"});if(u.error){const p=u.error instanceof Error?u.error.message:"Failed to load report";return e.jsx("div",{className:"py-8 text-center",children:e.jsx("p",{className:"text-sm text-negative-400",children:p})})}const h=u.data;return h?e.jsxs("div",{children:[e.jsxs("div",{className:"page-header",children:[e.jsxs("div",{className:"page-header-left",children:[e.jsx("p",{className:"eyebrow",children:"AI Visibility Report"}),e.jsx("h1",{className:"page-title",children:h.meta.project.displayName}),e.jsxs("p",{className:"page-subtitle",children:[h.meta.project.canonicalDomain," · ",h.meta.project.country," / ",h.meta.project.language.toUpperCase(),h.meta.location?` · Location: ${Nm(h.meta.location)}`:" · No location set"," · ","Last ",h.meta.periodDays," days"," · ","Generated ",vm(h.meta.generatedAt)]}),a&&e.jsx("p",{className:"mt-2 text-xs text-negative-400",children:a})]}),e.jsxs("div",{className:"page-header-right flex flex-col items-end gap-2",children:[e.jsx(Sm,{period:i,onChange:c}),e.jsxs(A,{variant:"secondary",size:"sm",onClick:ye(o),disabled:s,children:[e.jsx(ri,{className:"size-4"}),s?"Preparing…":"Download report HTML"]})]})]}),e.jsx(Rm,{report:h}),e.jsx(qm,{report:h,audience:"client"}),e.jsx(Am,{report:h}),e.jsx(Dm,{report:h,audience:"client",projectName:t}),e.jsx(Em,{report:h})]}):null}function Sm({period:t,onChange:s}){return e.jsx("div",{className:"segmented",role:"group","aria-label":"Report time period",children:ul.map(n=>{const a=n===t;return e.jsxs("button",{type:"button",onClick:()=>s(n),"aria-pressed":a,className:`segmented-option ${a?"segmented-option-active":""}`,children:[n,"d"]},n)})})}const qr="AI Visibility — Server-Side",Or="AI engine attention",Cm=t=>`What AI engines actually do in your server logs over the last ${t} days — the other half of citations.`,km="Live telemetry from your server logs.";function Am({report:t}){const s=t.serverActivity;if(!s)return null;if(!s.hasData)return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(an,{eyebrow:Or,title:qr,subtitle:km}),e.jsx("p",{className:"text-sm text-muted",children:"Your server-side traffic source is connected. Numbers will appear after the next sync."})]});const n={current:s.verifiedCrawlerHits.current+s.unverifiedCrawlerHits.current,prior:s.verifiedCrawlerHits.prior+s.unverifiedCrawlerHits.prior,deltaPct:Lc(s.verifiedCrawlerHits.current+s.unverifiedCrawlerHits.current,s.verifiedCrawlerHits.prior+s.unverifiedCrawlerHits.prior)},a=t.meta.periodDays,r=`vs prior ${a} days`,i=Wn(n,"requests",r),c=`${Qe(s.verifiedCrawlerHits.current)} verified · ${Qe(s.unverifiedCrawlerHits.current)} unverified${i?` · ${i}`:""}`,u=Wn(s.aiUserFetchHits,"requests",r),h=[Wn(s.referralArrivals,"sessions",r),s.referralArrivalsClassSummary].filter(Boolean).join(" · "),p=s.byOperator.filter(m=>m.verifiedHits>0||m.unverifiedHits>0||m.userFetchHits>0||m.referralArrivals>0).slice(0,5);return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(an,{eyebrow:Or,title:qr,subtitle:Cm(a)}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(ha,{label:"AI bot requests observed",value:Qe(n.current),subtitle:c}),e.jsx(ha,{label:"AI user-fetch requests",value:Qe(s.aiUserFetchHits.current),subtitle:u||"ChatGPT-User, Perplexity-User, MistralAI-User"}),e.jsx(ha,{label:"AI referral sessions",value:Qe(s.referralArrivals.current),subtitle:h})]}),p.length>0&&e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow mb-2",children:"By AI tool"}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"AI tool"}),e.jsxs("th",{children:["Bot requests (",a,"d)"]}),e.jsxs("th",{children:["User fetches (",a,"d)"]}),e.jsx("th",{children:"Referral sessions"})]})}),e.jsx("tbody",{children:p.map(m=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:m.operator}),e.jsx("td",{children:Qe(m.verifiedHits+m.unverifiedHits)}),e.jsx("td",{children:Qe(m.userFetchHits)}),e.jsx("td",{children:Qe(m.referralArrivals)})]},m.operator))})]})}),e.jsx("p",{className:"mt-2 text-[11px] text-muted",children:"Bot requests are bulk crawl (GPTBot, PerplexityBot, …). User fetches are on-demand reads triggered by real users inside an AI surface (ChatGPT-User, Perplexity-User, …). Verified means the request came from an IP the operator publishes as its own; unverified means the user-agent matched but the IP is not in a published range. User-fetch totals count both, since many genuine user fetches come from outside any published range."})]})]})}function $m(t,s){return t.audience==="both"||t.audience===s}const Tm={gemini:"Gemini",openai:"ChatGPT",claude:"Claude",perplexity:"Perplexity",local:"Local model","cdp:chatgpt":"ChatGPT (browser)"};function qn(t){return Tm[t]??t.charAt(0).toUpperCase()+t.slice(1)}function Pm(t){if(!t)return null;const s=t.window??1,n=s>=2?`vs prior ${s} checks (avg ${t.prior}%)`:`since last check (was ${t.prior}%)`;return t.direction==="up"?{text:`Up ${t.deltaAbs.toFixed(1)} points ${n}`,tone:"positive",arrow:"↑"}:t.direction==="down"?{text:`Down ${Math.abs(t.deltaAbs).toFixed(1)} points ${n}`,tone:"negative",arrow:"↓"}:{text:`Holding steady ${s>=2?`vs prior ${s} checks (avg ${t.prior}%)`:`since last check (was ${t.prior}%)`}`,tone:"neutral",arrow:"→"}}function Rm({report:t}){const s=t.executiveSummary,n=t.citationScorecard,a=s.totalQueryCount,r=a>0?`${s.mentionRate}%`:"—",i=a>0?`When customers asked AI ${a} ${a===1?"question":"questions"} about your industry, AI mentioned you in ${s.mentionedQueryCount} of ${a===1?"them":"those answers"}.`:"No AI check has been run yet. Run a check to see how AI tools answer customer questions about your business.",c=Pm(t.whatsChanged.mentionRate),u=n.providers.length>0?n.providers.map(qn).join(", "):`${Qe(s.queryCount)} ${s.queryCount===1?"question":"questions"} tested`;return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"rounded-2xl border border-default bg-bg-elevated/40 p-6 sm:p-8",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-muted",children:"Overview"}),e.jsx("p",{className:"mt-3 text-6xl font-bold tracking-tight text-primary sm:text-7xl",children:r}),e.jsx("p",{className:"mt-3 max-w-2xl text-base text-neutral sm:text-lg",children:i}),c&&e.jsxs("p",{className:`mt-3 text-sm font-medium ${c.tone==="positive"?"text-positive-400":c.tone==="negative"?"text-negative-400":"text-secondary"}`,children:[e.jsx("span",{className:"mr-1",children:c.arrow}),c.text]})]}),e.jsxs("div",{className:"mt-5 grid gap-4 sm:grid-cols-3",children:[e.jsx(ua,{label:"AI mentions your name",value:`${s.mentionRate}%`,subtitle:a>0?`Says your name in ${s.mentionedQueryCount} of ${a} ${a===1?"answer":"answers"}`:"No data yet"}),e.jsx(ua,{label:"AI links to your website",value:`${s.citationRate}%`,subtitle:a>0?`Cites your site as a source in ${s.citedQueryCount} of ${a} ${a===1?"answer":"answers"}`:"No data yet"}),e.jsx(ua,{label:"AI tools tested",value:Qe(s.providerCount),subtitle:u})]}),e.jsxs("div",{className:"mt-4 rounded-xl border border-default bg-bg/40 px-4 py-3 text-xs text-secondary",children:[e.jsx("span",{className:"font-semibold text-strong",children:"Mentions and links are different."})," ","A ",e.jsx("span",{className:"font-medium text-strong",children:"mention"})," is when AI says your name out loud in its answer. A ",e.jsx("span",{className:"font-medium text-strong",children:"link"})," is when AI lists your website as a source it used. AI can do either, both, or neither — that's why we track both."]}),n.queries.length>0&&e.jsxs("div",{className:"mt-5 rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Customer questions we tested"}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["These are the ",n.queries.length," ",n.queries.length===1?"question we asked":"questions we asked"," every AI tool. The numbers above measure how often you came up."]}),e.jsx("ol",{className:"mt-4 grid gap-2 sm:grid-cols-2",children:n.queries.map((o,h)=>e.jsxs("li",{className:"flex items-start gap-3 rounded-lg border border-default bg-bg/40 px-3 py-2 text-sm text-strong",children:[e.jsx("span",{className:"shrink-0 text-xs font-semibold tabular-nums text-muted",children:String(h+1).padStart(2,"0")}),e.jsxs("span",{children:['"',o,'"']})]},h))})]}),n.providerRates.length>0&&e.jsxs("div",{className:"mt-5 rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"How often each AI tool mentions you"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"Higher is better. Each bar shows the share of customer questions where the AI named you in the answer."}),e.jsx("div",{className:"mt-4 space-y-3",children:n.providerRates.map(o=>e.jsxs("div",{className:"grid grid-cols-[120px_1fr_120px] items-center gap-3",children:[e.jsx("span",{className:"text-sm text-neutral",children:qn(o.provider)}),e.jsx("div",{className:"h-3 overflow-hidden rounded-full bg-mono-800/80",children:e.jsx("div",{className:"h-full rounded-full bg-positive-500/70",style:{width:`${Math.max(o.mentionRate,1.5)}%`}})}),e.jsxs("span",{className:"text-right text-sm font-semibold text-heading",children:[o.mentionRate,"% ",e.jsxs("span",{className:"font-normal text-muted",children:["(",o.mentionedCount,"/",o.totalCount,")"]})]})]},o.provider))})]}),t.clientSummary.confidenceNotes.length>0&&e.jsx("div",{className:"mt-4 grid gap-2",children:t.clientSummary.confidenceNotes.map((o,h)=>e.jsx("div",{className:"rounded-lg border border-default bg-surface px-3 py-2 text-xs text-secondary",children:o},h))})]})}function ua({label:t,value:s,subtitle:n}){return e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-muted",children:t}),e.jsx("p",{className:"mt-3 text-4xl font-bold tracking-tight text-primary sm:text-5xl",children:s}),e.jsx("p",{className:"mt-2 text-xs text-muted",children:n})]})}function Lm(t){switch(t){case"immediate":return"Do now";case"short-term":return"This month";case"medium-term":return"Next quarter"}}function Im(t){switch(t){case"high":return"Strong evidence";case"medium":return"Some evidence";case"low":return"Worth trying"}}function Dm({report:t,audience:s,projectName:n}){const a=s==="client"?t.clientSummary.actionItems:t.agencyDiagnostics.priorities.length>0?t.agencyDiagnostics.priorities:t.actionPlan.filter(m=>$m(m,s)),r=qc(t,a),i=s==="client",c=hl(),[u,o]=l.useState(new Set),h=u.size>0?r.filter(m=>!m.targetRef||!u.has(m.targetRef)):r,p=m=>{if(!m.targetRef)return;const g=m.targetRef;o(k=>new Set(k).add(g)),c.mutate({projectName:n,body:{targetRef:g}},{onSuccess:()=>{xe({tone:"positive",title:`Dismissed "${m.title}"`,detail:"Will not appear in future reports until un-dismissed."})},onError:k=>{xe({tone:"negative",title:`Couldn't dismiss "${m.title}"`,detail:String(k)}),o(R=>{const v=new Set(R);return v.delete(g),v})}})};return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(an,{eyebrow:i?"Action plan":"Agency actions",title:i?"What to do next":"Agency Action Plan",subtitle:i?"Approve these in order. They are sorted by what will move the needle fastest.":"The highest-leverage work, sorted by urgency and evidence strength."}),h.length===0?e.jsx(Ua,{message:"No recommendations yet — run an AI check to populate this."}):e.jsx("div",{className:"grid gap-3 lg:grid-cols-2",children:h.map((m,g)=>{const k=m.evidence.length>0?m.evidence:m.why,R=m.why.length>0||m.evidence.length>0;return e.jsxs("article",{className:"rounded-xl border border-default bg-surface p-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex size-8 shrink-0 items-center justify-center rounded-full bg-mono-800/80 text-sm font-semibold text-heading",title:"Priority — 1 will move the needle fastest",children:g+1}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"mb-2 flex flex-wrap gap-2",children:[e.jsx(Z,{tone:pl(m),children:i?Lm(m.horizon):xl(m.horizon)}),!i&&e.jsx(Z,{tone:"neutral",children:gl(m.category)}),e.jsx(Z,{tone:"neutral",children:i?Im(m.confidence):`${fl(m.confidence)} confidence`})]}),e.jsx("p",{className:"text-sm font-medium text-heading",children:m.title})]})]}),e.jsx("p",{className:"mt-3 text-sm text-secondary",children:m.action}),e.jsx(Om,{items:k,limit:3,className:"mt-3"}),R&&e.jsxs("details",{className:"mt-3 text-xs text-secondary",children:[e.jsx("summary",{className:"cursor-pointer text-muted hover:text-neutral",children:i?"See the data behind this":"Evidence details"}),m.why.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"eyebrow-soft mb-1",children:i?"Why this matters":"Why"}),e.jsx("ul",{className:"list-disc space-y-1 pl-4",children:m.why.map((v,j)=>e.jsx("li",{children:v},j))})]}),m.evidence.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"eyebrow-soft mb-1",children:i?"What we saw":"Evidence"}),e.jsx("ul",{className:"list-disc space-y-1 pl-4",children:m.evidence.map((v,j)=>e.jsx("li",{children:v},j))})]})]}),e.jsxs("p",{className:"mt-3 border-t border-default pt-3 text-xs text-neutral",children:[e.jsx("span",{className:"font-medium",children:i?"What success looks like:":"Win condition:"})," ",m.successMetric]}),m.targetRef&&!H()&&e.jsx("div",{className:"mt-3 flex justify-end",children:e.jsx("button",{type:"button",onClick:()=>p(m),className:"rounded-md border border-default bg-bg-elevated/50 px-2.5 py-1 text-[11px] font-medium text-neutral hover:border-mono-600 hover:bg-mono-800/70 hover:text-heading",title:"Stop showing this recommendation. The page-detection logic relies on GSC/GA syncs that lag by days — if you've already addressed it, dismissing keeps the report current.",children:"Mark addressed"})})]},`${m.priority}-${m.title}`)})})]})}function Kr({label:t,value:s,displayValue:n,max:a,barClass:r}){const i=a>0?Math.max(s/a*100,1.5):0;return e.jsxs("div",{className:"grid grid-cols-[1fr_auto] items-center gap-3 text-sm",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-neutral",title:t,children:t}),e.jsx("div",{className:"mt-1 h-2 overflow-hidden rounded-full bg-mono-800/80",children:e.jsx("div",{className:`h-full rounded-full ${r}`,style:{width:`${i}%`}})})]}),e.jsx("span",{className:"whitespace-nowrap text-sm font-semibold text-heading",children:n})]})}function Em({report:t}){const s=t.aiSourceOrigin.topDomains.slice(0,5),n=t.gsc,a=t.indexingHealth,r=Oc(t).slice(0,5),i=s.length>0?Math.max(...s.map(o=>o.count)):0,c=n?Math.max(...n.topQueries.slice(0,5).map(o=>o.impressions),1):0,u=s.length>0||n!==null||a!==null||r.length>0;return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(an,{eyebrow:"What we based this on",title:"The signals behind this plan",subtitle:"The data behind the recommendations above. Switch to Agency for the full breakdowns."}),u?e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[s.length>0&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Where AI gets its answers"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"The websites AI tools cited most often when answering customer questions about your industry."}),e.jsx("div",{className:"mt-4 space-y-3",children:s.map(o=>e.jsx(Kr,{label:o.domain+(o.isCompetitor?" (competitor)":""),value:o.count,displayValue:`${Qe(o.count)}×`,max:i,barClass:"bg-mono-400/70"},o.domain))})]}),a&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Pages Google can find on your site"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"Google indexing your site increases the chances of it appearing in AI search (especially Gemini)."}),e.jsxs("p",{className:`mt-4 text-5xl font-bold tracking-tight ${a.indexedPct>=90?"text-positive-400":a.indexedPct>=70?"text-caution-400":"text-negative-400"}`,children:[a.indexedPct,"%"]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[Qe(a.indexed)," of ",Qe(a.total)," pages indexed"]}),e.jsx("div",{className:"mt-3 h-3 overflow-hidden rounded-full bg-mono-800/80",children:e.jsx("div",{className:`h-full rounded-full ${a.indexedPct>=90?"bg-positive-500/70":a.indexedPct>=70?"bg-caution-500/70":"bg-negative-500/70"}`,style:{width:`${Math.max(a.indexedPct,1.5)}%`}})}),e.jsxs("p",{className:"mt-3 text-xs text-secondary",children:[e.jsx("span",{className:"font-medium text-strong",children:Qe(a.notIndexed)})," ",a.notIndexed===1?"page is":"pages are"," not indexed yet."]})]}),n&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"What people search Google for"}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["You appeared in ",e.jsx("span",{className:"font-semibold text-strong",children:Qe(n.totalImpressions)})," Google searches and got ",e.jsx("span",{className:"font-semibold text-strong",children:Qe(n.totalClicks)})," ",n.totalClicks===1?"click":"clicks"," this period."]}),n.topQueries.length>0&&e.jsx("div",{className:"mt-4 space-y-3",children:n.topQueries.slice(0,5).map(o=>e.jsx(Kr,{label:o.query,value:o.impressions,displayValue:`${Qe(o.impressions)} ${o.impressions===1?"search":"searches"}`,max:c,barClass:"bg-info-500/70"},o.query))})]}),r.length>0&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Topics where you could improve"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"Customer questions where better content on your site would help AI cite you."}),e.jsx("ul",{className:"mt-4 space-y-2 text-sm text-neutral",children:r.map((o,h)=>e.jsxs("li",{className:"rounded-lg border border-default bg-bg/40 px-3 py-2",children:[e.jsx("p",{className:"font-medium text-heading",children:o.query}),e.jsxs("p",{className:"mt-0.5 flex items-center gap-2 text-xs text-secondary",children:[bl(o.action),o.winnabilityClass==="ceded"&&e.jsx(Z,{tone:"caution",children:"Ceded surface"})]})]},h))})]})]}):e.jsx(Ua,{message:"No supporting evidence yet — this fills in after the first AI check."})]})}function Fa(t){return t==="up"?"positive":t==="down"?"negative":"neutral"}function _a(t){return t==="up"?"↑":t==="down"?"↓":"→"}function ma({label:t,delta:s,unit:n}){if(!s)return e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("p",{className:"text-2xl font-semibold tracking-tight text-muted",children:"—"}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:"No prior data"})]});const a=n==="%"?"%":"",r=Fa(s.direction),i=r==="positive"?"text-positive-400":r==="negative"?"text-negative-400":"text-heading",c=n==="%"?`${s.deltaAbs>0?"+":""}${s.deltaAbs.toFixed(1)}% vs ${s.prior}%`:Ic(s);return e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsxs("p",{className:`text-2xl font-semibold tracking-tight ${i}`,children:[s.current,a," ",e.jsx("span",{className:"text-sm font-medium",children:_a(s.direction)})]}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:c})]})}function Fr({label:t,delta:s,countLabel:n,comparisonWindowDays:a}){if(!s)return e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("p",{className:"text-2xl font-semibold tracking-tight text-muted",children:"—"}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:"Not enough trend data"})]});const r=Fa(s.direction),i=r==="positive"?"text-positive-400":r==="negative"?"text-negative-400":"text-heading",c=Dc(s,n,`vs prior ${a} days`);return e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsxs("p",{className:`text-2xl font-semibold tracking-tight ${i}`,children:[Qe(s.current)," ",e.jsx("span",{className:"text-sm font-medium",children:_a(s.direction)})]}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:c})]})}function Mm({movements:t,audience:s}){const n=t.filter(r=>r.direction!=="flat");if(n.length===0)return null;const a=s==="client";return e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow mb-2",children:a?"How each AI tool changed":"AI engine movements"}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:a?"AI tool":"Engine"}),e.jsx("th",{children:a?"Was":"Prior"}),e.jsx("th",{children:a?"Now":"Current"}),e.jsx("th",{children:"Change"})]})}),e.jsx("tbody",{children:n.map(r=>{const i=r.deltaAbs>0?"+":"",c=Fa(r.direction),u=c==="positive"?"text-positive-400":c==="negative"?"text-negative-400":"text-neutral";return e.jsxs("tr",{children:[e.jsx("td",{children:a?qn(r.provider):r.provider}),e.jsxs("td",{children:[r.prior,"%"]}),e.jsxs("td",{children:[r.current,"%"]}),e.jsxs("td",{className:u,children:[i,r.deltaAbs.toFixed(1),"% ",_a(r.direction)]})]},r.provider)})})]})})]})}function _r({insights:t,heading:s,emptyMessage:n,audience:a}){if(t.length===0)return e.jsxs("div",{className:"mt-4 rounded-xl border border-default bg-surface p-4",children:[e.jsx("p",{className:"eyebrow mb-1",children:s}),e.jsx("p",{className:"text-xs text-muted",children:n})]});const r=a==="client";return e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow mb-2",children:s}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[!r&&e.jsx("th",{children:"Severity"}),e.jsx("th",{children:r?"What changed":"Title"}),e.jsx("th",{children:r?"Customer question":"Query"}),e.jsx("th",{children:r?"AI tool":"Provider"})]})}),e.jsx("tbody",{children:t.map(i=>e.jsxs("tr",{children:[!r&&e.jsxs("td",{children:[e.jsx(Z,{tone:ym[i.severity],children:jl(i.severity)}),i.instanceCount>1&&e.jsxs("span",{className:"ml-2 text-[11px] text-muted",children:["×",i.instanceCount]})]}),e.jsxs("td",{className:"evidence-query-cell",children:[i.title,r&&i.instanceCount>1&&e.jsxs("span",{className:"ml-2 text-[11px] text-muted",children:["×",i.instanceCount]})]}),e.jsx("td",{className:"text-xs text-secondary",children:i.query}),e.jsx("td",{className:"text-xs text-secondary",children:r?qn(i.provider):i.provider})]},i.id))})]})})]})}function qm({report:t,audience:s}){const n=t.whatsChanged,a=s==="client",r=!n.enoughHistory&&!n.gscClicksDelta&&!n.aiReferralsDelta&&n.wins.length===0&&n.regressions.length===0,i=e.jsx(an,{eyebrow:a?"Since last check":"Section 2",title:a?"What's different since last check":"What's Changed",subtitle:a?void 0:n.headline});return r?e.jsxs("section",{className:"page-section-divider",children:[i,e.jsx(Ua,{message:a?"No comparison yet — trends will appear after a few more checks.":"Trends will appear after a few more checks."})]}):e.jsxs("section",{className:"page-section-divider",children:[i,e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(ma,{label:a?"AI mentions your name":"Citation rate",delta:a?n.mentionRate:n.citationRate,unit:"%"}),e.jsx(ma,{label:a?"AI links to your website":"Mention rate",delta:a?n.citationRate:n.mentionRate,unit:"%"}),e.jsx(ma,{label:a?"Questions AI mentioned you in":"Cited queries",delta:a?n.mentionedQueryCount:n.citedQueryCount,unit:"count"}),e.jsx(Fr,{label:a?"Visitors from Google":"GSC clicks",delta:n.gscClicksDelta,countLabel:a?"visits":"clicks",comparisonWindowDays:n.comparisonWindowDays}),e.jsx(Fr,{label:a?"Visitors from AI tools":"AI referral sessions",delta:n.aiReferralsDelta,countLabel:a?"visits":"sessions",comparisonWindowDays:n.comparisonWindowDays})]}),e.jsx(Mm,{movements:n.providerMovements,audience:s}),e.jsx(_r,{insights:n.wins,heading:a?"What got better":"Wins",emptyMessage:a?"No new wins this period.":"No new gains in the latest check.",audience:s}),e.jsx(_r,{insights:n.regressions,heading:a?"What got worse":"Regressions",emptyMessage:a?"Nothing got worse this period.":"No new regressions in the latest check.",audience:s})]})}function ha({label:t,value:s,tone:n,subtitle:a}){const r=n==="positive"?"text-positive-400":n==="caution"?"text-caution-400":n==="negative"?"text-negative-400":"text-heading";return e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("p",{className:`text-2xl font-semibold tracking-tight ${r}`,children:s}),a&&e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:a})]})}function an({eyebrow:t,title:s,subtitle:n}){return e.jsxs("div",{className:"mb-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("h2",{className:"page-title",children:s}),n&&e.jsx("p",{className:"page-subtitle mt-1",children:n})]})}function Om({items:t,limit:s=3,className:n}){if(t.length===0)return null;const a=t.slice(0,s),r=t.length-a.length;return e.jsxs("div",{className:`flex flex-wrap gap-1.5 ${n??""}`,children:[a.map((i,c)=>e.jsx("span",{className:"rounded-md border border-default bg-bg-elevated/40 px-2 py-0.5 text-[11px] text-neutral",children:i},c)),r>0&&e.jsxs("span",{className:"rounded-md border border-default bg-bg-elevated/40 px-2 py-0.5 text-[11px] text-secondary",children:["+",r," more"]})]})}function Ua({message:t}){return e.jsx("p",{className:"text-sm text-muted py-4 text-center",children:t})}function Km({project:t,onUpdateProject:s,onRefresh:n}){const[a,r]=l.useState(!1),[i,c]=l.useState(!1),[u,o]=l.useState(null),[h,p]=l.useState(t.displayName),[m,g]=l.useState(t.canonicalDomain),[k,R]=l.useState(t.country),[v,j]=l.useState(t.language),[D,O]=l.useState(t.ownedDomains??[]),[E,F]=l.useState(""),[x,$]=l.useState(t.aliases??[]),[M,se]=l.useState(""),[de,C]=l.useState(null),[b,_]=l.useState(!1),[w,B]=l.useState(!1),[oe,ee]=l.useState(""),[U,pe]=l.useState(""),[le,K]=l.useState(""),[q,y]=l.useState(""),[Y,me]=l.useState(""),[N,G]=l.useState(null),[Q,T]=l.useState(null);l.useEffect(()=>{a||(p(t.displayName),g(t.canonicalDomain),R(t.country),j(t.language),O(t.ownedDomains??[]),$(t.aliases??[]))},[t,a]);function ne(){r(!1),o(null),p(t.displayName),g(t.canonicalDomain),R(t.country),j(t.language),O(t.ownedDomains??[]),$(t.aliases??[]),F(""),se("")}function ce(){const L=E.trim();L&&(D.includes(L)||O([...D,L]),F(""))}function Ae(L){O(D.filter(ve=>ve!==L))}function Fe(){const L=M.trim();if(!L)return;const ve=L.toLowerCase();x.some(De=>De.toLowerCase()===ve)||$([...x,L]),se("")}function Te(L){$(x.filter(ve=>ve!==L))}async function Me(){if(!(!h.trim()||!m.trim()||!k.trim()||!v.trim())){c(!0),o(null);try{await s(t.name,{displayName:h.trim(),canonicalDomain:m.trim(),ownedDomains:D,aliases:x,country:k.trim(),language:v.trim()}),r(!1),xe({title:"Project settings saved",detail:`${h.trim()} was updated.`,tone:"positive",dedupeKey:`project:update:${t.name}`,dedupeMode:"replace"})}catch(L){o(L instanceof Error?L.message:"Failed to save")}finally{c(!1)}}}async function Se(){const L=oe.trim(),ve=U.trim(),De=le.trim(),Rt=q.trim();if(!(!L||!ve||!De||!Rt)){_(!0),C(null);try{const Re={label:L,city:ve,region:De,country:Rt};Y.trim()&&(Re.timezone=Y.trim()),await Nl(t.name,Re),n(),ee(""),pe(""),K(""),y(""),me(""),B(!1),xe({title:"Location added",detail:`${L} is now available for ${t.name}.`,tone:"positive",dedupeKey:`project:location:add:${t.name}:${L}`,dedupeMode:"drop"})}catch(Re){C(Re instanceof Error?Re.message:"Failed to add location")}finally{_(!1)}}}async function ct(L){_(!0),C(null);try{await vl(t.name,L),n(),xe({title:"Location removed",detail:`${L} was removed from ${t.name}.`,tone:"positive",dedupeKey:`project:location:remove:${t.name}:${L}`,dedupeMode:"drop"})}catch(ve){C(ve instanceof Error?ve.message:"Failed to remove location")}finally{_(!1)}}async function Xe(L){_(!0),C(null);try{await yl(t.name,L),n(),xe({title:"Default location updated",detail:`${L} is now the default for ${t.name}.`,tone:"positive",dedupeKey:`project:location:default:${t.name}`,dedupeMode:"replace"})}catch(ve){C(ve instanceof Error?ve.message:"Failed to set default location")}finally{_(!1)}}async function _e(L){G(L),T(null);try{await wl(t.name,L),xe({title:`${L.toUpperCase()} download started`,detail:`Historical citation and mention results for ${t.displayName}.`,tone:"positive",dedupeKey:`project:results-export:${t.name}`,dedupeMode:"replace"})}catch(ve){T(ve instanceof Error?ve.message:"Could not download tracking results.")}finally{G(null)}}const X=h!==t.displayName||m!==t.canonicalDomain||k!==t.country||v!==t.language||JSON.stringify(D)!==JSON.stringify(t.ownedDomains??[])||JSON.stringify(x)!==JSON.stringify(t.aliases??[]),Pe="w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",Ie="mb-1 block text-sm font-medium text-secondary",ht=oe.trim()&&U.trim()&&le.trim()&&q.trim();return e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Configuration"}),e.jsx("h2",{children:"Project settings"})]}),!H()&&!a&&e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>r(!0),children:"Edit settings"})]}),u&&e.jsxs("div",{className:"mb-3 rounded-lg border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:[u,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>o(null),children:"×"})]}),!H()&&a?e.jsxs("div",{className:"rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:Ie,children:"Display name"}),e.jsx("input",{className:Pe,type:"text",value:h,onChange:L=>p(L.target.value),placeholder:"My Project"})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ie,children:"Canonical domain"}),e.jsx("input",{className:Pe,type:"text",value:m,onChange:L=>g(L.target.value),placeholder:"example.com"})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ie,children:"Country"}),e.jsx("input",{className:Pe,type:"text",value:k,onChange:L=>R(L.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ie,children:"Language"}),e.jsx("input",{className:Pe,type:"text",value:v,onChange:L=>j(L.target.value),placeholder:"en"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ie,children:"Owned domains"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:D.map(L=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:[L,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>Ae(L),"aria-label":`Remove ${L}`,children:"×"})]},L))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${Pe} flex-1`,type:"text",placeholder:"docs.example.com",value:E,onChange:L=>F(L.target.value),onKeyDown:L=>L.key==="Enter"&&(L.preventDefault(),ce())}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:!E.trim(),onClick:ce,children:"Add"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ie,children:"Aliases"}),e.jsx("p",{className:"mb-1.5 text-sm text-secondary",children:"Other brand names that may appear in answers."}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:x.map(L=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:[L,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>Te(L),"aria-label":`Remove ${L}`,children:"×"})]},L))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${Pe} flex-1`,type:"text",placeholder:"Facebook",value:M,onChange:L=>se(L.target.value),onKeyDown:L=>L.key==="Enter"&&(L.preventDefault(),Fe())}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:!M.trim(),onClick:Fe,children:"Add"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-default",children:[e.jsx(A,{type:"button",disabled:i||!X||!h.trim()||!m.trim(),onClick:ye(Me),children:i?"Saving...":"Save changes"}),e.jsx(A,{type:"button",variant:"outline",disabled:i,onClick:ne,children:"Cancel"})]})]}):e.jsx("div",{className:"rounded-lg border border-default bg-surface overflow-hidden",children:e.jsx("table",{className:"w-full text-sm",children:e.jsxs("tbody",{children:[e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium w-40",children:"Display name"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.displayName||"—"})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Canonical domain"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.canonicalDomain})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Owned domains"}),e.jsx("td",{className:"px-4 py-2.5",children:(t.ownedDomains??[]).length>0?e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.ownedDomains.map(L=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:L},L))}):e.jsx("span",{className:"text-muted",children:"—"})})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Aliases"}),e.jsx("td",{className:"px-4 py-2.5",children:(t.aliases??[]).length>0?e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.aliases.map(L=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:L},L))}):e.jsx("span",{className:"text-muted",children:"—"})})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Country"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.country})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Language"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.language})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium align-top pt-3",children:"Locations"}),e.jsxs("td",{className:"px-4 py-2.5",children:[de&&e.jsxs("div",{className:"mb-2 rounded border border-negative-800/40 bg-negative-950/20 px-2 py-1 text-xs text-negative",children:[de,e.jsx("button",{type:"button",className:"ml-1 text-negative-400 hover:text-negative-200",onClick:()=>C(null),children:"×"})]}),(t.locations??[]).length>0?e.jsxs("table",{className:"w-full text-xs mb-2",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-faint",children:[e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Label"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"City"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Region"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Country"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Timezone"}),e.jsx("th",{className:"pb-1"})]})}),e.jsx("tbody",{children:t.locations.map(L=>e.jsxs("tr",{className:"border-t border-mono-800/30",children:[e.jsx("td",{className:"py-1.5 pr-3",children:e.jsxs("span",{className:`inline-flex items-center gap-1 rounded-md border px-2 py-1 text-xs font-medium ${L.label===t.defaultLocation?"border-positive-700/60 bg-positive-950/30 text-positive":"border-mono-700/60 bg-mono-800/40 text-neutral"}`,children:[L.label,L.label===t.defaultLocation?" ★":""]})}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:L.city}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:L.region}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:L.country}),e.jsx("td",{className:"py-1.5 pr-3 text-muted",children:L.timezone??"—"}),e.jsx("td",{className:"py-1.5",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[!H()&&L.label!==t.defaultLocation&&e.jsx("button",{type:"button",disabled:b,onClick:()=>{Xe(L.label)},className:"text-sm text-secondary hover:text-positive-400 transition-colors disabled:opacity-40","aria-label":`Set ${L.label} as default location`,children:"Set default"}),!H()&&e.jsx("button",{type:"button",disabled:b,onClick:()=>{ct(L.label)},className:"text-sm text-secondary hover:text-negative-400 transition-colors disabled:opacity-40","aria-label":`Remove location ${L.label}`,children:"Remove"})]})})]},L.label))})]}):e.jsx("p",{className:"text-muted text-xs mb-2",children:"No locations configured"}),H()?null:w?e.jsxs("div",{className:"mt-2 rounded border border-base bg-bg-elevated/50 p-3 space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-secondary",children:"Add location"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-sm text-secondary",children:"Label *"}),e.jsx("input",{className:Pe,type:"text",value:oe,onChange:L=>ee(L.target.value),placeholder:"nyc"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-sm text-secondary",children:"City *"}),e.jsx("input",{className:Pe,type:"text",value:U,onChange:L=>pe(L.target.value),placeholder:"New York"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-sm text-secondary",children:"Region *"}),e.jsx("input",{className:Pe,type:"text",value:le,onChange:L=>K(L.target.value),placeholder:"NY"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-sm text-secondary",children:"Country *"}),e.jsx("input",{className:Pe,type:"text",value:q,onChange:L=>y(L.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"mb-1 block text-sm text-secondary",children:"Timezone (optional)"}),e.jsx("input",{className:Pe,type:"text",value:Y,onChange:L=>me(L.target.value),placeholder:"America/New_York"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(A,{type:"button",size:"sm",disabled:b||!ht,onClick:ye(Se),children:b?"Adding...":"Add location"}),e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:b,onClick:()=>{B(!1),C(null)},children:"Cancel"})]})]}):e.jsx(A,{type:"button",size:"sm",variant:"outline",onClick:()=>B(!0),children:"+ Add location"})]})]})]})})})]}),e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Data export"}),e.jsx("h2",{children:"Tracking results"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-muted",children:"Download historical citation and mention observations for this project. Each row is one query and provider result, including stored answer text and source URLs."})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("p",{className:"max-w-xl text-xs leading-5 text-muted",children:"Includes completed, partial, and failed answer-visibility runs with stored results. Test runs are excluded. Provider credentials and raw provider payloads are never included."}),e.jsxs("div",{className:"flex shrink-0 flex-wrap gap-2",children:[e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:N!==null,onClick:ye(()=>_e("csv")),children:N==="csv"?"Preparing CSV...":"Download CSV"}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:N!==null,onClick:ye(()=>_e("json")),children:N==="json"?"Preparing JSON...":"Download JSON"})]})]}),Q&&e.jsx("p",{className:"mt-3 rounded border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:Q})]})]})]})}function Hs(t){return{...t??{}}}function Fm(t,s){const n=Object.entries(t).sort(([r],[i])=>r.localeCompare(i)),a=Object.entries(s).sort(([r],[i])=>r.localeCompare(i));return n.length===a.length&&n.every(([r,i],c)=>{const u=a[c];return u?.[0]===r&&u[1]===i})}function _m({project:t,onSave:s}){const n=Ne({queryKey:["settings"],queryFn:Qr,staleTime:6e4}),[a,r]=l.useState(t.providers.length===0),[i,c]=l.useState(t.providers),[u,o]=l.useState(()=>Hs(t.providerModels)),[h,p]=l.useState({providers:t.providers,providerModels:Hs(t.providerModels)}),[m,g]=l.useState(!1),[k,R]=l.useState(!1),[v,j]=l.useState(null),[D,O]=l.useState(null),E=l.useRef(null),F=n.data?.providerCatalog??[],x=l.useMemo(()=>new Set((n.data?.providers??[]).filter(w=>w.configured).map(w=>w.name)),[n.data]),$=l.useMemo(()=>{const w=new Map(F.map(B=>[B.name,B]));for(const B of Object.keys(u))w.has(B)||w.set(B,{name:B,displayName:B,mode:"api",modelConfigurable:!0,defaultModel:"",knownModels:[],modelValidationPattern:{source:".",flags:""},modelValidationHint:"Validate this custom model ID with the server."});return[...w.values()].sort((B,oe)=>B.displayName.localeCompare(oe.displayName))},[F,u]),M=!Fm(u,h.providerModels);l.useEffect(()=>{if(m||k)return;const w={providers:t.providers,providerModels:Hs(t.providerModels)};p(w),r(w.providers.length===0),c(w.providers),o(w.providerModels)},[t]);function se(){R(!0),r(!1),i.length===0&&c([...x])}function de(w,B,oe=!1){R(!0),o(ee=>{const U={...ee};return B==="__inherit__"?delete U[w]:B==="__custom__"?U[w]=oe?"":U[w]??"":U[w]=B,U}),B==="__custom__"&&queueMicrotask(()=>E.current?.focus())}function C(w,B){R(!0),c(oe=>B?[...new Set([...oe,w])]:oe.filter(ee=>ee!==w))}function b(){R(!1),r(h.providers.length===0),c(h.providers),o(Hs(h.providerModels)),j(null),O(null)}async function _(){if(!(n.isError||n.isLoading||!a&&i.length===0)){g(!0),j(null),O(null);try{const w=Object.fromEntries(Object.entries(u).filter(([oe,ee])=>ee.trim()!==""&&(a||i.includes(oe)))),B={providers:a?[]:i,providerModels:w};await s(B),p({providers:[...B.providers],providerModels:Hs(B.providerModels)}),R(!1),O("Engine settings saved. They apply on the next sweep.")}catch(w){j(w instanceof Error?w.message:String(w))}finally{g(!1)}}}return H()?null:n.isLoading?e.jsx("section",{className:"project-engine-settings","aria-busy":"true",children:e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading engine settings…"})}):n.isError?e.jsxs("section",{className:"project-engine-settings",children:[e.jsx("h2",{children:"Answer engines"}),e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"Could not load the engine catalogue. Saving is disabled until it is available."}),e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>{n.refetch()},children:"Retry"})]}):F.length===0?e.jsxs("section",{className:"project-engine-settings",children:[e.jsx("h2",{children:"Answer engines"}),e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"The engine catalogue is incomplete. Saving is disabled so existing project overrides cannot be cleared."}),e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>{n.refetch()},children:"Retry"})]}):x.size===0?e.jsxs("section",{className:"project-engine-settings",children:[e.jsx("h2",{children:"Answer engines"}),e.jsxs("p",{className:"text-sm text-secondary",children:["Configure an answer engine in ",e.jsx(zt,{to:"/settings",className:"text-link",children:"global Settings"})," before choosing project engines."]})]}):e.jsxs("section",{className:"project-engine-settings","aria-busy":m,children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Execution"}),e.jsx("h2",{children:"Answer engines"})]}),e.jsx("p",{className:"supporting-copy",children:"Changes apply on the next sweep."})]}),e.jsxs("fieldset",{disabled:m,className:"project-engine-fieldset",children:[e.jsx("legend",{children:"Provider mode"}),e.jsxs("label",{children:[e.jsx("input",{type:"radio",checked:a,onChange:()=>{R(!0),r(!0)}})," All configured engines"]}),e.jsx("p",{className:"project-engine-help",children:"Includes engines configured later in global Settings."}),e.jsxs("label",{children:[e.jsx("input",{type:"radio",checked:!a,onChange:se})," Choose engines"]}),!a&&e.jsx("div",{className:"project-engine-list",children:$.map(w=>{const B=i.includes(w.name),oe=x.has(w.name),ee=B&&!oe,U=u[w.name],pe=w.knownModels.some(K=>K.id===U),le=U===void 0?"__inherit__":pe?U:"__custom__";return e.jsxs("div",{className:"project-engine-row",children:[e.jsxs("label",{className:"project-engine-provider",children:[e.jsx("input",{type:"checkbox",checked:B,disabled:!oe&&!B,onChange:K=>C(w.name,K.target.checked)})," ",e.jsx("span",{children:w.displayName}),ee&&e.jsx("span",{className:"text-xs text-caution-400",children:"Not configured, skipped"})]}),B&&(w.modelConfigurable?e.jsxs("div",{className:"project-engine-model",children:[e.jsx("label",{htmlFor:`project-model-${w.name}`,children:"Model"}),e.jsxs("select",{id:`project-model-${w.name}`,value:le,onChange:K=>de(w.name,K.target.value,pe),children:[e.jsxs("option",{value:"__inherit__",children:["Use instance setting: ",w.defaultModel||"default"]}),w.knownModels.map(K=>e.jsx("option",{value:K.id,children:K.displayName},K.id)),e.jsx("option",{value:"__custom__",children:"Custom model ID…"})]}),le==="__custom__"&&e.jsx("input",{ref:E,"aria-label":`${w.displayName} custom model ID`,value:U??"",onChange:K=>{R(!0),o(q=>({...q,[w.name]:K.target.value}))},"aria-describedby":`project-model-hint-${w.name}`}),e.jsxs("p",{id:`project-model-hint-${w.name}`,className:"project-engine-help",children:[U?"Project override":"Inherited from instance settings",". ",w.modelValidationHint]})]}):e.jsx("p",{className:"project-engine-help",children:"Model is detected/fixed for this browser engine."}))]},w.name)})})]}),!a&&i.length===0&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"Choose at least one configured engine."}),v&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:v}),D&&e.jsx("p",{role:"status",className:"text-sm text-positive-400",children:D}),M&&e.jsx("p",{className:"project-engine-warning",children:"Applies on the next sweep. Existing history remains visible. If the recorded model changes, month-to-month comparison may exclude that engine."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(A,{type:"button",onClick:()=>{_()},disabled:m||!a&&i.length===0,children:m?"Saving engines…":"Save engines"}),e.jsx(A,{type:"button",variant:"outline",onClick:b,disabled:m,children:"Cancel"})]})]})}const Um=[{value:"daily",label:"Every day"},{value:"weekly@mon",label:"Every Monday"},{value:"weekly@wed",label:"Every Wednesday"},{value:"weekly@fri",label:"Every Friday"},{value:"twice-daily",label:"Twice a day (6am & 6pm)"},{value:"custom",label:"Custom cron expression"}],Ur=["UTC","America/New_York","America/Chicago","America/Denver","America/Los_Angeles","America/Toronto","America/Vancouver","Europe/London","Europe/Paris","Europe/Berlin","Asia/Tokyo","Asia/Shanghai","Asia/Singapore","Australia/Sydney"];function Bm({projectName:t}){const[s,n]=l.useState("loading"),[a,r]=l.useState(!1),[i,c]=l.useState("daily"),[u,o]=l.useState(6),[h,p]=l.useState(""),[m,g]=l.useState("UTC"),[k,R]=l.useState(!1),[v,j]=l.useState(""),[D,O]=l.useState(!1),[E,F]=l.useState(!1),[x,$]=l.useState(null);l.useEffect(()=>{Sl(t).then(n).catch(()=>n(null))},[t]);const M=()=>{if(s&&s!=="loading"){const b=kl(s.preset??null,s.cronExpr);c(b.freq),o(b.hour),p(b.customCron);const _=Ur.includes(s.timezone);g(_?s.timezone:"Other"),R(!_),j(_?"":s.timezone)}else c("daily"),o(6),p(""),g("UTC"),R(!1),j("");$(null),r(!0)},se=async()=>{O(!0),$(null);try{const _={timezone:k?v.trim()||"UTC":m};i==="custom"?_.cron=h.trim():_.preset=$l(i,u);const w=await tr(t,_);n(w),r(!1),xe({title:"Schedule saved",detail:Hn(w.preset??null,w.cronExpr,w.timezone),tone:"positive",dedupeKey:`schedule:${t}`,dedupeMode:"replace"})}catch(b){$(b instanceof Error?b.message:"Failed to save schedule")}finally{O(!1)}},de=async()=>{if(!(!s||s==="loading")){O(!0),$(null);try{const b={timezone:s.timezone,enabled:!s.enabled};s.preset?b.preset=s.preset:b.cron=s.cronExpr;const _=await tr(t,b);n(_),xe({title:_.enabled?"Schedule resumed":"Schedule paused",detail:Hn(_.preset??null,_.cronExpr,_.timezone),tone:"positive",dedupeKey:`schedule:toggle:${t}`,dedupeMode:"replace"})}catch(b){$(b instanceof Error?b.message:"Failed to update schedule")}finally{O(!1)}}},C=async()=>{F(!0),$(null);try{await Al(t),n(null),r(!1),xe({title:"Schedule removed",detail:`${t} will no longer run automatically.`,tone:"positive",dedupeKey:`schedule:remove:${t}`,dedupeMode:"drop"})}catch(b){$(b instanceof Error?b.message:"Failed to remove schedule")}finally{F(!1)}};return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Automation"}),e.jsx("h2",{children:"Scheduled runs"})]}),!H()&&s!=="loading"&&!a&&e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:M,children:s?"Edit schedule":"+ Set schedule"})]}),s==="loading"&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),s!=="loading"&&!a&&s===null&&e.jsx(te,{className:"surface-card compact-card",children:e.jsx("p",{className:"supporting-copy",children:"No schedule configured. Set one to automatically trigger visibility sweeps."})}),s!=="loading"&&!a&&s!==null&&e.jsxs(te,{className:"surface-card compact-card",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:Hn(s.preset??null,s.cronExpr,s.timezone)}),e.jsxs("p",{className:"text-xs text-muted",children:["Cron: ",e.jsx("span",{className:"font-mono",children:s.cronExpr})]}),s.nextRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Next run: ",new Date(s.nextRunAt).toLocaleString()]}),s.lastRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Last run: ",new Date(s.lastRunAt).toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(Z,{tone:s.enabled?"positive":"neutral",children:s.enabled?"Active":"Paused"}),!H()&&e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:D,onClick:ye(de),children:s.enabled?"Pause":"Resume"}),!H()&&e.jsx(A,{type:"button",variant:"ghost",size:"sm",disabled:E,onClick:ye(C),children:E?"Removing...":"Remove"})]})]}),x&&e.jsx("p",{className:"text-negative-400 text-sm mt-2",children:x})]}),!H()&&a&&e.jsxs("div",{className:"rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Frequency"}),e.jsx("select",{className:"w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none",value:i,onChange:b=>c(b.target.value),children:Um.map(b=>e.jsx("option",{value:b.value,children:b.label},b.value))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Time"}),e.jsx("select",{className:"w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none disabled:opacity-40",value:u,disabled:i==="twice-daily"||i==="custom",onChange:b=>o(parseInt(b.target.value)),children:Array.from({length:24},(b,_)=>e.jsx("option",{value:_,children:Cl(_)},_))})]})]}),i==="custom"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Cron expression"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 font-mono focus:border-mono-500 focus:outline-none",type:"text",placeholder:"0 9 * * 1-5",value:h,onChange:b=>p(b.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Timezone"}),e.jsxs("select",{className:"w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none",value:k?"Other":m,onChange:b=>{b.target.value==="Other"?(R(!0),g("Other")):(R(!1),g(b.target.value))},children:[Ur.map(b=>e.jsx("option",{value:b,children:b},b)),e.jsxs("option",{value:"Other",children:["Other (enter manually)","…"]})]}),k&&e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"text",placeholder:"e.g. America/New_York",value:v,onChange:b=>j(b.target.value)})]}),x&&e.jsx("p",{className:"text-negative-400 text-sm",children:x}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!1),$(null)},children:"Cancel"}),e.jsx(A,{type:"button",size:"sm",disabled:D||i==="custom"&&!h.trim(),onClick:ye(se),children:D?"Saving...":"Save schedule"})]})]})]})}const Gm=[{value:"citation.lost",label:"Citation lost"},{value:"citation.gained",label:"Citation gained"},{value:"run.completed",label:"Run completed"},{value:"run.failed",label:"Run failed"}];function Qm({projectName:t}){const[s,n]=l.useState("loading"),[a,r]=l.useState(!1),[i,c]=l.useState(""),[u,o]=l.useState(["citation.lost","citation.gained"]),[h,p]=l.useState(!1),[m,g]=l.useState(null),[k,R]=l.useState({}),[v,j]=l.useState(new Set);l.useEffect(()=>{Tl(t).then(n).catch(()=>n([]))},[t]);const D=x=>{o($=>$.includes(x)?$.filter(M=>M!==x):[...$,x])},O=async()=>{if(!(!i.trim()||u.length===0)){p(!0),g(null);try{const x=await Pl(t,{channel:"webhook",url:i.trim(),events:u});n($=>$==="loading"?[x]:[...$,x]),c(""),o(["citation.lost","citation.gained"]),r(!1),xe({title:"Webhook added",detail:`Notifications will be sent to ${x.url}.`,tone:"positive",dedupeKey:`notification:add:${t}`,dedupeMode:"drop"})}catch(x){g(x instanceof Error?x.message:"Failed to add webhook")}finally{p(!1)}}},E=async x=>{if(!v.has(x)){j($=>new Set($).add(x));try{await Ll(t,x),n($=>$==="loading"?$:$.filter(M=>M.id!==x)),xe({title:"Webhook removed",detail:`${t} no longer sends notifications to this endpoint.`,tone:"positive",dedupeKey:`notification:remove:${t}:${x}`,dedupeMode:"drop"})}catch($){g($ instanceof Error?$.message:"Failed to remove webhook")}finally{j($=>{const M=new Set($);return M.delete(x),M})}}},F=async x=>{R($=>({...$,[x]:{state:"testing"}}));try{const $=await Rl(t,x);R(M=>({...M,[x]:{state:$.ok?"ok":"fail",status:$.status}})),$.ok&&xe({title:"Test notification sent",detail:`Webhook returned status ${$.status}.`,tone:"positive",dedupeKey:`notification:test:${t}:${x}`,dedupeMode:"replace"})}catch{R($=>({...$,[x]:{state:"fail"}}))}};return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Automation"}),e.jsx("h2",{children:"Notifications"})]}),!H()&&s!=="loading"&&e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!a),g(null)},children:a?"Cancel":"+ Add webhook"})]}),!H()&&a&&e.jsxs("div",{className:"mb-3 rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Webhook URL"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"url",placeholder:"https://hooks.example.com/canonry",value:i,onChange:x=>c(x.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Trigger on"}),e.jsx("div",{className:"flex flex-wrap gap-3",children:Gm.map(x=>e.jsxs("label",{className:"flex items-center gap-1.5 cursor-pointer select-none",children:[e.jsx("input",{type:"checkbox",className:"rounded border-mono-600 bg-mono-800",checked:u.includes(x.value),onChange:()=>D(x.value)}),e.jsx("span",{className:"text-sm text-neutral",children:x.label})]},x.value))})]}),m&&e.jsx("p",{className:"text-negative-400 text-sm",children:m}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!1),g(null)},children:"Cancel"}),e.jsx(A,{type:"button",size:"sm",disabled:h||!i.trim()||u.length===0,onClick:ye(O),children:h?"Adding...":"Add webhook"})]})]}),s==="loading"&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),s!=="loading"&&s.length===0&&!a&&e.jsx(te,{className:"surface-card compact-card",children:e.jsx("p",{className:"supporting-copy",children:"No webhooks configured. Add one to get alerted when citations change or runs complete."})}),s!=="loading"&&s.length>0&&e.jsxs("div",{className:"evidence-table-wrap",children:[e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Endpoint"}),e.jsx("th",{children:"Events"}),e.jsx("th",{children:"Status"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:s.map(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:e.jsx("span",{className:"font-mono text-xs text-neutral break-all",title:x.urlHost,children:x.urlDisplay??x.url})}),e.jsx("td",{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:x.events.map($=>e.jsx("span",{className:"inline-flex items-center rounded-full border border-strong bg-surface-inset px-2 py-0.5 text-[10px] font-medium text-secondary uppercase tracking-wide",children:$.replace("."," ")},$))})}),e.jsx("td",{children:e.jsx(Z,{tone:x.enabled?"positive":"neutral",children:x.enabled?"Active":"Paused"})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[k[x.id]&&(()=>{const $=k[x.id],M=$.state==="testing"?"Sending…":$.state==="ok"?`Delivered${$.status?` (${$.status})`:""}`:`Failed${$.status?` (${$.status})`:""}`;return e.jsx(Z,{tone:$.state==="ok"?"positive":$.state==="fail"?"negative":"neutral",children:M})})(),!H()&&e.jsx(A,{variant:"ghost",size:"sm",type:"button",disabled:k[x.id]?.state==="testing",onClick:()=>{F(x.id)},children:"Test"}),!H()&&e.jsx(A,{variant:"ghost",size:"sm",type:"button",disabled:v.has(x.id),onClick:()=>{E(x.id)},children:v.has(x.id)?"Removing…":"Remove"})]})})]},x.id))})]}),m&&e.jsx("p",{className:"text-negative-400 text-sm mt-2",children:m})]})]})}function zm(t,s){t.setQueriesData({predicate:n=>n.queryKey[0]==="project-dashboard-full"&&n.queryKey[1]===s.id},n=>!n||typeof n!="object"||!("project"in n)?n:{...n,project:s})}function Hm({projectName:t,refreshNonce:s}){const n=as(),[a,r]=l.useState(null),[i,c]=l.useState([]),[u,o]=l.useState(null),[h,p]=l.useState([]),[m,g]=l.useState([]),[k,R]=l.useState(null),[v,j]=l.useState(""),[D,O]=l.useState(""),[E,F]=l.useState(""),[x,$]=l.useState(!0),[M,se]=l.useState(!1),[de,C]=l.useState(null),[b,_]=l.useState("performance");l.useEffect(()=>{w()},[t,s]);async function w(){$(!0),C(null);try{const y=await n.fetchQuery({...ei({client:V,path:{name:t}}),staleTime:We});if(r(y),y.connected){const[Y,me,N,G]=await Promise.all([n.fetchQuery({...ti({client:V,path:{name:t}}),staleTime:We}).catch(()=>null),n.fetchQuery({...si({client:V,path:{name:t}}),staleTime:We}).catch(()=>[]),n.fetchQuery({...ic({client:V,path:{name:t}}),staleTime:We}).catch(()=>[]),y.siteUrl?Promise.resolve([]):n.fetchQuery({...oc({client:V,path:{name:t}}),staleTime:We}).then(Q=>Q.sites).catch(()=>[])]);o(Y),p(me),g(N),c(G)}else o(null),p([]),g([]),c([])}catch(y){C(y instanceof Error?y.message:"Failed to load Bing data")}finally{$(!1)}}async function B(){if(D.trim()){C(null);try{const y=await lc(t,D.trim());await ze(n,"bing"),O(""),y.availableSites.length>0&&c(y.availableSites),await w()}catch(y){C(y instanceof Error?y.message:"Failed to connect")}}}async function oe(){try{await cc(t),await ze(n,"bing"),r(null),c([]),o(null),p([]),g([]),R(null),F(""),C(null)}catch(y){C(y instanceof Error?y.message:"Failed to disconnect")}}async function ee(){if(E)try{await dc(t,E),await ze(n,"bing"),await w()}catch(y){C(y instanceof Error?y.message:"Failed to set site")}}async function U(){if(v.trim())try{const y=await ni(t,v.trim());await ze(n,"bing"),R(y),p(Y=>[y,...Y])}catch(y){C(y instanceof Error?y.message:"Inspection failed")}}async function pe(y){se(!0),C(null);try{const Y=await ar(t,{urls:[y]}),{succeeded:me,failed:N,total:G}=Y.summary;xe({title:"Bing submission requested",detail:N===0?`${me} URL submitted to Bing.`:`${me}/${G} submitted successfully, ${N} failed.`,tone:N===0?"positive":"caution",dedupeKey:`bing:indexing:${t}:${y}`,dedupeMode:"replace"})}catch(Y){const me=Y instanceof Error?Y.message:"Submission failed";C(me),xe({title:"Bing submission failed",detail:me,tone:"negative",dedupeKey:`bing:indexing:${t}:${y}`,dedupeMode:"replace"})}finally{se(!1)}}async function le(){se(!0),C(null),xe({title:"Submitting URLs to Bing",detail:"Requesting indexing for all currently unindexed URLs.",tone:"neutral",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"});try{const y=await ar(t,{allUnindexed:!0}),{succeeded:Y,failed:me,total:N}=y.summary;xe({title:"Bing submissions requested",detail:me===0?`${Y}/${N} URL${N!==1?"s":""} submitted to Bing.`:`${Y}/${N} submitted successfully, ${me} failed.`,tone:me===0?"positive":"caution",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}catch(y){const Y=y instanceof Error?y.message:"Batch submission failed";C(Y),xe({title:"Bing submissions failed",detail:Y,tone:"negative",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}finally{se(!1)}}if(x)return e.jsx(te,{className:"surface-card",children:e.jsx("div",{className:"text-sm text-secondary",children:"Loading Bing data..."})});if(!a?.connected)return H()?e.jsxs(te,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(Z,{tone:"caution",children:"Not connected"})]}),e.jsx("p",{className:"text-sm text-neutral",children:"Bing Webmaster Tools is not connected for this project."})]}):e.jsxs(te,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(Z,{tone:"caution",children:"Not connected"})]}),e.jsx("p",{className:"text-sm text-neutral",children:"Connect Bing Webmaster Tools to inspect URLs, monitor index coverage, and submit pages for indexing."}),e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:"bing-api-key",children:"API Key"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{id:"bing-api-key",type:"password",className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:"Bing Webmaster Tools API key",value:D,onChange:y=>O(y.target.value),onKeyDown:y=>{y.key==="Enter"&&B()}}),e.jsx(A,{size:"sm",disabled:!D.trim(),onClick:ye(B),children:"Connect"})]}),e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:["Get your API key from"," ",e.jsx("a",{href:"https://www.bing.com/webmasters/",target:"_blank",rel:"noopener noreferrer",className:"text-secondary hover:text-neutral underline underline-offset-2",children:"Bing Webmaster Tools"})]})]}),de&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:de})]});if(!a.siteUrl)return e.jsxs(te,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Z,{tone:"positive",children:"Connected"}),!H()&&e.jsx(A,{size:"sm",variant:"ghost",onClick:ye(oe),children:"Disconnect"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-positive-500"}),e.jsx("span",{className:"text-sm text-strong",children:"Authorized for this project domain"}),e.jsx("span",{className:"text-xs text-muted",children:a.domain})]}),e.jsx("p",{className:"mt-2 text-xs text-muted",children:"The API key is connected, but no Bing site is selected yet. Pick the verified site that should receive inspections and indexing requests."})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Registered domain"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.domain})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Last auth update"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.updatedAt?Dt(a.updatedAt):"—"})]})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Select site"}),i.length>0?e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsxs("select",{className:"flex-1 rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none",value:E,onChange:y=>F(y.target.value),children:[e.jsx("option",{value:"",children:"Select a site..."}),i.map(y=>e.jsxs("option",{value:y.url,children:[y.url,y.verified?" (verified)":""]},y.url))]}),!H()&&e.jsx(A,{size:"sm",disabled:!E,onClick:ye(ee),children:"Set Site"})]}):e.jsx("p",{className:"mt-3 text-xs text-muted",children:"No verified Bing sites are available yet. Verify the domain in Bing Webmaster Tools, then use the page-level refresh to reload everything."})]})]}),de&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:de})]});const K=[{key:"performance",label:"Performance",eyebrow:"Performance",title:"Search performance"},{key:"coverage",label:"Coverage",eyebrow:"Coverage",title:"Index monitoring"},{key:"inspections",label:"Inspections",eyebrow:"Inspection",title:"URL inspection history"}],q=K.find(y=>y.key===b)??K[0];return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(te,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Z,{tone:"positive",children:"Connected"}),!H()&&e.jsx(A,{size:"sm",variant:"ghost",onClick:ye(oe),children:"Disconnect"})]})]}),de&&e.jsx("p",{className:"mb-3 text-xs text-negative-400",children:de}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-positive-500"}),e.jsx("span",{className:"text-sm text-strong",children:"Authorized for this project domain"}),e.jsx("span",{className:"text-xs text-muted",children:a.domain})]}),e.jsxs("p",{className:"mt-2 text-sm text-secondary",children:["This project uses ",e.jsx("code",{children:a.siteUrl}),"."]})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Selected site"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.siteUrl})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Last auth update"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.updatedAt?Dt(a.updatedAt):"—"})]})]})]})]}),e.jsxs(te,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:q.eyebrow}),e.jsx("h3",{children:q.title})]}),e.jsx("p",{className:"text-xs text-muted",children:u?.lastInspectedAt?`Last inspected ${Dt(u.lastInspectedAt)}`:"No inspection history yet"})]}),e.jsx("div",{className:"flex gap-1 border-b border-base",children:K.map(y=>e.jsx("button",{className:`px-3 py-1.5 text-xs font-medium border-b-2 transition-colors ${b===y.key?"border-mono-200 text-strong":"border-transparent text-muted hover:text-neutral"}`,onClick:()=>_(y.key),children:y.label},y.key))}),b==="coverage"&&u&&e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(vn,{label:"Indexed",value:u.summary.indexed,tone:"positive"}),e.jsx(vn,{label:"Not in index",value:u.summary.notIndexed+(u.summary.unknown??0),tone:"negative"}),e.jsx(vn,{label:"Status unknown",value:u.summary.unknown??0,tone:"neutral"}),e.jsx(vn,{label:"Coverage",value:`${u.summary.percentage}%`,tone:"neutral"})]}),u.notIndexed.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("h4",{className:"text-xs font-medium text-secondary",children:["Not Indexed (",u.notIndexed.length,")"]}),!H()&&e.jsx(A,{size:"sm",variant:"ghost",disabled:M,onClick:ye(le),children:M?"Submitting…":"Submit all to Bing"})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-16",children:"HTTP"}),!H()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:u.notIndexed.map(y=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:y.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:y.httpCode??"—"}),!H()&&e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-sm text-secondary hover:text-strong underline underline-offset-2",disabled:M,onClick:()=>{pe(y.url)},children:"Submit"})})]},y.id))})]})})]}),(u.unknown??[]).length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("h4",{className:"text-sm font-medium text-secondary",children:["Unknown, not yet confirmed (",(u.unknown??[]).length,")"]}),!H()&&e.jsx(A,{size:"sm",variant:"ghost",disabled:M,onClick:ye(le),children:M?"Submitting…":"Submit all to Bing"})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Last Crawled"}),!H()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:(u.unknown??[]).map(y=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:y.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:y.lastCrawledDate?Dt(y.lastCrawledDate):"—"}),!H()&&e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-sm text-secondary hover:text-strong underline underline-offset-2",disabled:M,onClick:()=>{pe(y.url)},children:"Submit"})})]},y.id))})]})})]}),u.indexed.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"mb-2 text-xs font-medium text-secondary",children:["Indexed (",u.indexed.length,")"]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Last Crawled"})]})}),e.jsx("tbody",{children:u.indexed.map(y=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:y.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:y.lastCrawledDate?Dt(y.lastCrawledDate):"—"})]},y.id))})]})})]})]}),b==="coverage"&&!u&&e.jsx("p",{className:"mt-4 text-xs text-muted",children:"No coverage data yet. Inspect URLs to build coverage data."}),b==="inspections"&&e.jsxs("div",{className:"mt-4 space-y-3",children:[!H()&&e.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{type:"text",className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:"URL to inspect",value:v,onChange:y=>j(y.target.value),onKeyDown:y=>{y.key==="Enter"&&U()}}),e.jsx(A,{size:"sm",disabled:!v.trim(),onClick:ye(U),children:"Inspect"})]}),k&&e.jsxs("div",{className:"rounded border border-base bg-bg-elevated/40 p-3 text-xs space-y-1",children:[e.jsx("div",{className:"font-medium text-strong",children:k.url}),e.jsxs("div",{className:"text-secondary",children:["In Index: ",e.jsx("span",{className:k.inIndex?"text-positive-400":"text-negative-400",children:k.inIndex?"Yes":"No"})," · ","HTTP: ",k.httpCode??"—"," · ","Crawled: ",k.lastCrawledDate??"—"]})]}),h.length>0&&e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-16",children:"Index"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-14",children:"HTTP"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Inspected"})]})}),e.jsx("tbody",{children:h.map(y=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:y.url}),e.jsx("td",{className:"py-1.5 px-3",children:e.jsx(Z,{tone:y.inIndex?"positive":"negative",children:y.inIndex?"Yes":"No"})}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:y.httpCode??"—"}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:Dt(y.inspectedAt)})]},y.id))})]})})]}),b==="performance"&&e.jsx("div",{className:"mt-4",children:m.length===0?e.jsx("p",{className:"text-xs text-muted",children:"No Bing performance data available."}):e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"Query"}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-16",children:yn[hs.Clicks]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-16",children:yn[hs.Impressions]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:yn[hs.CTR]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:yn[hs.Position]})]})}),e.jsx("tbody",{children:m.map((y,Y)=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:y.query}),e.jsx("td",{className:"py-1.5 px-3 text-right text-strong",children:y.clicks}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:y.impressions}),e.jsxs("td",{className:"py-1.5 px-3 text-right text-secondary",children:[(Number.isFinite(y.ctr)?y.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:y.averagePosition.toFixed(1)})]},Y))})]})})})]})]})}function Vm({projectName:t}){const s=as(),[n,a]=l.useState("google"),[r,i]=l.useState(!0),[c,u]=l.useState("idle"),[o,h]=l.useState(null),p=l.useRef(null),[m,g]=l.useState(!1),[k,R]=l.useState(null),[v,j]=l.useState(null),[D,O]=l.useState(!1),[E,F]=l.useState(null),[x,$]=l.useState(null),[M,se]=l.useState(0);async function de(K=!1){K||i(!0),h(null);try{const[q,y,Y]=await Promise.all([s.fetchQuery(Jr({client:V})).catch(()=>null),s.fetchQuery({...Ra({client:V,path:{name:t}}),staleTime:We}).catch(()=>[]),s.fetchQuery({...ei({client:V,path:{name:t}}),staleTime:We}).catch(()=>null)]),me=y.find(Q=>Q.connectionType==="gsc")??null;g(!!q?.google?.configured),O(!!q?.bing?.configured),R(me),F(Y);const[N,G]=await Promise.all([me?s.fetchQuery({...zr({client:V,path:{name:t}}),staleTime:We}).catch(()=>null):Promise.resolve(null),Y?.connected?s.fetchQuery({...ti({client:V,path:{name:t}}),staleTime:We}).catch(()=>null):Promise.resolve(null)]);j(N),$(G)}catch(q){h(q instanceof Error?q.message:"Failed to load search console overview")}finally{i(!1)}}async function C(){if(c!=="idle")return;p.current?.abort();const K=new AbortController;p.current=K;const q=K.signal;u("syncing"),h(null),xe({title:"Refreshing search coverage",detail:"Queueing Google and Bing checks, then reloading the workspaces.",tone:"neutral",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"});const y=[];try{async function Y(){if(!k)return;const Q=await ac(t);if(!Q?.id)return;const T=2e3,ce=Date.now()+12e4;for(;Date.now()<ce;){if(q.aborted||(await new Promise(Fe=>setTimeout(Fe,T)),q.aborted))return;const Ae=await Wr(Q.id).catch(()=>null);if(!Ae)break;if(["completed","failed","cancelled"].includes(Ae.status)){Ae.status!=="completed"&&y.push(`Google sync ${Ae.status}`);break}}}const me=10;async function N(){if(!E?.connected)return;const Q=await s.fetchQuery({...si({client:V,path:{name:t}}),staleTime:0}).catch(()=>[]),T=[...new Set(Q.map(ne=>ne.url))];if(T.length===0){await rc(t).catch(()=>null);return}for(let ne=0;ne<T.length;ne+=me){if(q.aborted)return;const ce=T.slice(ne,ne+me),Fe=(await Promise.allSettled(ce.map(Te=>ni(t,Te)))).filter(Te=>Te.status==="rejected").length;Fe>0&&y.push(`${Fe} Bing inspection(s) failed`)}}const G=await Promise.allSettled([Y(),N()]);for(const Q of G)Q.status==="rejected"&&y.push(Q.reason instanceof Error?Q.reason.message:"Sync failed");if(q.aborted)return;if(u("reloading"),await Promise.all([ze(s,"gsc"),ze(s,"bing")]),await de(!0),se(Q=>Q+1),y.length>0){const Q=`Partial refresh: ${y.join("; ")}`;h(Q),xe({title:"Search coverage partially refreshed",detail:Q,tone:"caution",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}else xe({title:"Search coverage refreshed",detail:"Google and Bing workspaces are reloaded with the latest stored coverage.",tone:"positive",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}catch(Y){if(!q.aborted){const me=Y instanceof Error?Y.message:"Refresh failed";h(me),xe({title:"Search coverage refresh failed",detail:me,tone:"negative",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}}finally{q.aborted||u("idle")}}l.useEffect(()=>(de(),()=>{p.current?.abort()}),[t]);const b=k?"positive":m?"caution":"negative",_=k?"Connected":m?"Ready to connect":"Needs setup",w=v?`${v.summary.percentage}% indexed`:k?"Awaiting coverage":"No coverage data",B=v?`${v.summary.notIndexed} not indexed${v.summary.deindexed>0?` · ${v.summary.deindexed} deindexed`:""}`:k?"Run sitemap inspection to populate coverage":m?"Connect Search Console for this domain":"Add Google OAuth credentials in Settings",oe=E?.connected?"positive":D?"caution":"negative",ee=E?.connected?"Connected":D?"Ready to connect":"Needs setup",U=x?`${x.summary.percentage}% indexed`:E?.connected?"Awaiting coverage":"No coverage data",pe=x?x.summary.notIndexed+(x.summary.unknown??0):0,le=x?`${pe} not in index`:E?.connected?"Inspect URLs to populate coverage":D?"Connect Bing Webmaster Tools for this domain":"Add a Bing API key in Settings";return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(te,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search engines"}),e.jsx("h2",{children:"Coverage and performance"})]}),!H()&&e.jsxs(A,{type:"button",variant:"outline",size:"sm",disabled:r||c!=="idle",onClick:()=>{C()},children:[e.jsx(tn,{className:`h-3.5 w-3.5 ${c!=="idle"?"animate-spin":""}`,"aria-hidden":"true"}),r?"Loading…":c==="syncing"?"Refreshing Google & Bing…":c==="reloading"?"Reloading workspaces…":"Refresh all"]})]}),o&&e.jsx("div",{className:"mb-3 rounded-lg border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:o}),e.jsx("div",{className:"mt-4 divide-y divide-default border-y border-default",children:[["Google Search Console",r?"Loading…":_,r?"neutral":b,r?"Loading overview…":B,w],["Bing Webmaster Tools",r?"Loading…":ee,r?"neutral":oe,r?"Loading overview…":le,U]].map(([K,q,y,Y,me])=>e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 py-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-heading",children:K}),e.jsx("span",{className:"ml-2 text-secondary",children:Y})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"tabular-nums text-secondary",children:me}),e.jsx(Z,{tone:y,children:q})]})]},K))})]}),e.jsx("div",{className:"flex flex-wrap gap-2",role:"tablist","aria-label":"Search engine workspaces",children:[["google","Google"],["bing","Bing"]].map(([K,q])=>e.jsx("button",{type:"button",role:"tab","aria-selected":n===K,className:`project-subnav-link ${n===K?"project-subnav-link-active":""}`,onClick:()=>a(K),children:q},K))}),n==="google"&&e.jsx(pd,{projectName:t,refreshNonce:M}),n==="bing"&&e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search engine"}),e.jsx("h2",{children:"Bing Webmaster Tools"})]})}),e.jsx(Hm,{projectName:t,refreshNonce:M})]})]})}function Zs({label:t,summary:s,displayValue:n,tooltip:a}){const r=s.value.trim()!==""&&Number.isFinite(Number(s.value)),i=s.progress!==void 0?Math.min(Math.max(s.progress,0),100):0;return e.jsxs("div",{className:"aeo-hero-row",children:[e.jsxs("p",{className:"aeo-hero-row-label",children:[t,(a||s.tooltip)&&e.jsx(Ke,{text:a||s.tooltip||""})]}),e.jsx("p",{className:`aeo-hero-row-value ${Xl[s.tone]}`,children:n??e.jsxs(e.Fragment,{children:[s.value,r?e.jsx("span",{className:"text-faint",children:"%"}):null]})}),e.jsx("div",{className:"aeo-hero-row-bar","aria-hidden":"true",children:e.jsx("div",{className:`metric-card-bar-fill progress-fill-${s.tone}`,style:{width:`${i}%`}})}),e.jsx("p",{className:"aeo-hero-row-detail",children:s.delta})]})}function Wm({model:t,sweepRunning:s}){const n=t.citationMovement,a=t.mentionMovement,r=t.movementComparison,i=t.recentRuns.find(g=>g.kind===fs["answer-visibility"]),c=g=>g.tone==="positive"?"improved":g.tone==="negative"?"declined":g.gained>0||g.lost>0?"mixed":"steady",u=c(a),o=c(n),h=(()=>{if(s)return"A fresh sweep is running now";if(!r.hasPreviousRun)return"Baseline captured. The next sweep will show change.";if(r.querySetChanged)return"Tracking scope changed since the previous sweep";if(u===o)return u==="steady"?"Answer mentions and citation coverage held steady":u==="mixed"?"Answer mention and citation movement was mixed":`Answer mentions and citation coverage ${u}`;const g=u==="mixed"?"Answer mention movement was mixed":u==="steady"?"Answer mentions held steady":`Answer mentions ${u}`,k=o==="mixed"?"citation movement was mixed":o==="steady"?"citation coverage held steady":`citation coverage ${o}`;return`${g}; ${k}`})(),p=[r.addedQueryCount>0&&`${r.addedQueryCount} ${r.addedQueryCount===1?"query":"queries"} added`,r.removedQueryCount>0&&`${r.removedQueryCount} ${r.removedQueryCount===1?"query":"queries"} removed`].filter(Boolean).join(", "),m=`${r.comparableQueryCount} comparable ${r.comparableQueryCount===1?"query":"queries"}`;return e.jsxs("section",{className:"overview-brief","aria-labelledby":"overview-brief-title",children:[e.jsxs("div",{className:"overview-brief-head",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"eyebrow eyebrow-soft",children:["Visibility",e.jsx(Ke,{text:"Each sweep records two independent signals: answer mentions (your brand named in the answer text) and source citations (your domain in the engine's source list). They move separately."})]}),e.jsx("h2",{id:"overview-brief-title",className:"overview-brief-title",children:h})]}),e.jsx("p",{className:"overview-brief-updated",children:i?`Updated ${i.startedAt}`:"No completed sweep"})]}),e.jsxs("div",{className:"overview-brief-grid",children:[e.jsxs("div",{className:"overview-brief-panel overview-brief-coverage",children:[e.jsx("p",{className:"overview-brief-label",children:"Coverage now"}),e.jsxs("div",{className:"aeo-hero-rows",children:[e.jsx(Zs,{label:"Mentioned",summary:t.mentionSummary}),e.jsx(Zs,{label:"Cited",summary:t.visibilitySummary})]}),t.mentionSummary.providerCoverage&&e.jsxs("p",{className:"overview-brief-note",children:["Partial sweep: ",t.mentionSummary.providerCoverage]})]}),e.jsxs("div",{className:"overview-brief-panel",children:[e.jsx("p",{className:"overview-brief-label",children:"Since last sweep"}),r.hasPreviousRun?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"overview-signal-change-list",children:[e.jsxs("div",{className:"overview-signal-change-row",children:[e.jsx("span",{className:"overview-signal-change-label",children:"Mentioned"}),a.gained===0&&a.lost===0?e.jsx("span",{className:"text-secondary",children:"No change"}):e.jsxs("span",{className:"flex gap-3 tabular-nums",children:[a.gained>0&&e.jsxs("span",{className:"text-positive-400",children:["+",a.gained]}),a.lost>0&&e.jsxs("span",{className:"text-negative-400",children:["-",a.lost]})]})]}),e.jsxs("div",{className:"overview-signal-change-row",children:[e.jsx("span",{className:"overview-signal-change-label",children:"Cited"}),n.gained===0&&n.lost===0?e.jsx("span",{className:"text-secondary",children:"No change"}):e.jsxs("span",{className:"flex gap-3 tabular-nums",children:[n.gained>0&&e.jsxs("span",{className:"text-positive-400",children:["+",n.gained]}),n.lost>0&&e.jsxs("span",{className:"text-negative-400",children:["-",n.lost]})]})]})]}),e.jsx("p",{className:`overview-brief-panel-copy ${r.querySetChanged?"text-caution-400/80":""}`,children:r.querySetChanged?`${p||"Query set changed"} · ${m}.`:`${m}.`})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"overview-brief-panel-title",children:"No comparison yet"}),e.jsx("p",{className:"overview-brief-panel-copy",children:"Run another sweep to measure mention and citation movement."})]})]})]})]})}function xa({id:t,eyebrow:s,title:n,meta:a,defaultOpen:r=!1,children:i}){return e.jsxs("details",{id:t,className:"overview-disclosure page-section-divider scroll-mt-24",open:r||void 0,children:[e.jsxs("summary",{className:"overview-disclosure-summary",children:[e.jsxs("span",{children:[e.jsx("span",{className:"eyebrow eyebrow-soft",children:s}),e.jsx("span",{className:"overview-disclosure-title",children:n})]}),e.jsxs("span",{className:"overview-disclosure-meta",children:[a&&e.jsx("span",{children:a}),e.jsx(La,{className:"overview-disclosure-icon",size:16,"aria-hidden":"true"})]})]}),e.jsx("div",{className:"overview-disclosure-body",children:i})]})}function Ym({summary:t,projectLabel:s}){const n=t.breakdown;if(n.perCompetitor.length===0)return null;const a=n.projectMentionSnapshots+n.competitorMentionSnapshots;if(a===0)return null;const r=[{label:`${s} (you)`,mentions:n.projectMentionSnapshots,isYou:!0},...n.perCompetitor.map(c=>({label:c.domain,mentions:c.mentionSnapshots,isYou:!1}))].sort((c,u)=>u.mentions-c.mentions),i=r[0]?.mentions??1;return e.jsxs("div",{className:"mention-share-breakdown",children:[e.jsx("p",{className:"mention-share-breakdown-title",children:"Mention share breakdown · latest run"}),e.jsx("ul",{className:"mention-share-breakdown-rows",children:r.map(c=>{const u=c.mentions/a*100;return e.jsxs("li",{className:"mention-share-breakdown-row",children:[e.jsx("span",{className:`mention-share-breakdown-label ${c.isYou?"text-heading font-medium":"text-secondary"}`,children:c.label}),e.jsx("div",{className:"mention-share-breakdown-bar",children:e.jsx("div",{className:`mention-share-breakdown-bar-fill ${c.isYou?"bg-positive-500/70":"bg-mono-500/60"}`,style:{width:`${Math.max(c.mentions/i*100,2)}%`}})}),e.jsx("span",{className:"mention-share-breakdown-count",children:c.mentions}),e.jsxs("span",{className:"mention-share-breakdown-share",children:[u.toFixed(1),"%"]})]},c.label)})})]})}function Jm({insights:t,suggestedQueries:s,projectName:n}){const{openEvidence:a}=Br(),r=Jl(),[i,c]=l.useState(new Set);if(t.length===0&&s.rows.length===0)return null;const u=j=>{c(D=>{const O=new Set(D);return O.delete(j),O})},o=j=>{c(D=>new Set(D).add(j)),r.mutate({projectName:n,queries:[j]},{onSuccess:()=>{xe({tone:"positive",title:`Tracking "${j}"`}),u(j)},onError:D=>{xe({tone:"negative",title:`Could not track "${j}"`,detail:String(D)}),u(j)}})},h=j=>e.jsxs("div",{className:"py-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:j.title}),j.detail?e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-secondary",children:j.detail}):null]}),e.jsx(Z,{tone:j.tone,children:j.actionLabel})]}),j.affectedPhrases.length>0?e.jsxs("details",{className:"mt-2",children:[e.jsxs("summary",{className:"w-fit cursor-pointer text-sm font-medium text-secondary transition-colors hover:text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:["Evidence · ",j.affectedPhrases.length," affected ",j.affectedPhrases.length===1?"query":"queries"]}),e.jsx("ul",{className:"mt-2 divide-y divide-subtle border-y border-subtle",children:j.affectedPhrases.map((D,O)=>e.jsxs("li",{className:"flex flex-wrap items-center gap-2 py-2",children:[e.jsx(ba,{state:D.citationState}),e.jsx("span",{className:"min-w-0 flex-1 text-sm text-strong",children:D.query}),D.provider?e.jsx(Ts,{provider:D.provider}):null,!H()&&D.evidenceId?e.jsx(A,{type:"button",variant:"ghost",size:"sm",onClick:()=>{a(D.evidenceId)},children:"View evidence"}):null]},D.evidenceId||`${j.id}-${O}`))})]}):null]},j.id),p=j=>{const D=i.has(j.query);return e.jsxs("div",{className:"flex items-center justify-between gap-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted",children:"Suggested query"}),e.jsx("p",{className:"mt-1 text-sm font-medium text-strong",children:j.query}),e.jsx("p",{className:"mt-0.5 text-sm text-secondary",children:j.reason})]}),H()?null:e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:D,"aria-label":`Track query "${j.query}"`,onClick:()=>o(j.query),children:D?"Tracking…":"Track"})]},j.query)},m=t.slice(0,1),g=s.rows.slice(0,1),k=t.slice(1),R=s.rows.slice(1),v=k.length+R.length;return e.jsxs("section",{className:"page-section-divider","aria-labelledby":"overview-signals-title",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"overview-signals-title",children:"Latest signals"})}),e.jsxs("div",{className:"divide-y divide-default border-y border-default",children:[m.map(h),g.map(p)]}),v>0?e.jsxs("details",{className:"mt-2",children:[e.jsxs("summary",{className:"w-fit cursor-pointer text-sm font-medium text-secondary transition-colors hover:text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:[v," more ",v===1?"signal":"signals"]}),e.jsxs("div",{className:"mt-2 divide-y divide-default border-y border-default",children:[k.map(h),R.map(p)]})]}):null]})}function dh(t){const{projectName:s}=Fi({from:"/projects/$projectName"}),a=Il()?.dashboard.projects.find(g=>g.project.name===s||g.project.id===s)?.project.name??null,r=Ne({...Dl({client:V}),enabled:!a}),i=a??r.data?.find(g=>g.name===s||g.id===s)?.name??null,{commandCenter:c,isLoading:u,latestVisibilityRevision:o,refetch:h}=El(i),p=!a&&r.isLoading||u;return!i&&!a&&r.isSuccess&&!u?e.jsx("div",{className:"page-container",children:e.jsxs(te,{className:"surface-card empty-card",children:[e.jsx("h1",{children:"Project not found"}),e.jsxs("p",{children:['Could not find a project named "',s,'".']}),e.jsx(A,{asChild:!0,children:e.jsx(zt,{to:"/",children:"Return to overview"})})]})}):!c||p?e.jsxs("div",{className:"page-skeleton",children:[e.jsxs("div",{className:"page-skeleton-header",children:[e.jsx("div",{className:"skeleton-text h-6 w-48"}),e.jsx("div",{className:"skeleton-text-sm w-32"})]}),e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[1,2,3].map(g=>e.jsxs("div",{className:"page-skeleton-card flex flex-col items-center",children:[e.jsx("div",{className:"skeleton-circle size-20"}),e.jsx("div",{className:"skeleton-text w-16 mt-3"})]},g))}),e.jsxs("div",{className:"page-skeleton-card",children:[e.jsx("div",{className:"skeleton-text w-28"}),e.jsx("div",{className:"space-y-2 mt-2",children:[1,2,3,4].map(g=>e.jsx("div",{className:"skeleton-text-sm w-full"},g))})]})]}):e.jsx(Zm,{model:c,refetch:h,latestVisibilityRevision:o,...t})}function Xm({items:t,activeTab:s}){const[n,a]=l.useState(!1),r=l.useRef(null);if(l.useEffect(()=>{if(!n)return;const c=o=>{r.current&&!r.current.contains(o.target)&&a(!1)},u=o=>{o.key==="Escape"&&a(!1)};return document.addEventListener("pointerdown",c),document.addEventListener("keydown",u),()=>{document.removeEventListener("pointerdown",c),document.removeEventListener("keydown",u)}},[n]),t.length===0)return null;const i=t.some(c=>c.key===s);return e.jsxs("div",{className:"project-subnav-more",ref:r,children:[e.jsxs("button",{type:"button",className:`project-subnav-link project-subnav-more-trigger ${i?"project-subnav-link-active":""}`,"aria-haspopup":"menu","aria-expanded":n,onClick:()=>a(c=>!c),children:["More",e.jsx(La,{className:"h-3.5 w-3.5","aria-hidden":"true"})]}),n?e.jsx("div",{className:"project-subnav-menu",role:"menu",children:t.map(c=>e.jsx(zt,{to:c.href,role:"menuitem",className:`project-subnav-menu-item ${c.key===s?"project-subnav-menu-item-active":""}`,"aria-current":c.key===s?"page":void 0,onClick:()=>a(!1),children:c.label},c.key))}):null]})}function Zm({tab:t,model:s,refetch:n,latestVisibilityRevision:a}){const r=_i(),i=as(),c=l.useMemo(()=>{const S=Ml();return S?ql(S.projectTabs):void 0},[]),u=Ol(t,c),o=l.useMemo(()=>s.competitors.map(S=>S.domain),[s.competitors]),[h,p]=l.useState(!1),[m,g]=l.useState(!1),[k,R]=l.useState(!1),[v,j]=l.useState(""),[D,O]=l.useState(!1),[E,F]=l.useState(null),[x,$]=l.useState(!1),[M,se]=l.useState(""),[de,C]=l.useState(!1),[b,_]=l.useState(void 0),[w,B]=l.useState(!1),[oe,ee]=l.useState(null),[U,pe]=l.useState(null),[le,K]=l.useState(!1),q=s?.visibilityEvidence??[],y=s?.project.name??"",Y=s?.project.displayName||s?.project.name||y,me=Kl(),N=Ne({...Fl({client:V,path:{name:y}}),enabled:u==="portfolio"&&!!y,staleTime:0,refetchOnMount:"always"}),G=Ne({..._l({client:V,path:{name:y}}),enabled:u==="portfolio"&&!!y,staleTime:0,refetchOnMount:"always"}),Q=G.isPending||G.isFetching,T=G.data?.active?.revision??null,ne=Ne({...Ul({client:V,path:{name:y},query:{revision:T??1}}),enabled:u==="portfolio"&&T!==null&&!Q&&!G.isError,staleTime:0,refetchOnMount:"always"}),ce=(s?.recentRuns??[]).some(S=>S.kind===fs["answer-visibility"]&&(S.status===sr.running||S.status===sr.queued)),Ae=l.useMemo(()=>(s?.project.locations??[]).map(S=>S.label),[s?.project.locations]),Fe=l.useMemo(()=>new Set(q.map(S=>S.location??"")),[q]),Te=Fe.has(""),Me=l.useMemo(()=>[...new Set(q.map(S=>S.query))].sort((S,re)=>S.localeCompare(re)),[q]),Se=l.useMemo(()=>{const S=[...Fe].filter(Boolean);return S.length>1?S:Ae},[Fe,Ae]);l.useEffect(()=>{if(b===void 0||b===""||!y){pe(null),K(!1);return}K(!0),Bl(y,b,20).then(S=>{pe(S),K(!1)}).catch(()=>{pe(null),K(!1)})},[b,y]);const ct=l.useMemo(()=>{if(!U)return null;const S=new Map;for(const re of U){for(const[he,it]of Object.entries(re.providerRuns??{}))S.set(`${re.query}::${he}`,it.map($e=>({runId:$e.runId,citationState:$e.citationState,createdAt:$e.createdAt,answerMentioned:$e.answerMentioned,visibilityState:$e.visibilityState,visibilityTransition:$e.visibilityTransition,mentionState:$e.mentionState,mentionTransition:$e.mentionTransition})));(!re.providerRuns||Object.keys(re.providerRuns).length===0)&&S.set(`${re.query}::`,re.runs.map(he=>({runId:he.runId,citationState:he.citationState,createdAt:he.createdAt,answerMentioned:he.answerMentioned,visibilityState:he.visibilityState,visibilityTransition:he.visibilityTransition,mentionState:he.mentionState,mentionTransition:he.mentionTransition})))}return S},[U]),Xe=l.useMemo(()=>{let S=b!==void 0?q.filter(re=>b===""?!re.location:re.location===b):q;if(oe){const re=oe.toLowerCase();S=S.filter(he=>he.competitorDomains.some(it=>it.toLowerCase()===re))}return ct?S.map(re=>{const he=ct.get(`${re.query}::${re.provider}`)??ct.get(`${re.query}::`);return he?{...re,runHistory:he}:re}):S},[q,b,oe,ct]);async function _e(){try{await me.mutateAsync({projectName:y,projectLabel:Y,sourceAction:"project-run"}),n()}catch{}}async function X(){g(!0);try{await Gl(y),xe({title:"Project deleted",detail:`${Y} was removed.`,tone:"positive",dedupeKey:`project:delete:${y}`,dedupeMode:"drop"}),r({to:"/"}),n()}catch(S){console.error("Failed to delete project:",S)}finally{g(!1)}}async function Pe(){const S=v.split(`
|
|
8
|
+
`).map(re=>re.trim()).filter(Boolean);if(S.length!==0){O(!0);try{await nr(y,S),n(),j("")}finally{O(!1)}}}async function Ie(S){F(S);try{await tc(y,[S]),n()}catch(re){xe({title:"Could not remove query",detail:re instanceof Error?re.message:`Failed to remove "${S}"`,tone:"negative",dedupeKey:"query:remove",dedupeMode:"replace"})}finally{F(null)}}async function ht(){const S=M.trim();if(S){C(!0);try{await Zl(y,[S]),n(),se(""),$(!1)}finally{C(!1)}}}async function L(S){const re=s.competitors.find(he=>he.domain===S);if(!re){xe({title:"Could not remove competitor",detail:`Could not find ${S} in the tracked competitor list`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"});return}try{await ec(y,re.id),n()}catch(he){xe({title:"Could not remove competitor",detail:he instanceof Error?he.message:`Failed to remove ${re.domain}`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"})}}async function ve(S,re){const he=await sc(S,re);return await i.invalidateQueries({queryKey:Xr({client:V})}),i.setQueryData(nc({client:V,path:{name:S}}),he),zm(i,he),he}async function De(S){const{data:re}=await Yl({client:V,path:{name:y},body:S,throwOnError:!0});return re}async function Rt(S){const re=await nr(y,[...S]);return i.setQueryData(Wl({client:V,path:{name:y}}),re),n(),re}async function Re(S){const{data:re}=await Vl({client:V,path:{name:y},body:S,throwOnError:!0});return re}async function Yt(S){const{data:re}=await Hl({client:V,path:{name:y},body:S,throwOnError:!0});return re}async function dt(S,re){const{data:he}=await Ql({client:V,path:{name:y},body:{expectedActiveRevision:re,plan:S},throwOnError:!0});return await i.invalidateQueries({queryKey:zl({client:V,path:{name:y}})}),he}const Be=`/projects/${encodeURIComponent(s.project.name)}`,ut=[{key:"overview",label:"Overview",href:Be},...H()?[]:[{key:"portfolio",label:"Portfolio",href:`${Be}/portfolio`}],{key:"search-console",label:"Search Engines",href:`${Be}/search-console`},{key:"activity",label:"Activity",href:`${Be}/activity`},{key:"technical-aeo",label:"Technical AEO",href:`${Be}/technical-aeo`},{key:"local",label:"Local Presence",href:`${Be}/local`},{key:"discovery",label:"Query Discovery",href:`${Be}/discovery`},{key:"backlinks",label:"Backlinks",href:`${Be}/backlinks`}],qt=[{key:"report",label:"Report",href:`${Be}/report`},{key:"history",label:"Change History",href:`${Be}/history`}],Nt=ut.filter(S=>Vn(S.key,c)),xt=qt.filter(S=>Vn(S.key,c)),Ze=Vn("settings",c)?{key:"settings",label:"Settings",href:`${Be}/settings`}:null;function Ot(S,re=!1){const he=document.getElementById(S);if(!he)return;re&&he instanceof HTMLDetailsElement&&(he.open=!0);const it=window.matchMedia("(prefers-reduced-motion: reduce)").matches;window.requestAnimationFrame(()=>{he.scrollIntoView({behavior:it?"auto":"smooth",block:"start"}),(he instanceof HTMLDetailsElement?he.querySelector("summary"):he)?.focus({preventScroll:!0})})}return e.jsxs("div",{className:"page-container",children:[h?e.jsxs(te,{className:"surface-card p-6 mb-6 border-negative-800/60",children:[e.jsx("h3",{className:"text-base font-semibold text-negative-400 mb-2",children:"Delete project?"}),e.jsxs("p",{className:"text-sm text-secondary mb-4",children:["This will permanently delete ",e.jsx("strong",{className:"text-strong",children:s.project.displayName||s.project.name})," and all its queries, competitors, runs, and snapshots. This cannot be undone."]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(A,{type:"button",variant:"destructive",disabled:m,onClick:ye(X),children:m?"Deleting...":"Yes, delete project"}),e.jsx(A,{type:"button",variant:"outline",disabled:m,onClick:()=>p(!1),children:"Cancel"})]})]}):null,e.jsxs("div",{className:"page-header",children:[e.jsxs("div",{className:"page-header-left",children:[e.jsx("h1",{className:"page-title",children:s.project.displayName||s.project.name}),e.jsxs("p",{className:"page-subtitle",children:[s.project.canonicalDomain," · ",s.contextLabel]}),!H()&&e.jsxs("div",{className:"tag-row",children:[e.jsx("span",{className:"tag",children:s.project.country}),e.jsx("span",{className:"tag",children:s.project.language.toUpperCase()}),s.project.tags.map(S=>e.jsx("span",{className:"tag",children:S},S))]})]}),e.jsxs("div",{className:"page-header-right",children:[e.jsx("p",{className:"text-sm text-muted",children:s.dateRangeLabel}),!H()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(A,{type:"button",variant:"outline",size:"icon",onClick:()=>p(!0),"aria-label":"Delete project",children:e.jsx(vc,{className:"h-4 w-4 text-secondary"})}),e.jsx(A,{type:"button",disabled:me.isPending||ce,onClick:ye(_e),children:me.isPending?"Starting…":ce?"Sweep running…":"Run now"})]})]})]}),e.jsxs("nav",{className:"project-subnav","aria-label":"Project sections",children:[Nt.map(S=>e.jsx(zt,{to:S.href,className:`project-subnav-link ${S.key===u?"project-subnav-link-active":""}`,"aria-current":S.key===u?"page":void 0,children:S.label},S.key)),e.jsxs("div",{className:"project-subnav-trailing",children:[e.jsx(Xm,{items:xt,activeTab:u}),Ze&&e.jsx(zt,{to:Ze.href,className:`project-subnav-link ${u==="settings"?"project-subnav-link-active":""}`,"aria-current":u==="settings"?"page":void 0,children:Ze.label},Ze.key)]})]}),u==="portfolio"&&!H()?e.jsx(jm,{projectName:y,locations:s.project.locations,queries:N.data??[],isQueryLoading:N.isPending||N.isFetching,isQueryError:N.isError,onRetryQueries:()=>{N.refetch()},activePlan:G.data?.active??null,isPlanLoading:Q,isPlanError:G.isError,onRetryPlan:()=>{G.refetch()},report:ne.data??null,isReportLoading:ne.isPending||ne.isFetching,isReportError:ne.isError,onRetryReport:()=>{ne.refetch()},onDiscover:De,onCreateQueries:Rt,onCompilePlan:Re,onDiffPlan:Yt,onPublishPlan:dt},y):u==="overview"?e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"page-section-divider",children:e.jsx(wu,{projectName:s.project.name,competitorDomains:o,analyticsRevision:a})}),e.jsx(Wm,{model:s,sweepRunning:ce}),e.jsx(Jm,{insights:s.insights,suggestedQueries:s.suggestedQueries,projectName:s.project.name}),e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Competitive"}),e.jsx("h2",{children:"Where competitors are winning"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("p",{className:"supporting-copy",children:[s.competitors.length," tracked"]}),!H()&&e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>$(!x),children:x?"Cancel":"+ Add competitor"})]})]}),e.jsxs("div",{className:"aeo-hero competitive-summary",children:[e.jsxs("div",{className:"aeo-hero-rows",children:[e.jsx(Zs,{label:"Mention share",summary:s.mentionShareSummary,tooltip:"Of all brand mentions in answer text across your tracked queries (you + tracked competitors), the percentage that were you. Measured from the latest sweep."}),e.jsx(Zs,{label:"Mention gaps",summary:s.mentionGaps,displayValue:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-primary",children:s.mentionGaps.value}),e.jsxs("span",{className:"text-faint",children:[" / ",s.queryCounts.total]})]}),tooltip:"Queries where a competitor was mentioned in the answer but your brand was not."}),e.jsx(Zs,{label:"Citation gaps",summary:s.gapQueries,displayValue:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-primary",children:s.gapQueries.value}),e.jsxs("span",{className:"text-faint",children:[" / ",s.queryCounts.total]})]}),tooltip:"Queries where a competitor was cited as a source but you were not."})]}),e.jsx(Ym,{summary:s.mentionShareSummary,projectLabel:s.project.displayName||s.project.name})]}),x&&e.jsxs("div",{className:"mt-4 mb-3 flex gap-2 rounded-lg border border-base bg-bg-elevated/40 p-3",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"text",placeholder:"competitor.com",value:M,onChange:S=>se(S.target.value),onKeyDown:S=>{S.key==="Enter"&&ht()}}),e.jsx(A,{type:"button",size:"sm",disabled:!M.trim()||de,onClick:ye(ht),children:de?"Adding...":"Add"})]}),s.competitors.length>0&&e.jsxs("details",{className:"inline-disclosure mt-4",children:[e.jsx("summary",{children:"Review tracked competitors"}),e.jsx("div",{className:"mt-3",children:e.jsx(Yc,{competitors:s.competitors,onSelectCompetitor:S=>{ee(S),Ot("evidence-section",!0)},onRemoveCompetitor:H()?void 0:S=>{L(S)},activeFilter:oe})})]})]}),e.jsxs(xa,{id:"evidence-section",eyebrow:"Tracked coverage",title:"Query evidence",meta:`${s.queryCounts.total} ${s.queryCounts.total===1?"query":"queries"}`,defaultOpen:H(),children:[!H()&&e.jsx("div",{className:"mb-3 flex items-center justify-end",children:e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>R(!k),children:k?"Done":"Manage queries"})}),!H()&&k&&e.jsxs("div",{className:"mb-3 rounded-lg border border-base bg-bg-elevated/40 p-3",children:[Me.length>0?e.jsx("ul",{className:"mb-3 max-h-64 divide-y divide-mono-800/60 overflow-y-auto rounded border border-default",children:Me.map(S=>e.jsxs("li",{className:"flex items-center justify-between gap-3 px-3 py-2",children:[e.jsx("span",{className:"min-w-0 truncate text-sm text-strong",title:S,children:S}),e.jsx("button",{type:"button",className:"shrink-0 rounded px-1.5 py-0.5 text-xs text-muted transition-colors hover:text-negative-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-negative-500 disabled:opacity-50","aria-label":`Remove query ${S}`,title:`Stop tracking "${S}"`,disabled:E!==null,onClick:()=>{Ie(S)},children:E===S?"Removing…":"Remove"})]},S))}):e.jsx("p",{className:"mb-3 text-xs text-muted",children:"No queries tracked yet. Add some below."}),e.jsx("textarea",{className:"w-full resize-none rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",rows:3,placeholder:"Enter queries to add, one per line",value:v,onChange:S=>j(S.target.value)}),e.jsxs("div",{className:"mt-2 flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-muted",children:[v.split(`
|
|
9
|
+
`).filter(S=>S.trim()).length," to add"]}),e.jsx(A,{type:"button",size:"sm",disabled:!v.trim()||D,onClick:ye(Pe),children:D?"Adding...":"Add queries"})]})]}),s.project.locations.length>0&&e.jsxs("div",{className:"filter-row mb-3",role:"toolbar","aria-label":"Location filters",children:[e.jsx("button",{className:`filter-chip ${b===void 0?"filter-chip-active":""}`,type:"button","aria-pressed":b===void 0,onClick:()=>{_(void 0)},children:"All locations"}),s.project.locations.map(S=>e.jsx("button",{className:`filter-chip ${b===S.label?"filter-chip-active":""}`,type:"button","aria-pressed":b===S.label,onClick:()=>{_(S.label),B(!1)},children:S.label},S.label)),Te&&e.jsx("button",{className:`filter-chip ${b===""?"filter-chip-active":""}`,type:"button","aria-pressed":b==="",onClick:()=>{_(""),B(!1)},children:"No location"}),Se.length>1&&b===void 0&&e.jsx("button",{className:`filter-chip filter-chip-compare ${w?"filter-chip-active":""}`,type:"button","aria-pressed":w,onClick:()=>B(S=>!S),title:"Side-by-side location comparison",children:"Compare"})]}),oe&&e.jsxs("div",{className:"mb-3 flex items-center gap-2 rounded-md border border-negative-900/40 bg-negative-950/20 px-3 py-2",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-wide text-negative-400",children:"Competitor filter"}),e.jsxs("span",{className:"text-sm text-strong",children:["Showing queries where ",e.jsx("span",{className:"font-semibold",children:oe})," surfaced"]}),e.jsx("button",{type:"button",className:"ml-auto text-xs text-secondary hover:text-strong",onClick:()=>ee(null),children:"Clear filter ×"})]}),e.jsx(zc,{evidence:Xe,compareLocations:w})]}),e.jsxs(xa,{eyebrow:"Analysis",title:"Citation and engine diagnostics",meta:"Deep dive",defaultOpen:H(),children:[e.jsx(Ud,{projectName:s.project.name}),s.providerScores.length>1&&e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Model breakdown"}),e.jsxs("h2",{children:["Citation rate by model ",e.jsx(Ke,{text:"Per-model citation rate in the latest sweep. The same query set can perform differently across engines."})]})]})}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Model"}),e.jsx("th",{scope:"col",children:"Citation rate"}),e.jsx("th",{scope:"col",children:"Cited queries"})]})}),e.jsx("tbody",{children:s.providerScores.map(S=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"flex flex-col items-start gap-0.5",children:[e.jsx(Ts,{provider:S.provider}),S.model&&e.jsx("span",{className:"text-[11px] font-mono text-muted",children:S.model})]})}),e.jsx("td",{children:e.jsxs("span",{className:"font-semibold text-strong",children:[S.score,"%"]})}),e.jsxs("td",{className:"text-muted",children:[S.cited," of ",S.total]})]},`${S.provider}::${S.model??"unknown"}`))})]})})]})]}),!H()&&e.jsx(xa,{eyebrow:"Run history",title:"Recent execution history",meta:`${s.recentRuns.length} recent`,children:e.jsx("div",{className:"run-list",children:s.recentRuns.map(S=>e.jsx(uc,{run:S},S.id))})})]}):u==="settings"?e.jsxs(e.Fragment,{children:[e.jsx(Km,{project:{...s.project,displayName:s.project.displayName??s.project.name,defaultLocation:s.project.defaultLocation??null},onUpdateProject:async(S,re)=>{await ve(S,re)},onRefresh:()=>{n()}}),e.jsx(_m,{project:s.project,onSave:async S=>{await ve(s.project.name,S)}}),e.jsx(Bm,{projectName:s.project.name}),e.jsx(Qm,{projectName:s.project.name})]}):u==="report"?e.jsx(wm,{projectName:s.project.name}):u==="discovery"?e.jsx(Lu,{projectName:y}):u==="technical-aeo"?e.jsx(Gu,{projectName:s.project.name,projectId:s.project.id}):u==="history"?e.jsx(Qu,{projectName:s.project.name}):u==="activity"?e.jsx(ad,{projectName:s.project.name}):u==="backlinks"?e.jsx(_d,{projectName:s.project.name}):u==="local"?e.jsx(fd,{projectName:s.project.name,projectId:s.project.id}):u==="search-console"?e.jsx(Vm,{projectName:s.project.name}):null]})}export{dh as ProjectPage,zm as patchProjectDashboardCache};
|