@ainyc/canonry 4.115.0 → 4.116.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/assets/{BacklinksPage-DhXsZ8Sb.js → BacklinksPage-Dy6Xc-LT.js} +1 -1
- package/assets/assets/{ChartPrimitives-Cdj0P8uG.js → ChartPrimitives-CHJh5M8x.js} +1 -1
- package/assets/assets/ProjectPage-Bjfa4CI5.js +7 -0
- package/assets/assets/{RunRow-GJ_2CEif.js → RunRow-DmvQnWPf.js} +1 -1
- package/assets/assets/{RunsPage-upaDiLFK.js → RunsPage-BxkxQEKE.js} +1 -1
- package/assets/assets/{SettingsPage-FbmEaN16.js → SettingsPage-DCyqHqDh.js} +1 -1
- package/assets/assets/{TrafficPage-Di0H5JRu.js → TrafficPage-BT_ae5aO.js} +1 -1
- package/assets/assets/{TrafficSourceDetailPage-Bc2mxXSV.js → TrafficSourceDetailPage-Cps-tSHn.js} +1 -1
- package/assets/assets/{arrow-left-yOCIy3_x.js → arrow-left-D8vdqhx4.js} +1 -1
- package/assets/assets/{extract-error-message-tCNIzznL.js → extract-error-message-BOY5txUA.js} +1 -1
- package/assets/assets/{index-Bb5yUz7k.css → index-B4R1-8hR.css} +1 -1
- package/assets/assets/{index-D0ZdnFQf.js → index-DxjY63VC.js} +89 -89
- package/assets/assets/{trash-2-gRyTO-PS.js → trash-2-ap_Fa4zA.js} +1 -1
- package/assets/index.html +2 -2
- package/dist/{chunk-PGVGHGIX.js → chunk-GV665WOU.js} +4 -4
- package/dist/{chunk-VEUBAZRG.js → chunk-IQPMK36Y.js} +1352 -1199
- package/dist/{chunk-MO7GPMNV.js → chunk-RVH6QPTA.js} +1 -1
- package/dist/{chunk-BXNFOGDF.js → chunk-WEAXJ25Y.js} +420 -87
- package/dist/cli.js +57 -9
- package/dist/index.js +4 -4
- package/dist/{intelligence-service-2C7H4C6A.js → intelligence-service-HEN5HLUM.js} +2 -2
- package/dist/mcp.js +2 -2
- package/package.json +7 -7
- package/assets/assets/ProjectPage-DAWtJQ3w.js +0 -7
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{j as e,r as l,L as yt,n as vt,u as Ie,o as ms,A as ai,B as ii,h as ri}from"./vendor-tanstack-Be8JdV5M.js";import{c as Fs,T as oe,t as oi,a as li,u as ga,C as ci,b as Gs,P as Qt,B as D,h as di,d as ui,e as mi,f as Je,g as W,i as T,j as ae,I as De,k as os,l as xi,m as Z,n as hi,o as pi,p as gi,q as fi,r as fa,s as bi,v as ji,S as Pt,w as yi,x as vi,y as Ni,z as Ot,A as wi,D as En,E as Si,G as Oe,F as bn,H as ki,J as Ci,K as Ai,L as $i,M as Pi,N as K,O as On,Q as ba,R as Di,U as Li,V as Ii,W as Ri,X as Ti,Y as Mi,Z as Ei,_ as Oi,$ as Bi,a0 as Fi,a1 as Gi,a2 as qi,a3 as _i,a4 as Ui,a5 as zi,a6 as Ki,a7 as xs,a8 as Qi,a9 as Hi,aa as Bn,ab as Wi,ac as Vi,ad as Yi,ae as Xi,af as Ms,ag as Ji,ah as Zi,ai as er,aj as tr,ak as un,al as sr,am as nr,an as ar,ao as ir,ap as Qs,aq as Ut,ar as ja,as as ya,at as rr,au as or,av as va,aw as lr,ax as cr,ay as dr,az as ur,aA as mr,aB as xr,aC as Na,aD as hr,aE as wa,aF as pr,aG as gr,aH as fr,aI as br,aJ as qs,aK as jr,aL as yr,aM as vr,aN as Nr,aO as wr,aP as Sr,aQ as kr,aR as Cr,aS as Ar,aT as $r,aU as Pr,aV as Dr,aW as Lr,aX as Ir,aY as Rr,aZ as Tr,a_ as Hs,a$ as Mr,b0 as Er,b1 as Fn,b2 as Or,b3 as Br,b4 as Fr,b5 as Gr,b6 as qr,b7 as _r,b8 as Ur,b9 as zr,ba as Kr,bb as Qr,bc as Hr,bd as Wr,be as Gn,bf as Vr,bg as Ws,bh as Yr,bi as qn,bj as _n,bk as Xr,bl as Jr,bm as Zr,bn as eo,bo as to,bp as so,bq as no,br as ao,bs as io,bt as Sa,bu as ka,bv as ro,bw as Ca,bx as oo,by as Aa,bz as lo,bA as co,bB as Cs,bC as uo,bD as mo,bE as xo,bF as Un}from"./index-DxjY63VC.js";import{R as ho}from"./RunRow-DmvQnWPf.js";import{f as Ht,C as ut,a as et,b as mt,c as Dt,d as ze,e as Qe,g as Es,h as po,i as jn,p as go}from"./ChartPrimitives-CHJh5M8x.js";import{u as fo,t as bo,R as dt,e as zn}from"./extract-error-message-BOY5txUA.js";import{R as Wt,C as Vt,X as Yt,Y as Xt,T as Jt,L as $a,A as Ft,a as yn,b as jo,d as vn}from"./vendor-recharts-C9EZkgbP.js";import{C as Pa,D as Gt,a as yo,T as vo}from"./trash-2-ap_Fa4zA.js";import"./vendor-radix-CQ77EO2y.js";import"./vendor-markdown-6dwjPOKK.js";const No=[["path",{d:"M5 12h14",key:"1ays0h"}]],wo=Fs("minus",No);const So=[["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"}]],ko=Fs("scan-search",So);const Co=[["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"}]],Ao=Fs("unplug",Co);const $o=[["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"}]],Po=Fs("upload",$o);function Rs(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 Do(t,s){return s<=0?null:Math.round((t-s)/s*100)}function Vs(t,s,n="vs prior 7 days"){return t.deltaPct===null?t.prior===0?"First baseline week":"":t.deltaPct>0?`Up ${t.deltaPct}% ${n} (${Rs(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${Rs(t.prior)} ${s})`:`Flat ${n} (${Rs(t.prior)} ${s})`}const Da=30;function Kn(t){return Math.round(t*10)/10}function Lo(t){return t.prior>=Da&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% vs prior`:`${t.deltaAbs>0?"+":""}${Kn(t.deltaAbs)} vs ${Kn(t.prior)}`}function Io(t,s,n){return t.prior>=Da&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% ${n}`:`${t.deltaAbs>0?"+":""}${Rs(Math.round(t.deltaAbs))} ${s} ${n}`}const Ro=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function La(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function Ia(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 Ra(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(La).map(Ia).filter(Boolean)):new Set}function Ta(t,s){const n=La(t).map(Ia).filter(Boolean).filter(a=>!Ro.has(a)).filter(a=>!s.has(a));return[...new Set(n)].sort().join(" ")}function To(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function Mo(t,s){const n=Ra(t);if(s.length<=1||n.size===0)return[...s];const a=new Set,i=[];for(const r of s){if(r.category!=="content"){i.push(r);continue}const o=Ta(To(r),n);!o||a.has(o)||(a.add(o),i.push(r))}return i}function Eo(t){const s=Ra(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const a=new Set;return n.filter(i=>{const r=Ta(i.query,s);return!r||a.has(r)?!1:(a.add(r),!0)})}function mn({state:t,label:s}){return e.jsx(oe,{tone:li(t),children:s??oi(t)})}function Qn({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"},i=new Date(n[0].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),r=new Date(n[n.length-1].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"});return e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-[9px] text-faint shrink-0",children:i}),e.jsx("div",{className:"flex items-center gap-[3px]",title:`${n.length} runs`,children:n.map((o,p)=>e.jsx("div",{className:`h-2.5 w-2.5 rounded-sm ${a[o.citationState]??"bg-mono-700"} ${o.model&&p>0&&n[p-1]?.model&&n[p-1].model!==o.model?"ring-1 ring-caution-300/80 ring-offset-1 ring-offset-bg":""}`,title:[o.citationState,new Date(o.createdAt).toLocaleDateString(),o.model?`model ${o.model}`:null,o.model&&p>0&&n[p-1]?.model&&n[p-1].model!==o.model?"model changed":null].filter(Boolean).join(" — ")},p))}),e.jsx("span",{className:"text-[9px] text-faint shrink-0",children:r})]})}function xn(t){const s=new Map;for(const a of t)for(const i of a.runHistory){const r=s.get(i.createdAt);r?r.states.push(i.citationState):s.set(i.createdAt,{states:[i.citationState],runId:i.runId})}return[...s.entries()].sort(([a],[i])=>a.localeCompare(i)).map(([a,{states:i,runId:r}])=>({runId:r,createdAt:a,citationState:i.includes("cited")?"cited":i.includes("emerging")?"emerging":"not-cited"}))}const Oo=320;function Hn(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 Wn(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 Vn(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 i=t[t.length-1].citationState,r=t[t.length-2].citationState;if(r!=="cited"&&i==="cited")return`Newly ${n}`;if(r==="cited"&&i!=="cited")return"Lost since last run";let o=0;for(let p=t.length-1;p>=0&&t[p].citationState===i;p--)o++;return i==="cited"?o<=1?`${a} in latest run`:`${a} for ${o} runs`:o<=1?`Not ${n} in latest run`:`Not ${n} across ${o} runs`}function Bo(t,s){return t.map(n=>Ma(n,s))}function Ma(t,s){return s==="citations"?t:{...t,citationState:Hn(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:Hn(n,s)}))}}function Yn(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 i=t[t.length-1].citationState,r=t.length>=2?t[t.length-2].citationState:null,o=i==="cited"||i==="emerging",p=r==="cited"||r==="emerging";return i==="lost"||r!==null&&p&&!o?{key:s,label:`Lost ${n}`,tone:"negative"}:i==="emerging"||r!==null&&!p&&o?{key:s,label:`New ${n}`,tone:"positive"}:r===null&&o?{key:s,label:`First ${n}`,tone:"positive"}:o?{key:s,label:s==="mentions"?"Still mentioned":"Still cited",tone:"neutral"}:{key:s,label:`No ${n}`,tone:"neutral"}}function Fo(t){const s=xn(Bo(t,"mentions")),n=xn(t);return[Yn(s,"mentions"),Yn(n,"citations")]}function Go({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 Xn({items:t}){return e.jsx("div",{className:"mt-1 flex flex-wrap gap-1","aria-label":"Latest run mention and citation signals",children:Fo(t).map(s=>e.jsx(Go,{signal:s},s.key))})}function qo({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:a}=ga(),[i,r]=l.useState(new Set),[o,p]=l.useState("mentions"),[x,m]=l.useState(n),f=l.useMemo(()=>{const w=new Map;for(const C of t){const P=C.query,F=s?C.location??null:null,M=s?JSON.stringify([P,F]):P,_=w.get(M)??{key:M,phrase:P,location:F,items:[],rawItems:[]};_.items.push(Ma(C,o)),_.rawItems.push(C),w.set(M,_)}return[...w.values()]},[t,o,s]),d=w=>{r(C=>{const P=new Set(C);return P.has(w)?P.delete(w):P.add(w),P})},R=o==="mentions"?"mentioned":"cited",h=o==="mentions"?"Mention History":"Citation History",A=o==="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":o==="mentions",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${o==="mentions"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>p("mentions"),children:"Mentions"}),e.jsx("button",{type:"button",role:"tab","aria-selected":o==="citations",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${o==="citations"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>p("citations"),children:"Citations"})]}),e.jsx("span",{className:"text-[11px] text-muted",children:o==="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:()=>{r(w=>w.size===f.length?new Set:new Set(f.map(C=>C.key)))},children:i.size===f.length&&f.length>0?"Collapse all":"Expand all"}),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":x==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${x==="compact"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>m("compact"),children:"Compact"}),e.jsx("button",{type:"button",role:"tab","aria-selected":x==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${x==="detailed"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>m("detailed"),children:"Detailed"})]})]})]})]}),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:h}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:f.map(({key:w,phrase:C,location:P,items:F,rawItems:M})=>{const _=i.has(w),u=F.map(L=>L.citationState),S=u.includes("cited")?"cited":u.includes("emerging")?"emerging":u.includes("lost")?"lost":u.every(L=>L==="pending")?"pending":"not-cited",Q=xn(F),v=F.filter(L=>L.citationState===ci.cited||L.citationState==="emerging").length,U=Vn(Q,o);return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"evidence-phrase-row cursor-pointer hover:bg-mono-800/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>d(w),onKeyDown:L=>{(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),d(w))},tabIndex:0,role:"button","aria-expanded":_,children:[e.jsx("td",{children:e.jsx(Gs,{size:14,className:`transition-transform duration-150 text-muted ${_?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-heading",children:C}),s&&e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-muted",children:P??"No location"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:F.map(L=>e.jsx(Qt,{provider:L.provider},L.id))})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mn,{state:S,label:Wn(S,o)}),e.jsxs("span",{className:"text-[11px] text-muted",title:`${v} of ${F.length} engines ${A}`,children:[v,"/",F.length]})]})}),e.jsx("td",{children:e.jsx(Qn,{history:Q})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:U}),e.jsx(Xn,{items:M})]}),e.jsx("td",{})]}),_&&F.map((L,N)=>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(Qt,{provider:L.provider})}),e.jsx("td",{children:e.jsx(mn,{state:L.citationState,label:Wn(L.citationState,o)})}),e.jsx("td",{children:e.jsx(Qn,{history:L.runHistory})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:Vn(L.runHistory,o)}),e.jsx(Xn,{items:[M[N]??L]})]}),e.jsx("td",{children:e.jsx(D,{variant:"ghost",size:"sm",type:"button",onClick:E=>{E.stopPropagation(),a(L.id)},children:"View"})})]}),x==="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(zo,{item:L,onViewFull:()=>a(L.id)})})]})]},L.id))]},w)})})]})}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",R==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function _o(t){const s=(t.matchedTerms??[]).filter(i=>i.trim().length>2),n=[...t.competitorDomains.flatMap(i=>{const r=ui(i);return r.length>=4?[r]:[]}),...t.recommendedCompetitors??[]].filter(i=>i.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 Uo(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 zo({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:i}=Uo(t.answerSnippet,Oo),r=_o(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:di(a,r)}),(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(o=>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:o},`c-${o}`)),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(o=>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:o},`co-${o}`)),t.competitorDomains.length>4&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.competitorDomains.length-4," more"]})]})]}),i&&e.jsx("button",{type:"button",className:"text-[11px] font-medium text-positive-400 hover:text-positive",onClick:o=>{o.stopPropagation(),s()},children:"View full answer →"})]})}function Ko({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 i=s!=null,r=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"}),r&&e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{children:t.map(o=>{const p=a!=null&&a.toLowerCase()===o.domain.toLowerCase(),x=[i?"cursor-pointer hover:bg-mono-800/30 transition-colors":"",p?"bg-negative-950/20":""].filter(Boolean).join(" ");return e.jsxs("tr",{className:x,onClick:i?()=>s(o.domain):void 0,title:i?`Filter answers to queries where ${o.domain} surfaced`:void 0,children:[e.jsx("td",{className:"font-medium text-heading",children:o.domain}),e.jsx("td",{children:e.jsx(oe,{tone:mi(o.pressureLabel),children:o.pressureLabel})}),e.jsx("td",{className:"text-neutral tabular-nums",children:o.totalQueries>0?`${o.citationCount} / ${o.totalQueries}`:"—"}),e.jsx("td",{className:"text-muted text-xs",children:o.citedQueries.length>0?o.citedQueries.join(", "):"Not cited"}),r&&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 ${o.domain}`,title:`Remove ${o.domain}`,onClick:m=>{m.stopPropagation(),n(o.domain)},children:"Remove"})})]},o.id)})})]})})}function Jn({eyebrow:t,title:s,status:n,tone:a,targetLabel:i,targetValue:r,coverageValue:o,note:p,updatedAt:x,active:m,onClick:f}){return e.jsxs("button",{type:"button",onClick:f,className:`surface-card w-full text-left transition-colors ${m?"border-mono-200 bg-bg-elevated/50":"hover:border-strong hover:bg-bg-elevated/40"}`,children:[e.jsxs("div",{className:"section-head",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:t}),e.jsx("h3",{children:s})]}),e.jsx(oe,{tone:a,children:n})]}),e.jsxs("div",{className:"mt-4 grid gap-3 sm: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:i}),e.jsx("p",{className:"mt-1 truncate text-sm text-strong",children:r})]}),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:"Coverage"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:o})]})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-1 text-xs text-muted sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("span",{children:p}),e.jsx("span",{children:x?`Updated ${Je(x)}`:"No recent sync yet"})]})]})}function As({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 Qo=6,Zt="__other__",zt="_socialTotal";function Ho(t,s=Qo){const n=new Map;for(const f of t)n.set(f.source,(n.get(f.source)??0)+f.sessions);const a=[...n.entries()].sort((f,d)=>d[1]!==f[1]?d[1]-f[1]:f[0].localeCompare(d[0])),i=a.slice(0,s),r=new Set(i.map(([f])=>f)),o=Math.max(0,a.length-s),p=new Map;for(const f of t){let d=p.get(f.date);d||(d={date:f.date,[zt]:0},p.set(f.date,d));const R=r.has(f.source)?f.source:Zt;d[R]=(d[R]??0)+f.sessions,d[zt]=(d[zt]??0)+f.sessions}const x=[...p.values()].sort((f,d)=>String(f.date).localeCompare(String(d.date))),m=i.map(([f])=>f);return o>0&&m.push(Zt),{data:x,sources:m,otherCount:o}}function Kt(t){return t.replace(/\+/g," ")}function Ea(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const Wo=["7d","30d","90d","all"],bt=Qe,hn=ze.textDim,Oa=ze.textFaint,ls=25,$s=50;function Ps(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function Ba(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 Vo({projectName:t}){const{data:s,isLoading:n,isError:a}=fo(t);if(n)return e.jsx(W,{className:"p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading server activity…"})});if(a)return e.jsx(W,{className:"p-5",children:e.jsx("div",{className:"text-sm text-negative-400",children:"Failed to load server activity."})});const i=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:"Crawler hits, AI fetches & AI referral sessions"}),e.jsxs("p",{className:"text-xs text-muted mt-1",children:["Server-side log evidence of bulk crawlers, on-demand AI user fetches (ChatGPT-User, Perplexity-User), and AI referral sessions — orthogonal to GA4 click-through traffic below."," ",!T()&&e.jsx(yt,{to:"/traffic",className:"text-link hover:underline",children:"Manage sources →"})]})]})}),i.length===0?e.jsx(W,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-secondary",children:["No server traffic source connected yet."," ",!T()&&e.jsxs(e.Fragment,{children:[e.jsx(yt,{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(W,{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:i.map(r=>e.jsxs("tr",{className:"border-t border-default",children:[e.jsx("td",{className:"px-4 py-3 text-heading",children:r.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(oe,{tone:bo(r.status),children:r.status})}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:r.totals24h.crawlerHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:r.totals24h.aiUserFetchHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:r.totals24h.aiReferralHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right text-secondary text-xs",children:r.lastSyncedAt?Ba(r.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:T()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(yt,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:r.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},r.id))})]})})]})}function Yo({projectName:t}){return e.jsxs("div",{className:"space-y-10",children:[e.jsx(Vo,{projectName:t}),e.jsx(Xo,{projectName:t})]})}function Xo({projectName:t}){const s=vt(),[n,a]=l.useState(null),[i,r]=l.useState(null),[o,p]=l.useState(!0),[x,m]=l.useState(!1),[f,d]=l.useState(!1),[R,h]=l.useState(null),[A,w]=l.useState(null),[C,P]=l.useState("sessions"),[F,M]=l.useState("desc"),[_,u]=l.useState("sessions"),[S,Q]=l.useState("desc"),[v,U]=l.useState("sessions"),[L,N]=l.useState("desc"),[E,O]=l.useState("sessions"),[se,he]=l.useState("desc"),[ye,pe]=l.useState(1),[ge,Y]=l.useState([]),[de,fe]=l.useState([]),[b,q]=l.useState([]),[X,le]=l.useState(!1),[ce,$e]=l.useState("30d");async function $(k){p(!0),h(null);try{const te=await s.fetchQuery({...xi({client:Z,path:{name:t}}),staleTime:os});if(k.current)return;if(a(te),!te.connected){r(null),Y([]),fe([]),q([]),p(!1);return}const V=ce==="all"?void 0:ce,[ie,at,ns,Ce]=await Promise.all([s.fetchQuery({...hi({client:Z,path:{name:t},query:V?{window:V}:void 0}),staleTime:os}).then(Ge=>Ge),s.fetchQuery({...pi({client:Z,path:{name:t},query:V?{window:V}:void 0}),staleTime:os}).catch(()=>[]),s.fetchQuery({...gi({client:Z,path:{name:t},query:V?{window:V}:void 0}),staleTime:os}).catch(()=>[]),s.fetchQuery({...fi({client:Z,path:{name:t},query:V?{window:V}:void 0}),staleTime:os}).catch(()=>[])]);if(k.current)return;r(ie),Y(at),fe(ns),q(Ce),p(!1)}catch(te){if(k.current)return;h(te instanceof Error?te.message:"Failed to load GA4 data"),p(!1)}}l.useEffect(()=>{const k={current:!1};return $(k),()=>{k.current=!0}},[t,ce,s]);async function H(){m(!0),h(null),w(null);try{const k=await fa(t);w(`Synced ${k.rowCount.toLocaleString()} page rows, ${k.aiReferralCount.toLocaleString()} AI and ${k.socialReferralCount.toLocaleString()} social referral rows (${k.days} days)`),await s.invalidateQueries({predicate:te=>{const V=te.queryKey[0];return typeof V?._id=="string"&&V._id.startsWith("getApiV1ProjectsByNameGa")}}),await $({current:!1})}catch(k){h(k instanceof Error?k.message:"Sync failed")}finally{m(!1)}}async function Te(){d(!0),h(null),w(null);try{await bi(t),await s.invalidateQueries({predicate:k=>{const te=k.queryKey[0];return typeof te?._id=="string"&&te._id.startsWith("getApiV1ProjectsByNameGa")}}),a({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),r(null),w("GA4 disconnected")}catch(k){h(k instanceof Error?k.message:"Disconnect failed")}finally{d(!1)}}function je(k){C===k?M(te=>te==="desc"?"asc":"desc"):(P(k),M("desc"))}function ve(k){_===k?Q(te=>te==="desc"?"asc":"desc"):(u(k),Q("desc"))}function ne(k){v===k?N(te=>te==="desc"?"asc":"desc"):(U(k),N("desc"))}function G(k){pe(1),E===k?he(te=>te==="desc"?"asc":"desc"):(O(k),he("desc"))}const z=l.useMemo(()=>i?.topPages?[...i.topPages].sort((k,te)=>{const V=k[C],ie=te[C];return typeof V=="string"&&typeof ie=="string"?F==="asc"?V.localeCompare(ie):ie.localeCompare(V):F==="asc"?V-ie:ie-V}):[],[i?.topPages,C,F]),ue=l.useMemo(()=>i?.aiReferrals?[...i.aiReferrals].sort((k,te)=>{const V=k[_],ie=te[_];return typeof V=="string"&&typeof ie=="string"?S==="asc"?V.localeCompare(ie):ie.localeCompare(V):S==="asc"?V-ie:ie-V}):[],[i?.aiReferrals,_,S]),xe=l.useMemo(()=>i?.aiReferralLandingPages?[...i.aiReferralLandingPages].sort((k,te)=>{const V=k[E],ie=te[E];return typeof V=="string"&&typeof ie=="string"?se==="asc"?V.localeCompare(ie):ie.localeCompare(V):se==="asc"?V-ie:ie-V}):[],[i?.aiReferralLandingPages,E,se]),y=Math.max(1,Math.ceil(xe.length/$s)),I=Math.min(Math.max(1,ye),y),Le=(I-1)*$s,Be=l.useMemo(()=>xe.slice(Le,Le+$s),[xe,Le]),we=l.useMemo(()=>i?.socialReferrals?[...i.socialReferrals].sort((k,te)=>{const V=k[v],ie=te[v];return typeof V=="string"&&typeof ie=="string"?L==="asc"?V.localeCompare(ie):ie.localeCompare(V):L==="asc"?V-ie:ie-V}):[],[i?.socialReferrals,v,L]),{socialChartData:Nt,socialChartSources:xt,socialOtherCount:We}=l.useMemo(()=>{const k=Ho(b);return{socialChartData:k.data,socialChartSources:k.sources,socialOtherCount:k.otherCount}},[b]),{chartData:wt,chartSources:_e,dateRange:st}=l.useMemo(()=>{const k=[...new Set(ge.map(Ce=>Ce.source))],te=new Map;for(const Ce of de)te.set(Ce.date,{_totalSessions:Ce.sessions,_organicSessions:Ce.organicSessions});const V=new Map;for(const Ce of ge){const Ge=`${Ce.date}::${Ce.source}`,rt=V.get(Ge)??0;V.set(Ge,Math.max(rt,Ce.sessions))}for(const[Ce,Ge]of V){const[rt,as]=Ce.split("::");let me=te.get(rt);me||(me={_totalSessions:0,_organicSessions:0},te.set(rt,me)),me[as]=(me[as]??0)+Ge}const ie=[...te.entries()].sort(([Ce],[Ge])=>Ce.localeCompare(Ge)).map(([Ce,Ge])=>({date:Ce,...Ge})),at=ie.map(Ce=>Ce.date),ns=at.length>0?{start:at[0],end:at[at.length-1]}:null;return{chartData:ie,chartSources:k,dateRange:ns}},[ge,de]);if(o&&!n)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!n?.connected)return T()?e.jsx(W,{className:"p-5",children:e.jsx("div",{className:"text-sm text-secondary",children:"No Google Analytics 4 property connected yet."})}):e.jsx(Jo,{projectName:t,onConnected:()=>{(async()=>(await s.invalidateQueries({predicate:k=>{const te=k.queryKey[0];return typeof te?._id=="string"&&te._id.startsWith("getApiV1ProjectsByNameGa")}}),await $({current:!1})))()}});const nt=i?.organicSharePctDisplay??"0%",Lt=i?.channelBreakdown?.organic.sharePctDisplay??nt,St=i?.channelBreakdown?.organic.sessions??i?.totalOrganicSessions??0,es=i?.aiSessionsDeduped??0,Pe=i?.channelBreakdown?.ai.sessions??i?.aiSessionsBySession??0,ts=i?.channelBreakdown?.ai.sharePctDisplay??i?.aiSharePctBySessionDisplay??"0%",Fe=i?.paidAiSessionsBySession??0,He=i?.paidAiSharePctBySessionDisplay??"0%",kt=i?new Set(i.aiReferrals.map(k=>k.source.toLowerCase())).size:0,ht=ue[0]??null,ss=i?.totalDirectSessions??0,bs=i?.directSharePctDisplay??"0%",it=i?.channelBreakdown?.direct.sessions??ss,Me=i?.channelBreakdown?.direct.sharePctDisplay??bs,g=i?.channelBreakdown?.other.sessions??i?.otherSessions??0,J=i?.channelBreakdown?.other.sharePctDisplay??i?.otherSharePctDisplay??"0%",ee=i?.socialSessions??0,Ee=i?.socialSharePctDisplay??"0%",ke=i?.channelBreakdown?.social.sessions??ee,It=i?.channelBreakdown?.social.sharePctDisplay??Ee,Rt=i?new Set(i.socialReferrals.map(k=>k.source.toLowerCase())).size:0,Se=we[0]??null;return e.jsxs(e.Fragment,{children:[R&&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:R}),A&&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:A}),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})]})]})]}),!T()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(D,{variant:"outline",size:"sm",disabled:x,onClick:ae(H),children:[e.jsx(dt,{className:`w-3.5 h-3.5 mr-1.5 ${x?"animate-spin":""}`}),x?"Syncing…":"Sync"]}),e.jsxs(D,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:f,onClick:ae(Te),children:[e.jsx(Ao,{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(De,{text:`Aggregated traffic metrics from Google Analytics 4. Sessions and users are summed across the selected period.${i?.periodStart&&i?.periodEnd?` Data available: ${new Date(i.periodStart+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})} – ${new Date(i.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:"flex gap-1",children:Wo.map(k=>e.jsx("button",{type:"button",className:`px-3 py-1 text-xs rounded-full border transition-colors ${ce===k?"bg-mono-700 border-mono-600 text-primary":"border-base text-secondary hover:border-strong hover:text-neutral"}`,onClick:()=>$e(k),children:k==="all"?"All":k},k))})]}),i?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(Ys,{value:Ps(i.totalSessions),label:"Total Sessions",subtitle:i.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(Ys,{value:Ps(i.totalOrganicSessions),label:"Organic Sessions",subtitle:`${nt} of total`,tone:"positive"}),e.jsx(Ys,{value:Ps(i.totalUsers),label:"Total Users",subtitle:i.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."}),!T()&&e.jsxs(D,{variant:"outline",size:"sm",disabled:x,onClick:ae(H),children:[e.jsx(dt,{className:`w-3.5 h-3.5 mr-1.5 ${x?"animate-spin":""}`}),"Sync from GA4"]})]})]}),i&&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(De,{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."})]})]}),st&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(st.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(st.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),wt.length>0&&e.jsxs(W,{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:_e.length>0?"AI vs. total sessions":"All sessions (baseline)"}),_e.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),_e.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(Wt,{width:"100%",height:"100%",children:e.jsxs(Vt,{data:wt,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Yt,{dataKey:"date",tick:et,tickLine:!1,axisLine:{stroke:ut},tickFormatter:Ht}),e.jsx(Xt,{tick:et,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Jt,{...Dt,labelFormatter:mt,formatter:(k,te)=>{const V=typeof k=="number"?k.toLocaleString():String(k??0),ie=String(te??"");return ie==="_totalSessions"?[V,"Total Sessions"]:ie==="_organicSessions"?[V,"Organic Sessions"]:[V,ie]}}),e.jsx($a,{wrapperStyle:{fontSize:11,color:ze.text},formatter:k=>k==="_totalSessions"?"Total Sessions":k==="_organicSessions"?"Organic Sessions":k}),e.jsx(Ft,{type:"monotone",dataKey:"_totalSessions",stroke:ze.textFaint,fill:ze.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),_e.map((k,te)=>e.jsx(Ft,{type:"monotone",dataKey:k,stackId:"ai",stroke:bt[te%bt.length],fill:bt[te%bt.length],fillOpacity:.4,strokeWidth:1.5},k))]})})})]}),e.jsxs(W,{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(tt,{label:"Organic",value:Lt,hint:`${St.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(tt,{label:"Social",value:It,hint:`${ke.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(tt,{label:"Direct",value:Me,hint:`${it.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(tt,{label:"Known AI referrers (lower bound)",value:ts,hint:Fe>0?`${Pe.toLocaleString()} sessions · ${Fe.toLocaleString()} paid`:`${Pe.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(tt,{label:"Other channels",value:J,hint:`${g.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."})]}),ht&&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:ht.source})," via ",ht.medium,", accounting for ",ht.sessions.toLocaleString()," sessions.",Fe>0&&e.jsxs("span",{children:[" Paid AI: ",Fe.toLocaleString()," sessions (",He,")."]})]})]}),e.jsxs(W,{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:i.aiReferrals.length>0?`${kt} unique sources, ${i.aiReferrals.length} rows`:"No source rows"})]}),i.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(qe,{label:"Source",sortKey:"source",current:_,dir:S,onSort:ve,align:"left"}),e.jsx(qe,{label:"Medium",sortKey:"medium",current:_,dir:S,onSort:ve,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(qe,{label:"Sessions",sortKey:"sessions",current:_,dir:S,onSort:ve,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(qe,{label:"Users",sortKey:"users",current:_,dir:S,onSort:ve,align:"right"})]})}),e.jsx("tbody",{children:ue.map(k=>e.jsx(el,{referral:k,totalSessions:es},`${k.source}:${k.medium}:${k.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(W,{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:xe.length>$s?`${Le+1}–${Le+Be.length} of ${xe.length} rows`:xe.length>0?`${xe.length} rows`:"No landing-page rows"})]}),xe.length>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(qe,{label:"Landing Page",sortKey:"landingPage",current:E,dir:se,onSort:G,align:"left"}),e.jsx(qe,{label:"Source",sortKey:"source",current:E,dir:se,onSort:G,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(qe,{label:"Sessions",sortKey:"sessions",current:E,dir:se,onSort:G,align:"right"}),e.jsx(qe,{label:"Users",sortKey:"users",current:E,dir:se,onSort:G,align:"right"})]})}),e.jsx("tbody",{children:Be.map(k=>e.jsx(tl,{row:k},`${k.landingPage}:${k.source}:${k.medium}:${k.sourceDimension}`))})]})}),y>1&&e.jsxs("div",{className:"mt-3 flex items-center justify-center gap-2",children:[e.jsx("button",{type:"button",onClick:()=>pe(I-1),disabled:I<=1,className:"text-xs text-secondary hover:text-strong disabled:opacity-40 disabled:hover:text-secondary px-3 py-1 rounded-full border border-base hover:border-strong disabled:hover:border-base transition-colors",children:"Previous"}),e.jsxs("span",{className:"text-xs text-muted tabular-nums",children:["Page ",I," of ",y]}),e.jsx("button",{type:"button",onClick:()=>pe(I+1),disabled:I>=y,className:"text-xs text-secondary hover:text-strong disabled:opacity-40 disabled:hover:text-secondary px-3 py-1 rounded-full border border-base hover:border-strong disabled:hover:border-base transition-colors",children:"Next"})]})]}):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."})]})]})]})]}),i&&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(De,{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."})]})]}),Nt.length>0&&e.jsxs(W,{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"})]}),We>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",xt.length-1," sources · ",We," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(Wt,{width:"100%",height:"100%",children:e.jsxs(Vt,{data:Nt,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Yt,{dataKey:"date",tick:et,tickLine:!1,axisLine:{stroke:ut},tickFormatter:Ht}),e.jsx(Xt,{tick:et,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Jt,{...Dt,labelFormatter:mt,formatter:(k,te)=>{const V=typeof k=="number"?k.toLocaleString():String(k??0),ie=String(te??"");if(ie===zt)return[V,"Total Social"];if(ie===Zt){const at=`Other (${We} source${We===1?"":"s"})`;return[V,at]}return[V,Kt(ie)]}}),e.jsx(Ft,{type:"monotone",dataKey:zt,stroke:Oa,fill:ze.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),xt.map((k,te)=>{const ie=k===Zt?hn:bt[te%bt.length];return e.jsx(Ft,{type:"monotone",dataKey:k,stackId:"social",stroke:ie,fill:ie,fillOpacity:.4,strokeWidth:1.5},k)})]})})}),e.jsx(nl,{sources:xt,otherCount:We})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.5fr)]",children:[e.jsxs(W,{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"})]}),i.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(tt,{label:"Social Sessions",value:Ps(ee),hint:`${ee.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(tt,{label:"Share of Traffic",value:Ee,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(tt,{label:"Platforms",value:String(Rt),hint:`${i.socialReferrals.length} source rows`,tone:"neutral",tooltip:"Number of distinct social media platforms detected. Each unique source/medium combination counts as one source row."})]}),Se&&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:`${Se.source} via ${Se.medium}`,children:Ea(Kt(Se.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:Se.medium,children:["via ",Kt(Se.medium)," · ",Se.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(tt,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(tt,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(tt,{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(W,{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:i.socialReferrals.length>0?we.length>ls&&!X?`Top ${ls} of ${we.length}`:`${we.length} rows`:"No source rows"})]}),i.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(qe,{label:"Source",sortKey:"source",current:v,dir:L,onSort:ne,align:"left"}),e.jsx(qe,{label:"Medium",sortKey:"medium",current:v,dir:L,onSort:ne,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(qe,{label:"Sessions",sortKey:"sessions",current:v,dir:L,onSort:ne,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(qe,{label:"Users",sortKey:"users",current:v,dir:L,onSort:ne,align:"right"})]})}),e.jsx("tbody",{children:(X?we:we.slice(0,ls)).map(k=>e.jsx(sl,{referral:k,totalSessions:ee},`${k.source}:${k.medium}:${k.channelGroup}`))})]})}),we.length>ls&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>le(k=>!k),className:"text-xs text-secondary hover:text-strong px-3 py-1 rounded-full border border-base hover:border-strong transition-colors",children:X?`Show top ${ls}`:`Show all ${we.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."})]})]})]})]})]}),i&&i.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(De,{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(qe,{label:"Landing Page",sortKey:"landingPage",current:C,dir:F,onSort:je,align:"left"}),e.jsx(qe,{label:"Sessions",sortKey:"sessions",current:C,dir:F,onSort:je,align:"right"}),e.jsx(qe,{label:"Organic",sortKey:"organicSessions",current:C,dir:F,onSort:je,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"}),e.jsx(qe,{label:"Users",sortKey:"users",current:C,dir:F,onSort:je,align:"right"})]})}),e.jsx("tbody",{children:z.map(k=>e.jsx(Zo,{page:k},k.landingPage))})]})})]})]}),e.jsxs("div",{className:"mt-6 flex items-center justify-between text-xs text-muted",children:[e.jsx("span",{children:i?.lastSyncedAt?`Last synced ${Ba(i.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:i?`${i.topPages.length} pages · ${i.aiReferrals.length} AI rows · ${i.socialReferrals.length} social rows`:""})]})]})}function Jo({projectName:t,onConnected:s}){const[n,a]=l.useState(""),[i,r]=l.useState(null),[o,p]=l.useState(null),[x,m]=l.useState(!1),[f,d]=l.useState(null),R=l.useRef(null),h=l.useCallback(w=>{const C=w.target.files?.[0];if(!C)return;d(null),r(C.name);const P=new FileReader;P.onload=()=>{const F=P.result;try{const M=JSON.parse(F);if(!M.client_email||!M.private_key){d("JSON file is missing required fields: client_email and private_key. Make sure you downloaded a service account key (not an OAuth client)."),p(null);return}p(F)}catch{d("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),p(null)}},P.onerror=()=>{d("Failed to read file."),p(null)},P.readAsText(C)},[]);async function A(){if(d(null),!n.trim()){d("Property ID is required.");return}if(!o){d("Please upload a service account key file.");return}m(!0);try{await ji(t,{propertyId:n.trim(),keyJson:o});try{await fa(t)}catch{}s()}catch(w){d(w instanceof Error?w.message:"Failed to connect GA4")}finally{m(!1)}}return e.jsxs(W,{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."}),f&&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:f}),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:w=>a(w.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:R,type:"file",accept:".json,application/json",onChange:h,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>R.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(Po,{className:"w-4 h-4 shrink-0"}),i?e.jsx("span",{className:"text-strong truncate",children:i}):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(D,{variant:"default",size:"sm",disabled:x||!n.trim()||!o,onClick:ae(A),children:x?"Connecting & syncing…":"Connect GA4"})]})}function qe({label:t,sortKey:s,current:n,dir:a,onSort:i,align:r}){const o=n===s;return e.jsx("th",{className:`py-1 ${r==="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:()=>i(s),"aria-label":`Sort by ${t}${o?` (currently ${a==="asc"?"ascending":"descending"})`:""}`,children:[t,o&&e.jsx("span",{className:"ml-0.5",children:a==="asc"?"↑":"↓"})]})})}const Fa={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function Ys({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 ${Fa[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function tt({value:t,label:s,hint:n,tone:a,tooltip:i}){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,i&&e.jsx(De,{text:i})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${Fa[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Zo({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,"%"]}),e.jsx("td",{className:"py-1.5 text-right text-strong tabular-nums",children:t.users.toLocaleString()})]})}const Ga={session:"Session",first_user:"First Visit",manual_utm:"UTM"},qa={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 el({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=Ga[t.sourceDimension]??t.sourceDimension,i=qa[t.sourceDimension]??"",r=t.trafficClass==="paid"?"Paid":"Organic",o=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:o,children:r})}),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:i,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,"%"]}),e.jsx("td",{className:"py-1.5 text-right text-strong tabular-nums",children:t.users.toLocaleString()})]})}function tl({row:t}){const s=Ga[t.sourceDimension]??t.sourceDimension,n=qa[t.sourceDimension]??"";return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 text-neutral max-w-[360px] truncate",title:t.landingPage,children:t.landingPage}),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()}),e.jsx("td",{className:"py-1.5 text-right text-strong tabular-nums",children:t.users.toLocaleString()})]})}function sl({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=t.channelGroup==="Paid Social"?"Paid":"Organic",i=Kt(t.source),r=Kt(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:i}),e.jsx("td",{className:"py-1.5 pr-3 text-muted truncate",title:t.medium,children:r}),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 nl({sources:t,otherCount:s}){const n=[{key:zt,color:Oa,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const i=t[a];if(i===Zt)n.push({key:Zt,color:hn,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const r=Kt(i);n.push({key:i,color:bt[a%bt.length]??hn,label:Ea(r,32),tooltip:r})}}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 al(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 il=["7d","30d","90d","all"],Ds=500,gt=25;function rl({projectName:t,refreshNonce:s}){const n=vt(),[a,i]=l.useState(!1),[r,o]=l.useState([]),[p,x]=l.useState([]),[m,f]=l.useState([]),[d,R]=l.useState(null),[h,A]=l.useState([]),[w,C]=l.useState([]),[P,F]=l.useState(null),[M,_]=l.useState(""),[u,S]=l.useState(""),[Q,v]=l.useState("30"),[U,L]=l.useState(!1),[N,E]=l.useState("30d"),[O,se]=l.useState({startDate:"",endDate:"",query:"",page:"",limit:"20"}),[he,ye]=l.useState(0),[pe,ge]=l.useState(!1),[Y,de]=l.useState(0),[fe,b]=l.useState(!1),[q,X]=l.useState(""),[le,ce]=l.useState(!0),[$e,$]=l.useState(!1),[H,Te]=l.useState(!1),[je,ve]=l.useState(!1),[ne,G]=l.useState(!1),[z,ue]=l.useState(!1),[xe,y]=l.useState(!1),[I,Le]=l.useState(null),[Be,we]=l.useState(!1),[Nt,xt]=l.useState(!1),[We,wt]=l.useState(null),[_e,st]=l.useState(""),[nt,Lt]=l.useState(!1),[St,es]=l.useState(!1),[Pe,ts]=l.useState("indexed"),[Fe,He]=l.useState(null),kt=!!(O.query.trim()||O.page.trim()||Fe),ht=Fe!==null,ss=l.useMemo(()=>{if(!Fe)return m;const{key:c,dir:j}=Fe;return[...m].sort((B,re)=>{const Ne=c===Pt.CTR?Number.isFinite(B.ctr)?B.ctr:0:B[c],Ke=c===Pt.CTR?Number.isFinite(re.ctr)?re.ctr:0:re[c];return j==="asc"?Ne-Ke:Ke-Ne})},[m,Fe]),[bs,it]=l.useState([]),[Me,g]=l.useState(null),[J,ee]=l.useState(1);l.useEffect(()=>{ee(1)},[I,Pe,Me]);const Ee=l.useMemo(()=>Me?(I?.reasonGroups??[]).find(c=>c.reason===Me):void 0,[I,Me]),ke=l.useMemo(()=>I?Pe==="indexed"?I.indexed:Pe==="deindexed"?I.deindexed:Pe==="notIndexed"?Me?Ee?.urls??[]:(I.reasonGroups??[]).length===0?I.notIndexed:[]:[]:[],[I,Pe,Me,Ee]),It=Math.max(1,Math.ceil(ke.length/gt)),Rt=Math.min(Math.max(1,J),It),Se=(Rt-1)*gt,k=ke.length>gt,te=ke.length===0?0:Se+1,V=Math.min(Se+gt,ke.length),ie=l.useMemo(()=>I?.indexed.slice(Se,Se+gt)??[],[I,Se]),at=l.useMemo(()=>I?.notIndexed.slice(Se,Se+gt)??[],[I,Se]),ns=l.useMemo(()=>I?.deindexed.slice(Se,Se+gt)??[],[I,Se]),Ce=l.useMemo(()=>(Ee?.urls??[]).slice(Se,Se+gt),[Ee,Se]),[Ge,rt]=l.useState(!1),[as,me]=l.useState(null),[ot,js]=l.useState(null),[An,lt]=l.useState(null);function Qa(c,j){const B=zn(c),re=al(B);re?(js(re),me(null)):(js(null),me(B.message||j))}const Ae=r.find(c=>c.connectionType==="gsc"),Ha=m.length>0||h.length>0||w.length>0,Us=yi(),is=vi(),zs=Ni();async function $n(c,j={}){if(!c){x([]),_("");return}Te(!0);try{const{sites:B}=await n.fetchQuery({...Ti({client:Z,path:{name:t}}),staleTime:j.force?0:Oe});x(B),_(c.propertyId??B[0]?.siteUrl??""),js(null),j.notify&&K({title:"GSC properties refreshed",detail:`${B.length} propert${B.length===1?"y":"ies"} available for this connection.`,tone:B.length>0?"positive":"caution",dedupeKey:`gsc:properties:${t}`,dedupeMode:"replace"})}catch(B){if(x([]),Qa(B,"Failed to load Search Console properties"),j.notify){const re=zn(B);K({title:"GSC property refresh failed",detail:re.message||"Failed to load Search Console properties",tone:"negative",dedupeKey:`gsc:properties:${t}`,dedupeMode:"replace"})}}finally{Te(!1)}}async function Tt(c){G(!0);const j=c??he;try{const B=parseInt(O.limit,10)||20,re=kt?Ds:B+1,Ne=kt?0:j,Ke={limit:String(re)};O.startDate&&(Ke.startDate=O.startDate),O.endDate&&(Ke.endDate=O.endDate),O.query&&(Ke.query=O.query),O.page&&(Ke.page=O.page),Ne>0&&(Ke.offset=String(Ne)),N&&N!=="all"&&!O.startDate&&(Ke.window=N);const Ve=await n.fetchQuery({...ki({client:Z,path:{name:t},query:Ke}),staleTime:Oe});kt?(ge(!1),f(Ve),de(Ve.length),b(!0)):(ge(Ve.length>B),f(Ve.slice(0,B)),de(0),b(!1))}catch(B){f([]),ge(!1),de(0),me(B instanceof Error?B.message:"Failed to load GSC performance data")}finally{G(!1)}}async function Ks(){try{const c={};O.startDate&&(c.startDate=O.startDate),O.endDate&&(c.endDate=O.endDate),N&&N!=="all"&&!O.startDate&&(c.window=N);const j=await n.fetchQuery({...Ci({client:Z,path:{name:t},query:c}),staleTime:Oe});R(j)}catch{R(null)}}async function ys(c={}){ue(!0);try{const j=q.trim()||void 0,B={limit:"20"};j&&(B.url=j);const[re,Ne]=await Promise.all([n.fetchQuery({...Ii({client:Z,path:{name:t},query:B}),staleTime:c.force?0:Oe}),n.fetchQuery({...Ri({client:Z,path:{name:t}}),staleTime:c.force?0:Oe})]);A(re),C(Ne),c.notify&&K({title:"Inspection history refreshed",detail:`${re.length} recent inspection${re.length===1?"":"s"} loaded${Ne.length>0?`, ${Ne.length} deindexed URL${Ne.length===1?"":"s"} flagged`:""}.`,tone:"positive",dedupeKey:`gsc:inspection-history:${t}`,dedupeMode:"replace"})}catch(j){const B=j instanceof Error?j.message:"Failed to load GSC inspection history";A([]),C([]),me(B),c.notify&&K({title:"Inspection history refresh failed",detail:B,tone:"negative",dedupeKey:`gsc:inspection-history:${t}`,dedupeMode:"replace"})}finally{ue(!1)}}async function Pn(c={}){we(!0);try{const[j,B]=await Promise.all([n.fetchQuery({...ba({client:Z,path:{name:t}}),staleTime:c.force?0:Oe}),n.fetchQuery({...Di({client:Z,path:{name:t}}),staleTime:c.force?0:Oe}).catch(()=>[])]);Le(j),it(B),c.notify&&K({title:"GSC coverage refreshed",detail:j.summary.total>0?`${j.summary.indexed}/${j.summary.total} URLs indexed. Use Inspect sitemap to re-read new sitemap URLs.`:"No coverage rows yet. Inspect the sitemap to populate this view.",tone:j.summary.total>0?"positive":"caution",dedupeKey:`gsc:coverage:${t}`,dedupeMode:"replace"})}catch(j){const B=j instanceof Error?j.message:"Failed to load coverage data";Le(null),it([]),me(B),c.notify&&K({title:"GSC coverage refresh failed",detail:B,tone:"negative",dedupeKey:`gsc:coverage:${t}`,dedupeMode:"replace"})}finally{we(!1)}}async function Dn(c){rt(!0),me(null);try{const j=await On(t,{urls:c}),{succeeded:B,failed:re,total:Ne}=j.summary;K({title:"Indexing requested",detail:re===0?`${B} URL${B!==1?"s":""} submitted for indexing.`:`${B}/${Ne} submitted successfully, ${re} failed.`,tone:re===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(j){const B=j instanceof Error?j.message:"Failed to request indexing";me(B),K({title:"Indexing request failed",detail:B,tone:"negative",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}finally{rt(!1)}}async function Wa(){rt(!0),me(null);try{const c=await On(t,{urls:[],allUnindexed:!0}),{succeeded:j,failed:B,total:re}=c.summary;K({title:"Indexing requested",detail:B===0?`${j} unindexed URL${j!==1?"s":""} submitted for indexing.`:`${j}/${re} submitted successfully, ${B} failed.`,tone:B===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(c){const j=c instanceof Error?c.message:"Failed to request indexing";me(j),K({title:"Indexing request failed",detail:j,tone:"negative",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}finally{rt(!1)}}async function vs(){if(_e.trim()){Lt(!0),me(null);try{await Pi(t,"gsc",_e.trim()),await n.invalidateQueries({predicate:c=>{const j=c.queryKey[0];return typeof j?._id=="string"&&j._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),o(c=>c.map(j=>j.connectionType==="gsc"?{...j,sitemapUrl:_e.trim()}:j)),K({title:"Sitemap URL saved",detail:`${t} will use the updated sitemap URL.`,tone:"positive",dedupeKey:`gsc:sitemap:${t}`,dedupeMode:"drop"}),st("")}catch(c){me(c instanceof Error?c.message:"Failed to save sitemap URL")}finally{Lt(!1)}}}async function Ln(){me(null);try{const c=await is.mutateAsync({projectName:t,projectLabel:t});wt(c.sitemaps),o(j=>j.map(B=>B.connectionType==="gsc"?{...B,sitemapUrl:c.primarySitemapUrl}:B))}catch{}}async function Va(){xt(!0),me(null);try{const c=await Ei(t);n.setQueryData(Oi({client:Z,path:{name:t}}),c),wt(c.sitemaps),c.sitemaps.length===0?(lt("No sitemaps found in this GSC property. Submit a sitemap in Google Search Console first."),K({title:"No GSC sitemaps found",detail:"Submit a sitemap in Google Search Console, then browse again.",tone:"caution",dedupeKey:`gsc:sitemaps:${t}`,dedupeMode:"replace"})):K({title:"GSC sitemaps loaded",detail:`${c.sitemaps.length} sitemap${c.sitemaps.length===1?"":"s"} returned from Search Console.`,tone:"positive",dedupeKey:`gsc:sitemaps:${t}`,dedupeMode:"replace"})}catch(c){const j=c instanceof Error?c.message:"Failed to list sitemaps";me(j),K({title:"Could not load GSC sitemaps",detail:j,tone:"negative",dedupeKey:`gsc:sitemaps:${t}`,dedupeMode:"replace"})}finally{xt(!1)}}async function In(){ce(!0),me(null);try{const[c,j]=await Promise.all([Si().catch(()=>null),n.fetchQuery({...bn({client:Z,path:{name:t}}),staleTime:Oe}).catch(()=>[])]);i(!!c?.google?.configured),o(j);const B=j.find(re=>re.connectionType==="gsc");await Promise.all([$n(B),Tt(),Ks(),ys(),Pn()])}finally{ce(!1)}}l.useEffect(()=>{In()},[t,s]),l.useEffect(()=>{ye(0),Tt(0),Ks()},[N]);const Rn=l.useRef(!1);l.useEffect(()=>{if(!Rn.current){Rn.current=!0;return}ye(0),Tt(0)},[ht]);async function Ya(){if(!a){me("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}$(!0),me(null),lt(null);try{const{authUrl:c}=await $i(t,"gsc");if(!c.startsWith("https://accounts.google.com/")){me("Unexpected OAuth redirect URL. Please try again.");return}const j=window.open(c,"_blank","width=600,height=700");if(!j){window.location.assign(c);return}lt("Finish the Google consent flow in the popup, then close it to refresh this project.");const B=window.setInterval(()=>{j.closed&&(window.clearInterval(B),lt(null),n.invalidateQueries({predicate:re=>{const Ne=re.queryKey[0];return typeof Ne?._id=="string"&&Ne._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),In())},1e3)}catch(c){me(c instanceof Error?c.message:"Failed to start OAuth flow")}finally{$(!1)}}async function Xa(){me(null),lt(null);try{await Ai(t,"gsc"),await n.invalidateQueries({predicate:c=>{const j=c.queryKey[0];return typeof j?._id=="string"&&j._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),o(c=>c.filter(j=>j.connectionType!=="gsc")),x([]),_("")}catch(c){me(c instanceof Error?c.message:"Failed to disconnect")}}async function Ja(){if(M){ve(!0),me(null);try{await Mi(t,"gsc",M),await n.invalidateQueries({predicate:c=>{const j=c.queryKey[0];return typeof j?._id=="string"&&j._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),o(c=>c.map(j=>j.connectionType==="gsc"?{...j,propertyId:M}:j)),K({title:"GSC property updated",detail:`${t} is now linked to ${M}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(c){me(c instanceof Error?c.message:"Failed to save GSC property")}finally{ve(!1)}}}async function Za(){me(null),lt(null);try{await Us.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(Q,10)||void 0,full:U||void 0}}),await n.invalidateQueries({predicate:c=>{const j=c.queryKey[0];return typeof j?._id=="string"&&j._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}})}catch{}}async function Tn(){if(u.trim()){y(!0),me(null),lt(null);try{const c=await Li(t,u.trim());await n.invalidateQueries({predicate:j=>{const B=j.queryKey[0];return typeof B?._id=="string"&&B._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),F(c),S(""),await ys()}catch(c){me(c instanceof Error?c.message:"Failed to inspect URL")}finally{y(!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"})]})}),ot&&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:ot.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:ot.message}),(Ot(ot.enableUrl)||Ot(ot.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[Ot(ot.enableUrl)&&e.jsx("a",{href:Ot(ot.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 ↗"}),Ot(ot.indexingApiUrl)&&e.jsx("a",{href:Ot(ot.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:()=>js(null),children:"×"})]})}),as&&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:[as,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>me(null),children:"×"})]}),An&&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:[An,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>lt(null),children:"×"})]}),le?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[Ae?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:Ae.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Last updated ",Je(Ae.updatedAt)]}),!T()&&e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:ae(Xa),children:"Disconnect"})]}):e.jsxs(W,{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(oe,{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."}),!T()&&e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[a?e.jsx(D,{type:"button",variant:"outline",size:"sm",disabled:$e,onClick:ae(Ya),children:$e?"Opening…":"Connect Google Search Console"}):e.jsx(D,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(yt,{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."})]})]})]}),Ae&&!Ae.sitemapUrl&&e.jsx("div",{className:"rounded-lg border border-caution-800/40 bg-caution-950/20 px-4 py-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"mt-0.5 text-caution-400",children:e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",className:"h-5 w-5","aria-hidden":"true",children:e.jsx("path",{fillRule:"evenodd",d:"M8.485 2.495c.673-1.167 2.357-1.167 3.03 0l6.28 10.875c.673 1.167-.17 2.625-1.516 2.625H3.72c-1.347 0-2.189-1.458-1.515-2.625L8.485 2.495zM10 6a.75.75 0 01.75.75v3.5a.75.75 0 01-1.5 0v-3.5A.75.75 0 0110 6zm0 9a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-caution-300",children:"Set your sitemap URL"}),e.jsx("p",{className:"mt-1 text-xs text-caution-400/70",children:"Canonry uses your sitemap to discover URLs for index coverage inspection. Auto-discover from GSC or enter it manually."}),!T()&&e.jsxs("div",{className:"mt-2 flex flex-col gap-2",children:[e.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row",children:[e.jsx(D,{type:"button",size:"sm",disabled:is.isPending||!Ae.propertyId,onClick:ae(Ln),children:is.isPending?"Discovering…":"Auto-discover from GSC"}),e.jsx("span",{className:"self-center text-xs text-caution-400/60",children:"or enter manually:"})]}),e.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-caution-800/40 bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-500 focus:border-caution-600 focus:outline-none",type:"url",placeholder:"https://example.com/sitemap.xml",value:_e,onChange:c=>st(c.target.value),onKeyDown:c=>c.key==="Enter"&&void vs()}),e.jsx(D,{type:"button",size:"sm",variant:"outline",disabled:nt||!_e.trim(),onClick:ae(vs),children:nt?"Saving…":"Save sitemap URL"})]})]})]})]})}),(Ae||Ha)&&e.jsxs(e.Fragment,{children:[e.jsxs(W,{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:[!T()&&I&&I.notIndexed.length>0&&e.jsx(D,{type:"button",variant:"outline",size:"sm",disabled:Ge,onClick:()=>{Wa()},children:Ge?"Requesting…":`Request indexing (${I.notIndexed.length})`}),e.jsxs(D,{type:"button",variant:"outline",size:"sm",disabled:Be,onClick:()=>{Pn({force:!0,notify:!0})},children:[e.jsx(dt,{className:`h-3.5 w-3.5 ${Be?"animate-spin":""}`,"aria-hidden":"true"}),Be?"Loading…":"Refresh coverage"]})]})]}),I&&I.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const c=I.summary.indexed+I.summary.notIndexed,j=c>0?I.summary.indexed/c:0,B=c>0?I.summary.notIndexed/c:0,re=54,Ne=2*Math.PI*re,Ke=Ne*(1-j),Ve=Ne*B,Mt=Ne*j;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:re,fill:"none",stroke:ze.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:re,fill:"none",stroke:Es.positiveDeep,strokeWidth:"14",strokeDasharray:Ne,strokeDashoffset:Ke,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),I.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:re,fill:"none",stroke:ze.textFaint,strokeWidth:"14",strokeDasharray:`${Ve} ${Ne-Ve}`,strokeDashoffset:-Mt,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:[(j*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:I.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:I.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:["Not indexed",(I.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-faint",children:["· ",(I.reasonGroups??[]).length," ",(I.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),I.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:I.summary.deindexed.toLocaleString()}),e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:"Deindexed"})]})]})]})]})]})})()}),e.jsx("div",{className:"mt-3 flex gap-1",children:["indexed","notIndexed","deindexed"].map(c=>{const j=c==="indexed"?I.indexed.length:c==="notIndexed"?I.notIndexed.length:I.deindexed.length,B=c==="indexed"?"Indexed":c==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",className:`rounded-full px-3 py-1 text-xs font-medium transition-colors ${Pe===c?"bg-mono-700 text-heading":"text-secondary hover:bg-mono-800 hover:text-strong"}`,onClick:()=>{ts(c),g(null)},children:[B," (",j,")"]},c)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[Pe==="indexed"&&I.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:ie.map(c=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:c.url}),e.jsx("td",{className:"text-secondary",children:c.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:c.crawlTime?c.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:c.isMobileFriendly===!0?"Yes":c.isMobileFriendly===!1?"No":"—"})]},c.id))})]}),Pe==="notIndexed"&&!Me&&(I.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:(I.reasonGroups??[]).map(c=>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:()=>g(c.reason),onKeyDown:j=>{(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),g(c.reason))},tabIndex:0,role:"button","aria-label":`View ${c.reason} pages`,children:[e.jsx("td",{className:"text-strong",children:c.reason}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:c.count})]},c.reason))})]}),Pe==="notIndexed"&&!Me&&(I.reasonGroups??[]).length===0&&I.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:at.map(c=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:c.url}),e.jsx("td",{className:"text-secondary",children:c.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:c.coverageState??"Unknown"})]},c.id))})]}),Pe==="notIndexed"&&Me&&(()=>{const c=(I.reasonGroups??[]).find(j=>j.reason===Me);return c?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:()=>g(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:c.reason}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[c.count," affected page",c.count!==1?"s":""]})]}),!T()&&e.jsx(D,{type:"button",variant:"outline",size:"sm",disabled:Ge,onClick:()=>{Dn(c.urls.map(j=>j.url))},children:Ge?"Requesting…":`Request indexing (${c.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"}),!T()&&e.jsx("th",{className:"w-8"})]})}),e.jsx("tbody",{children:Ce.map(j=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:j.url}),e.jsx("td",{className:"text-secondary",children:j.crawlTime?j.crawlTime.split("T")[0]:"—"}),!T()&&e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-strong transition-colors",disabled:Ge,onClick:()=>{Dn([j.url])},title:"Request indexing",children:"Index"})})]},j.id))})]})]}):null})(),Pe==="deindexed"&&I.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:ns.map((c,j)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:c.url}),e.jsx("td",{className:"text-secondary",children:c.previousState}),e.jsx("td",{className:"text-secondary",children:c.currentState}),e.jsx("td",{className:"text-secondary",children:c.transitionDate.split("T")[0]})]},`${c.url}-${j}`))})]}),(Pe==="indexed"&&I.indexed.length===0||Pe==="notIndexed"&&!Me&&I.notIndexed.length===0||Pe==="deindexed"&&I.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),k&&e.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-between gap-x-4 gap-y-2 text-xs text-secondary",children:[e.jsxs("p",{className:"tabular-nums",children:["Showing ",e.jsx("span",{className:"text-neutral",children:te.toLocaleString("en-US")}),"–",e.jsx("span",{className:"text-neutral",children:V.toLocaleString("en-US")})," of"," ",e.jsx("span",{className:"text-neutral",children:ke.length.toLocaleString("en-US")})," URLs"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>ee(c=>Math.max(1,c-1)),disabled:Rt<=1,"aria-label":"Previous page",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-mono-800 disabled:hover:text-strong",children:[e.jsx(po,{className:"size-3.5"}),"Prev"]}),e.jsxs("span",{className:"tabular-nums",children:["Page ",e.jsx("span",{className:"text-strong",children:Rt})," of"," ",e.jsx("span",{className:"text-strong",children:It})]}),e.jsxs("button",{type:"button",onClick:()=>ee(c=>Math.min(It,c+1)),disabled:Rt>=It,"aria-label":"Next page",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-mono-800 disabled:hover:text-strong",children:["Next",e.jsx(Gs,{className:"size-3.5"})]})]})]})]})]}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:Be?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),e.jsxs(W,{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:"flex gap-1",role:"tablist","aria-label":"Performance window",children:il.map(c=>e.jsx("button",{type:"button",role:"tab","aria-selected":N===c,className:`px-2.5 py-1 text-xs rounded-full border transition-colors ${N===c?"bg-mono-700 border-mono-600 text-primary":"border-base text-secondary hover:border-strong hover:text-neutral"}`,onClick:()=>E(c),children:c==="all"?"All":c},c))}),e.jsxs(D,{type:"button",variant:"outline",size:"sm",disabled:ne,onClick:()=>{ye(0),Tt(0),Ks()},children:[e.jsx(dt,{className:`h-3.5 w-3.5 ${ne?"animate-spin":""}`,"aria-hidden":"true"}),ne?"Loading…":"Apply filters"]})]})]}),d&&d.daily.length>0&&(()=>{const c=d.daily,j=Math.max(...c.map(be=>be.impressions),1),{clicks:B,impressions:re,ctr:Ne}=d.totals,Ke=(Ne*100).toFixed(1),Ve=700,Mt=220,Ye={top:12,bottom:36,left:48,right:12},ei=Ve-Ye.left-Ye.right,Et=Mt-Ye.top-Ye.bottom,rs=ei/c.length,Ns=Math.max(Math.min(rs*.35,24),4),Mn=Math.max(Ns*.15,1),ti=be=>{if(be<=0)return 1;const ct=Math.pow(10,Math.floor(Math.log10(be))),Xe=be/ct,pt=Xe<=1.5?1.5:Xe<=3?3:Xe<=5?5:10;return Math.ceil(pt*ct)},ws=4,Ss=Math.ceil(ti(j)/ws)*ws,si=Array.from({length:ws+1},(be,ct)=>Ss/ws*ct),ni=be=>be>=1e3?`${(be/1e3).toFixed(be>=1e4?0:1)}k`:String(be);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:B.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:re.toLocaleString()})]})]}),e.jsxs("span",{className:"text-xs text-muted",children:["CTR ",e.jsxs("span",{className:"text-caution-400 tabular-nums font-medium",children:[Ke,"%"]})]})]}),e.jsx("div",{className:"relative w-full",style:{aspectRatio:`${Ve} / ${Mt}`},children:e.jsxs("svg",{viewBox:`0 0 ${Ve} ${Mt}`,className:"h-full w-full",children:[si.map((be,ct)=>{const Xe=Ye.top+Et-be/Ss*Et;return e.jsxs("g",{children:[e.jsx("line",{x1:Ye.left,y1:Xe,x2:Ve-Ye.right,y2:Xe,stroke:ze.gridLine,strokeWidth:"1"}),e.jsx("text",{x:Ye.left-6,y:Xe+3.5,textAnchor:"end",fill:ze.text,fontSize:"10",fontFamily:"inherit",children:ni(be)})]},`t-${ct}`)}),c.map((be,ct)=>{const Xe=Ye.left+rs*ct+rs/2,pt=be.impressions/Ss*Et,ks=be.clicks/Ss*Et;return e.jsxs("g",{children:[e.jsx("title",{children:`${be.date}
|
|
2
|
+
Clicks: ${be.clicks}
|
|
3
|
+
Impressions: ${be.impressions}
|
|
4
|
+
CTR: ${(be.ctr*100).toFixed(1)}%`}),e.jsx("rect",{x:Xe-Ns-Mn/2,y:Ye.top+Et-pt,width:Ns,height:Math.max(pt,1),rx:2,fill:Qe[1],opacity:.85}),e.jsx("rect",{x:Xe+Mn/2,y:Ye.top+Et-ks,width:Ns,height:Math.max(ks,1),rx:2,fill:Es.positiveDeep,opacity:.85})]},be.date)}),(()=>{const be=Math.min(c.length,7);return Array.from({length:be},(ct,Xe)=>{const pt=c.length===1?0:Math.round(Xe/(be-1)*(c.length-1)),ks=Ye.left+rs*pt+rs/2;return e.jsx("text",{x:ks,y:Mt-8,textAnchor:"middle",fill:ze.textDim,fontSize:"10",fontFamily:"inherit",children:c[pt].date.slice(5)},`xl-${pt}`)})})()]})})]})})(),e.jsxs("div",{className:"mt-3 grid gap-2 lg:grid-cols-5",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:O.startDate,onChange:c=>se(j=>({...j,startDate:c.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:O.endDate,onChange:c=>se(j=>({...j,endDate:c.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:"text",placeholder:"Contains query…","aria-label":"Filter query (substring match)",title:"Case-insensitive substring match on the query column.",value:O.query,onChange:c=>se(j=>({...j,query:c.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:"text",placeholder:"Contains page URL…","aria-label":"Filter page (substring match)",title:"Case-insensitive substring match on the page URL.",value:O.page,onChange:c=>se(j=>({...j,page:c.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:"number",min:"1",placeholder:"Rows per page (20)","aria-label":"Rows per page",title:"Rows per page. Ignored while a filter or column sort is active — then up to 500 matches are loaded.",value:O.limit,onChange:c=>se(j=>({...j,limit:c.target.value}))})]}),e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Query and page filters match case-insensitive substrings. Click Apply filters to run. When a filter or column sort is active, up to ",Ds.toLocaleString()," matching rows load so sorting covers the full set."]}),m.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(Pt).map(c=>e.jsx("th",{className:"text-right","aria-sort":Fe?.key===c?Fe.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:()=>He(j=>j?.key===c?j.dir==="desc"?{key:c,dir:"asc"}:null:{key:c,dir:"desc"}),children:[wi[c],Fe?.key===c?Fe.dir==="desc"?" ↓":" ↑":""]})},c))]})}),e.jsx("tbody",{children:ss.map((c,j)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:c.date}),e.jsx("td",{className:"max-w-xs truncate text-strong",children:c.query}),e.jsx("td",{className:"max-w-xs truncate text-secondary",children:c.page}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:c.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:c.impressions.toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[(Number.isFinite(c.ctr)?c.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:c.position.toFixed(1)})]},`${c.date}:${c.query}:${c.page}:${j}`))})]})}),fe?e.jsx("div",{className:"mt-3 text-xs text-muted",children:e.jsxs("span",{className:"tabular-nums",children:["Showing ",Y.toLocaleString()," matching row",Y===1?"":"s",Y>=Ds?` (capped at ${Ds.toLocaleString()} — narrow the filter to see more)`:""]})}):(he>0||pe)&&(()=>{const c=parseInt(O.limit,10)||20,j=he+1,B=he+m.length;return e.jsxs("div",{className:"mt-3 flex items-center justify-between text-xs text-muted",children:[e.jsxs("span",{className:"tabular-nums",children:["Showing ",j.toLocaleString()," – ",B.toLocaleString(),pe?"+":""]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(D,{type:"button",variant:"outline",size:"sm",disabled:ne||he===0,onClick:()=>{const re=Math.max(0,he-c);ye(re),Tt(re)},children:"Previous"}),e.jsx(D,{type:"button",variant:"outline",size:"sm",disabled:ne||!pe,onClick:()=>{const re=he+c;ye(re),Tt(re)},children:"Next"})]})]})})()]}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No performance rows match the current filters yet."})]}),e.jsxs(W,{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"})]})}),!T()&&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:u,onChange:c=>S(c.target.value),onKeyDown:c=>c.key==="Enter"&&void Tn()}),e.jsx(D,{type:"button",size:"sm",disabled:xe||!Ae?.propertyId||!u.trim(),onClick:ae(Tn),children:xe?"Inspecting…":"Inspect URL"})]}),P&&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:P.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:P.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:En(P.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:Je(P.crawlTime)})]})]})]}),e.jsxs(W,{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.jsxs(D,{type:"button",variant:"outline",size:"sm",disabled:z,onClick:()=>{ys({force:!0,notify:!0})},children:[e.jsx(dt,{className:`h-3.5 w-3.5 ${z?"animate-spin":""}`,"aria-hidden":"true"}),z?"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:q,onChange:c=>X(c.target.value)}),e.jsx(D,{type:"button",size:"sm",variant:"outline",disabled:z,onClick:()=>{ys({force:!0,notify:!0})},children:"Apply filter"})]}),h.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:h.map(c=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:c.url}),e.jsx("td",{className:"text-neutral",children:c.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:c.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:c.coverageState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:En(c.isMobileFriendly??null)}),e.jsx("td",{className:"text-secondary",children:Je(c.inspectedAt)})]},c.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No inspection history yet."})]}),e.jsxs(W,{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"})]})}),w.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:w.map(c=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:c.url}),e.jsx("td",{className:"text-secondary",children:c.previousState??"Unknown"}),e.jsx("td",{className:"text-neutral",children:c.currentState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:Je(c.transitionDate)})]},`${c.url}:${c.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No deindexed transitions recorded."})]})]}),Ae&&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:()=>es(c=>!c),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 ${St?"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"})]})}),St&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(W,{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:M,disabled:H||p.length===0,onChange:c=>_(c.target.value),children:p.length===0?e.jsx("option",{value:"",children:H?"Loading properties…":"No properties available"}):p.map(c=>e.jsxs("option",{value:c.siteUrl,children:[c.siteUrl," · ",c.permissionLevel]},c.siteUrl))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(D,{type:"button",size:"sm",variant:"outline",disabled:H,onClick:()=>{$n(Ae,{force:!0,notify:!0})},children:[e.jsx(dt,{className:`h-3.5 w-3.5 ${H?"animate-spin":""}`,"aria-hidden":"true"}),H?"Refreshing…":"Refresh properties"]}),!T()&&e.jsx(D,{type:"button",size:"sm",disabled:!M||je,onClick:ae(Ja),children:je?"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(W,{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:Q,onChange:c=>v(c.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:U,onChange:c=>L(c.target.checked)}),"Replace existing imported rows for the requested range"]})]}),!T()&&e.jsx(D,{type:"button",size:"sm",disabled:Us.isPending||!Ae.propertyId,onClick:ae(Za),children:Us.isPending?"Queueing…":"Queue sync"}),!Ae.propertyId&&e.jsx("p",{className:"text-xs text-caution-400",children:"Select a Search Console property before queueing a sync."})]})]})]}),e.jsxs(W,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Sitemap"}),e.jsx("h3",{children:"Sitemap configuration"})]})}),e.jsxs("div",{className:"mt-3 space-y-3",children:[Ae.sitemapUrl&&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:"Current sitemap URL"}),e.jsx("p",{className:"mt-1 text-sm text-strong break-all",children:Ae.sitemapUrl})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(D,{type:"button",size:"sm",variant:"outline",disabled:Nt||!Ae.propertyId,onClick:()=>{Va()},children:Nt?"Loading…":"Browse sitemaps from GSC"}),!T()&&e.jsx(D,{type:"button",size:"sm",variant:"outline",disabled:is.isPending||!Ae.propertyId,onClick:ae(Ln),children:is.isPending?"Discovering…":"Auto-discover and queue inspection"})]}),e.jsx("p",{className:"text-xs text-muted",children:"Browse lists available sitemaps without queueing a run. Auto-discover saves the primary sitemap and queues an inspection."}),We&&We.length>0&&e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3 space-y-2",children:[e.jsxs("p",{className:"text-xs uppercase tracking-wide text-muted",children:["Sitemaps (",We.length,")"]}),We.map(c=>{const j=c.contents?.[0];return e.jsxs("div",{className:"flex items-start justify-between gap-2 text-xs",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-strong break-all",children:c.path}),c.lastSubmitted&&e.jsxs("p",{className:"text-muted",children:["Submitted: ",c.lastSubmitted.split("T")[0]]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[j&&e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-neutral",children:[j.indexed," / ",j.submitted]}),e.jsx("p",{className:"text-muted",children:"indexed"})]}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong transition-colors",onClick:()=>st(c.path),children:"Use"})]})]},c.path)})]}),!T()&&e.jsxs("div",{className:"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:Ae.sitemapUrl?"Update sitemap URL…":"https://example.com/sitemap.xml",value:_e,onChange:c=>st(c.target.value),onKeyDown:c=>c.key==="Enter"&&_e.trim()&&void vs()}),e.jsx(D,{type:"button",size:"sm",disabled:nt||!_e.trim(),onClick:ae(vs),children:nt?"Saving…":Ae.sitemapUrl?"Update":"Save"})]}),!T()&&e.jsxs("div",{className:"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:"Sitemap URL for inspection (leave empty for saved default)",id:`gsc-sitemap-inspect-${t}`}),e.jsx(D,{type:"button",size:"sm",variant:"outline",disabled:zs.isPending||!Ae.propertyId,onClick:ae(async()=>{const j=document.getElementById(`gsc-sitemap-inspect-${t}`)?.value?.trim()||Ae.sitemapUrl||void 0;me(null),lt(null);try{await zs.mutateAsync({projectName:t,projectLabel:t,opts:{sitemapUrl:j}})}catch{}}),children:zs.isPending?"Queueing…":"Inspect sitemap"})]}),!Ae.propertyId&&e.jsx("p",{className:"text-xs text-caution-400",children:"Select a Search Console property first."})]})]})]})]})]})]})}const ol=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function ll({projectName:t,projectId:s}){const n=vt(),[a,i]=l.useState(null),[r,o]=l.useState(null),[p,x]=l.useState(!1),m=Ie(bn({client:Z,path:{name:t}})),f=m.data?.find($=>$.connectionType==="gbp"),d=!!f,R=a?{locationName:a}:void 0,h=Ie({...Bi({client:Z,path:{name:t}}),enabled:d}),A=Ie({...Fi({client:Z,path:{name:t},query:R}),enabled:d}),w=Ie({...Gi({client:Z,path:{name:t},query:R}),enabled:d}),C=Ie({...qi({client:Z,path:{name:t},query:R}),enabled:d}),P=Ie({..._i({client:Z,path:{name:t},query:R}),enabled:d}),F=Ie({...Ui({client:Z,path:{name:t},query:R}),enabled:d}),M=Ie({queryKey:["gbp-section-insights",t],queryFn:()=>zi(t),enabled:d});function _(){n.invalidateQueries({predicate:$=>{const H=$.queryKey[0];return typeof H?._id=="string"&&H._id.startsWith("getApiV1ProjectsByNameGbp")}})}const u=ms({...Qi(),onSuccess:$=>{Ki({id:$.runId,projectId:s,kind:xs["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),K({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),S=l.useSyncExternalStore(Hi,Bn,Bn),Q=Object.values(S.runs).some($=>$.kind===xs["gbp-sync"]&&$.projectId===s),v=u.isPending||Q,U=ms({...Wi(),onSuccess:()=>_()});if(l.useEffect(()=>{if(!a||!h.data)return;const $=h.data.locations.filter(H=>H.selected);($.length<=1||!$.some(H=>H.locationName===a))&&i(null)},[a,h.data]),l.useEffect(()=>{if(!r||!h.data)return;(a?[a]:h.data.locations.filter(H=>H.selected).map(H=>H.locationName)).includes(r)||o(null)},[r,h.data,a]),m.isLoading)return null;if(!f){const $=[{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(W,{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:$.map((H,Te)=>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:Te+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:H.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:H.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:H.note})]})]},H.title))})]})})}const L=A.data,N=h.data?.locations??[],E=N.filter($=>$.selected),O=w.data?.keywords??[],se=C.data?.lodging??[],he=P.data?.placeActions??[],ye=F.data?.places??[],pe=N.length>0?N[0].accountName:f.domain,ge=a?N.find($=>$.locationName===a)?.displayName??null:null,Y=a?N.filter($=>$.locationName===a):E,de=new Set(Y.map($=>$.locationName)),fe=se.filter($=>de.has($.locationName)),b=he.filter($=>de.has($.locationName)),q=ye.filter($=>de.has($.locationName)),X=new Set(E.map($=>$.locationName)),le=a?O:O.filter($=>X.has($.locationName)),ce=!a&&E.length>1,$e=(M.data??[]).filter($=>!$.dismissed&&ol.has($.type)&&(!ge||$.query===ge||$.query===a||$.title.startsWith(ge)));return e.jsx("section",{className:"page-section-divider",children:e.jsxs(W,{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(De,{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(oe,{tone:"positive",children:"Connected"}),!T()&&e.jsx(D,{type:"button",variant:"outline",size:"sm",disabled:v,onClick:()=>u.mutate({client:Z,path:{name:t},body:{}}),children:v?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-muted",children:[pe?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-secondary",children:pe})," · "]}):null,h.data?`${h.data.totalSelected} of ${h.data.totalDiscovered} locations tracked`:"Loading locations…"]}),E.length>1&&e.jsxs("div",{className:"mb-5 flex flex-wrap gap-1.5",role:"tablist","aria-label":"Location",children:[e.jsx(Zn,{label:"All locations",active:a===null,onClick:()=>i(null)}),E.map($=>e.jsx(Zn,{label:$.displayName,active:a===$.locationName,onClick:()=>i($.locationName)},$.id))]}),E.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:[$e.length>0&&e.jsxs("div",{className:"mb-6 grid gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Needs attention"}),$e.map($=>e.jsx("div",{className:["insight-card",vl($.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:[$.title,$.recommendation?.reason&&e.jsx(De,{text:$.recommendation.reason})]})},$.id))]}),L&&e.jsx(kl,{performance:L.performance,freshness:L.freshness,timeseries:L.timeseries}),L?.profileCompleteness&&e.jsx(cl,{summary:L.profileCompleteness}),Y.length>0&&e.jsx(dl,{locations:Y,lodging:fe,places:q,placeActions:b,expandedLocation:r,onToggleExpanded:$=>{o(H=>H===$?null:$)}}),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"}),w.data&&w.data.total>0&&e.jsxs("span",{className:"text-[11px] text-faint",children:[w.data.thresholdedPct,"% privacy-thresholded"]})]}),le.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"}),ce&&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:le.slice(0,25).map($=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-neutral",children:$.keyword}),ce&&e.jsx("td",{className:"text-muted",children:N.find(H=>H.locationName===$.locationName)?.displayName??$.locationName}),e.jsx("td",{className:"text-right font-mono text-strong",children:$.valueCount!==null?$.valueCount.toLocaleString():e.jsxs("span",{className:"text-muted",title:"Privacy floor — Google withheld the exact count",children:["<",$.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-faint",children:[$.periodStart,"–",$.periodEnd]})]},`${$.locationName}:${$.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:()=>x($=>!$),"aria-expanded":p,children:[e.jsx("span",{"aria-hidden":"true",children:p?"▾":"▸"})," Manage locations (",N.length,")"]}),p&&e.jsx("div",{className:"mt-3",children:N.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"}),!T()&&e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:N.map($=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:$.displayName}),e.jsx("td",{className:"text-muted",children:$.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(oe,{tone:$.selected?"positive":"neutral",children:$.selected?"Tracked":"Not tracked"})}),!T()&&e.jsx("td",{className:"text-right",children:e.jsx(D,{type:"button",variant:"outline",size:"sm",disabled:U.isPending,onClick:()=>U.mutate({client:Z,path:{name:t,locationName:$.locationName},body:{selected:!$.selected}}),children:$.selected?"Untrack":"Track"})})]},$.id))})]})})]})]})})}function Zn({label:t,active:s,onClick:n}){return e.jsx("button",{type:"button",role:"tab","aria-selected":s,onClick:n,className:`rounded-full border px-3 py-1 text-xs transition-colors ${s?"border-mono-500 bg-mono-800 text-heading":"border-mono-700/60 text-secondary hover:border-mono-600 hover:text-strong"}`,children:t})}function cl({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:cs(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:cs(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:cs(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:cs(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:cs(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(De,{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 ${yl(a.tone)}`,children:a.value}),a.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-faint",children:a.detail})]},a.label))})]})}function dl({locations:t,lodging:s,places:n,placeActions:a,expandedLocation:i,onToggleExpanded:r}){const o=new Map(s.map(m=>[m.locationName,m])),p=new Map(n.map(m=>[m.locationName,m])),x=new Map;for(const m of a){const f=x.get(m.locationName)??[];f.push(m),x.set(m.locationName,f)}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(De,{text:T()?"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(m=>{const f=o.get(m.locationName)??null,d=p.get(m.locationName)??null,R=x.get(m.locationName)??[],h=i===m.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:m.displayName}),e.jsx("p",{className:"mt-1 text-xs text-faint",children:m.primaryCategoryDisplayName??"Primary category not returned"}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[e.jsx(oe,{tone:m.selected?"positive":"neutral",children:m.selected?"Tracked":"Not tracked"}),m.openStatus&&m.openStatus!=="OPEN"&&e.jsx(oe,{tone:m.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:_a(m.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(ml,{location:m})}),e.jsx("td",{children:e.jsx(xl,{lodging:f})}),e.jsx("td",{children:e.jsx(pl,{place:d,mapsUri:m.mapsUri})}),e.jsx("td",{children:e.jsx(fl,{actions:R})}),e.jsx("td",{className:"text-right",children:e.jsx(D,{type:"button",variant:"outline",size:"sm",onClick:()=>r(m.locationName),children:h?"Hide":"Details"})})]}),h&&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(jl,{location:m,lodging:f,place:d,placeActions:R})})})]},m.id)})})]})})]})}function ul(t){return[{label:"Description",tone:$t(t.description)?"positive":"neutral",value:$t(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:$t(t.primaryPhone)?"positive":"neutral",value:$t(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:$t(t.websiteUri)?"positive":"neutral",value:$t(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 ml({location:t}){const s=ul(t);return e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>e.jsxs(oe,{tone:n.tone,children:[n.label," ",n.value]},n.label))})}function xl({lodging:t}){return e.jsx(Nn,{...hl(t)})}function hl(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 pl({place:t,mapsUri:s}){return e.jsx(Nn,{...gl(t,s)})}function gl(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 fl({actions:t}){return e.jsx(Nn,{...bl(t)})}function bl(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 Nn({tone:t,label:s,detail:n}){return e.jsxs("div",{children:[e.jsx(oe,{tone:t,children:s}),e.jsx("p",{className:"mt-1.5 text-xs leading-5 text-faint",children:n})]})}function jl({location:t,lodging:s,place:n,placeActions:a}){const i=s?wl(s.attributes):[];return e.jsxs("div",{className:"grid gap-5 text-xs lg:grid-cols-3",children:[e.jsxs(Xs,{title:"Owner profile · Business Information",children:[e.jsx(Ue,{label:"Primary category",value:t.primaryCategoryDisplayName??"Not returned"}),e.jsx(Ue,{label:"Secondary categories",value:t.additionalCategories.length>0?t.additionalCategories.join(", "):"Not returned"}),e.jsx(Ue,{label:"Description",value:$t(t.description)?t.description:"Not returned"}),e.jsx(Ue,{label:"Hours",value:t.regularHours?"Returned by Google":"Not returned"}),e.jsx(Ue,{label:"Service area",value:t.serviceArea?"Returned by Google":"Not returned"}),e.jsx(Ue,{label:"Phone",value:t.primaryPhone??"Not returned"}),e.jsx(Ue,{label:"Website",value:t.websiteUri??"Not returned"}),e.jsx(Ue,{label:"Open status",value:_a(t.openStatus)}),e.jsx(Ue,{label:"Opening date",value:t.openingDate??"Not returned"})]}),e.jsx(Xs,{title:"Hotel data · Lodging API",children:s?e.jsxs(e.Fragment,{children:[e.jsx(Ue,{label:"Last checked",value:ea(s.syncedAt)}),e.jsx(Ue,{label:"Groups returned",value:String(s.populatedGroupCount)}),e.jsx(Ue,{label:"Populated groups",value:i.length>0?i.join(", "):"None returned"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Lodging API snapshot was stored for this location."})}),e.jsxs(Xs,{title:"Public listing + CTAs",children:[n?e.jsxs(e.Fragment,{children:[e.jsx(Ue,{label:"Places tier",value:n.tier}),e.jsx(Ue,{label:"Last checked",value:ea(n.syncedAt)}),e.jsx(Ue,{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(r=>e.jsxs("div",{className:"grid gap-0.5",children:[e.jsxs("span",{className:"font-medium text-neutral",children:[Os(r.placeActionType),r.isPreferred?" · preferred":""]}),e.jsxs("span",{className:"text-faint",children:[Os(r.providerType),r.uri?` · ${Nl(r.uri)}`:""]})]},r.placeActionLinkName))})})]})]})}function Xs({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 Ue({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 cs(t,s,n){return t===s?"positive":t===0?n:"caution"}function yl(t){switch(t){case"positive":return"text-positive";case"caution":return"text-caution";case"negative":return"text-negative";case"neutral":return"text-neutral"}}function vl(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function $t(t){return typeof t=="string"&&t.trim().length>0}function _a(t){return t?Os(t):"Not returned"}function Os(t){return t?t.toLowerCase().split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"Unknown"}function Nl(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function ea(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function wl(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&Sl(n)).map(([s])=>Os(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function Sl(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function kl({performance:t,freshness:s,timeseries:n}){const a=t.totals,i=Vi.filter(A=>(a[A]??0)>0),r=Yi.filter(A=>(a[A]??0)>0),o=Object.keys(a).filter(A=>(a[A]??0)>0&&Xi(A)==="other").sort((A,w)=>(a[w]??0)-(a[A]??0)),p=Object.keys(a).filter(A=>(a[A]??0)===0).sort(),x=n.map(A=>{const w={date:A.date};for(const[C,P]of Object.entries(A.metrics))w[C]=P;return w}),m=n.find(A=>A.pending)?.date,f=n.length>0?n[n.length-1].date:void 0,d=x.length>0,R=s.dataThroughDate?`Data through ${mt(s.dataThroughDate)}${s.pendingDays>0?` · ${s.pendingDays}d pending`:""}`:null,h=[...i,...o];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"}),R&&e.jsx("span",{className:"text-[11px] text-muted",children:R})]}),!d||i.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(ta,{data:x,metrics:i,kind:"line",firstPending:m,lastDate:f}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-x-5 gap-y-1",children:h.map(A=>e.jsxs("span",{className:"text-sm text-secondary",children:[Ms(A)," ",e.jsx("span",{className:"font-mono text-heading",children:(a[A]??0).toLocaleString()})]},A))})]})]}),d&&r.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(ta,{data:x,metrics:r,kind:"area",firstPending:m,lastDate:f})]}),p.length>0&&e.jsxs("p",{className:"text-xs text-faint",children:["Not active: ",p.map(A=>Ms(A)).join(", ")]})]})}function ta({data:t,metrics:s,kind:n,firstPending:a,lastDate:i}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(Wt,{width:"100%",height:"100%",children:e.jsxs(Vt,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(yn,{stroke:jn,vertical:!1}),e.jsx(Yt,{dataKey:"date",tick:et,tickLine:!1,axisLine:{stroke:ut},tickFormatter:Ht,minTickGap:24}),e.jsx(Xt,{tick:et,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Jt,{...Dt,labelFormatter:mt,formatter:(r,o)=>[typeof r=="number"?r.toLocaleString():String(r??0),Ms(String(o??""))]}),e.jsx($a,{wrapperStyle:{fontSize:11,color:ze.text},formatter:r=>Ms(r)}),a&&i&&e.jsx(jo,{x1:a,x2:i,fill:ze.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:ze.textDim,fontSize:10}}),s.map((r,o)=>n==="line"?e.jsx(vn,{type:"monotone",dataKey:r,stroke:Qe[o%Qe.length],strokeWidth:2,dot:!1,isAnimationActive:!1},r):e.jsx(Ft,{type:"monotone",dataKey:r,stackId:"reach",stroke:Qe[o%Qe.length],fill:Qe[o%Qe.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},r))]})})})}function Js({children:t,label:s="More info",placement:n="top",className:a}){const i=l.useId(),[r,o]=l.useState(!1);return e.jsxs("span",{className:`relative inline-flex ${a??""}`,children:[e.jsx("button",{type:"button","aria-label":s,"aria-describedby":r?i: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:()=>o(!0),onMouseLeave:()=>o(!1),onFocus:()=>o(!0),onBlur:()=>o(!1),children:e.jsx(yo,{className:"h-3.5 w-3.5","aria-hidden":!0})}),r&&e.jsx("span",{id:i,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 Ct=50,sa={commoncrawl:"Common Crawl","bing-webmaster":"Bing Webmaster"},Cl={commoncrawl:"Common Crawl hyperlink graph · refreshes ~monthly when a release sync completes","bing-webmaster":"Bing Webmaster Tools · live inbound links from your connected account"};function At(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function Bt(t){return t.toLocaleString()}function Al(t){const s=Number(t);return Number.isFinite(s)?`${(s*100).toFixed(1)}%`:"—"}function $l(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 Pl(t){const s=t.filter(n=>n.kind===xs["backlink-extract"]&&!ja(n.status));return s.length===0?null:s.reduce((n,a)=>n.createdAt>a.createdAt?n:a)}function Dl(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 i=Math.floor(a/60),r=a%60;return r===0?`${i}m`:`${i}m ${r}s`}function Ll({projectName:t}){const[s,n]=l.useState(null),[a,i]=l.useState("commoncrawl"),[r,o]=l.useState(null),[p,x]=l.useState(null),[m,f]=l.useState([]),[d,R]=l.useState(null),[h,A]=l.useState(null),[w,C]=l.useState("commoncrawl"),[P,F]=l.useState(null),[M,_]=l.useState(Date.now()),[u,S]=l.useState(0),[Q,v]=l.useState(!0),[U,L]=l.useState(!1),[N,E]=l.useState(!1),[O,se]=l.useState(null),he=l.useRef(null),ye=l.useRef(!1),pe=l.useCallback(async()=>{v(!0),se(null);try{const[G,z,ue,xe,y,I]=await Promise.all([Ji(t,{excludeCrawlers:!0}).catch(()=>null),Zi().catch(()=>null),er(t,{excludeCrawlers:!0,source:a}).catch(()=>null),tr(t,{limit:Ct,offset:u,excludeCrawlers:!0,source:a}).catch(Be=>{if(Be instanceof un&&Be.code==="NOT_FOUND")return null;throw Be}),sr(t,{source:a}).catch(()=>[]),nr(t).catch(()=>[])]);n(G),R(z),o(ue),x(xe),f(y);const Le=Pl(I);A(Le),he.current=Le?.id??null}catch(G){se(G instanceof Error?G.message:"Failed to load backlinks")}finally{v(!1)}},[t,u,a]);l.useEffect(()=>{pe()},[pe]),l.useEffect(()=>{if(!s||ye.current)return;const G=s.sources.find(xe=>xe.hasData),z=s.sources.find(xe=>xe.connected),ue=G?.source??z?.source;ue&&ue!==a&&i(ue)},[s,a]);function ge(G){ye.current=!0,S(0),i(G)}l.useEffect(()=>{if(!h)return;const G=h.id;let z=!1;const ue=async()=>{try{const y=await ya(G);if(z)return;ja(y.status)?(A(null),F(y),await pe()):A(I=>I?.id===y.id?{...I,...y}:I)}catch{}},xe=window.setInterval(()=>{ue()},3e3);return()=>{z=!0,window.clearInterval(xe)}},[h,pe]),l.useEffect(()=>{if(!h)return;const G=window.setInterval(()=>_(Date.now()),1e3);return()=>window.clearInterval(G)},[h]),l.useEffect(()=>{if(!P||P.status==="failed")return;const G=window.setTimeout(()=>F(null),1e4);return()=>window.clearTimeout(G)},[P]);async function Y(){L(!0),se(null);try{const G=await or(t);C("commoncrawl"),A(G),he.current=G.id}catch(G){G instanceof un&&G.code==="MISSING_DEPENDENCY"?se("DuckDB is not installed. Visit the Backlinks admin page to install it."):se(G instanceof Error?G.message:"Failed to trigger extract")}finally{L(!1)}}async function de(){E(!0),se(null);try{const G=await rr(t);C("bing-webmaster"),A(G),he.current=G.id}catch(G){se(G instanceof Error?G.message:"Failed to trigger Bing sync")}finally{E(!1)}}const fe=l.useMemo(()=>m.slice().sort((G,z)=>G.queriedAt.localeCompare(z.queriedAt)).map(G=>({date:G.queriedAt,linkingDomains:G.totalLinkingDomains})),[m]),b=p?.rows??[],q=p?.total??0,X=r?.excludedLinkingDomains??0,le=q>Ct,ce=Math.floor(u/Ct)+1,$e=Math.max(1,Math.ceil(q/Ct));return l.useEffect(()=>{u>0&&u>=q&&S(0)},[u,q]),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"}),e.jsxs("p",{className:"text-sm text-muted mt-1 max-w-2xl",children:["Domains linking to "," ",e.jsx("span",{className:"text-neutral",children:t}),", from whichever source you have set up — the"," ",e.jsx("span",{className:"text-neutral",children:"Common Crawl"})," hyperlink graph (~monthly) and"," ",e.jsx("span",{className:"text-neutral",children:"Bing Webmaster"})," inbound links (live)."]})]})}),O&&e.jsx(W,{className:"surface-card p-4 mb-4 border-negative-800/60",children:e.jsx("p",{className:"text-sm text-negative",children:O})}),h&&e.jsx(W,{className:"surface-card p-4 mb-4 border-info-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ar,{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:w==="bing-webmaster"?"Bing sync running":"Extract running"}),e.jsx(oe,{tone:"neutral",children:h.status}),e.jsxs("span",{className:"text-xs text-muted tabular-nums",children:[Dl(h.startedAt??null,h.createdAt)," elapsed · refreshing every 3s"]}),e.jsxs("span",{className:"sr-only",children:["now=",M]})]}),w==="bing-webmaster"?e.jsxs("p",{className:"text-xs text-muted mt-1",children:["Pulling inbound links live from Bing Webmaster for"," ",e.jsx("span",{className:"text-neutral",children:t}),". Time depends on how many pages link to your site."]}):e.jsxs("p",{className:"text-xs text-muted mt-1",children:["Re-querying the cached Common Crawl release for"," ",e.jsx("span",{className:"text-neutral",children:t}),". No re-download — the ~16 GB dump already lives at"," ",e.jsx("code",{className:"text-secondary",children:"~/.canonry/cache/commoncrawl/"}),". Typically takes ~5 minutes."]})]})]})}),P&&!h&&e.jsx(W,{className:`surface-card p-4 mb-4 ${P.status==="failed"?"border-negative-800/60":"border-positive-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[P.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(Pa,{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 ${P.status==="failed"?"text-negative":"text-positive"}`,children:w==="bing-webmaster"?P.status==="failed"?"Bing sync failed":"Bing sync complete":P.status==="failed"?"Extract failed":"Extract complete"}),P.error?e.jsx("p",{className:"text-xs text-muted mt-1",children:ir(P.error)}):P.status!=="failed"?e.jsx("p",{className:"text-xs text-muted mt-1",children:w==="bing-webmaster"?"Inbound links refreshed live from Bing Webmaster.":"Backlinks refreshed from the cached release."}):null]})]})}),$()]});function $(){return Q||!s?e.jsx(W,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading backlinks…"})}):!s.anyConnected&&!s.anyData?Te():e.jsxs(e.Fragment,{children:[H(s),a==="bing-webmaster"?je():ve()]})}function H(G){return e.jsx("div",{className:"flex items-center gap-2 mb-4 flex-wrap",role:"tablist","aria-label":"Backlink source",children:G.sources.map(z=>{const ue=z.source===a,xe=z.hasData?"bg-positive-500":z.connected?"bg-caution-500":"bg-mono-600";return e.jsxs("button",{type:"button",role:"tab","aria-selected":ue,onClick:()=>ge(z.source),className:`inline-flex items-center gap-2 rounded-full border px-3 py-1 text-xs transition-colors focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-500 ${ue?"border-mono-500 bg-mono-800 text-heading":"border-base bg-bg-elevated/40 text-secondary hover:text-strong"}`,children:[e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${xe}`,"aria-hidden":!0}),sa[z.source],z.hasData&&e.jsx("span",{className:"text-muted tabular-nums",children:Bt(z.totalLinkingDomains)})]},z.source)})})}function Te(){return e.jsx(W,{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(Qs,{className:"h-5 w-5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No backlink source set up yet"}),e.jsxs("p",{className:"text-sm text-muted mt-1 max-w-2xl",children:["Connect at least one source to see which domains link to"," ",e.jsx("code",{className:"text-neutral",children:t}),":"]}),e.jsxs("ul",{className:"mt-3 space-y-2 text-sm text-secondary",children:[e.jsxs("li",{children:[e.jsx("span",{className:"text-strong",children:"Common Crawl"})," — free public hyperlink graph, refreshes ~monthly. Enable backlinks and run a workspace release sync."]}),e.jsxs("li",{children:[e.jsx("span",{className:"text-strong",children:"Bing Webmaster"})," — live inbound links from your verified site. Connect a Bing Webmaster account, then sync."]})]}),!T()&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(D,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:At("/backlinks"),children:"Set up Common Crawl"})})}),e.jsxs("p",{className:"mt-3 text-xs text-muted",children:["Connect Bing with"," ",e.jsxs("code",{className:"text-secondary",children:["canonry bing connect ",t," --api-key <key>"]}),"."]})]})]})]})})}function je(){const G=s?.sources.find(y=>y.source==="bing-webmaster"),z=G?.connected??!1,ue=G?.hasData??!1;return r!==null&&r.totalLinkingDomains>0?ne(T()?null:e.jsxs(D,{type:"button",variant:"outline",size:"sm",disabled:N||h!==null,onClick:ae(de),children:[e.jsx(Gt,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Sync running…":N?"Queuing…":"Re-sync Bing"]})):e.jsx(W,{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(Qs,{className:"h-5 w-5","aria-hidden":!0})}),e.jsx("div",{className:"flex-1",children:z&&ue?X>0?e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No non-crawler referring domains"}),e.jsxs("p",{className:"text-sm text-muted mt-1",children:["Bing Webmaster synced for ",e.jsx("code",{className:"text-neutral",children:t}),", but"," ",Bt(X)," crawler/proxy referring domain",X===1?"":"s"," in the latest window ",X===1?"is":"are"," hidden by default. Re-sync to check for new links."]}),!T()&&e.jsx("div",{className:"mt-4",children:e.jsxs(D,{type:"button",variant:"outline",size:"sm",disabled:N||h!==null,onClick:ae(de),children:[e.jsx(Gt,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Sync running…":N?"Queuing…":"Re-sync Bing inbound links"]})})]}):e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No Bing inbound links returned"}),e.jsxs("p",{className:"text-sm text-muted mt-1",children:["Bing Webmaster synced for ",e.jsx("code",{className:"text-neutral",children:t}),", but the Bing backlink API returned ",e.jsx("span",{className:"text-neutral",children:"0 inbound-link rows"})," in the latest window. There were no referring domains to filter."]}),e.jsx("p",{className:"text-xs text-muted mt-2",children:"Re-sync later or compare against the Bing Webmaster Tools backlink export for this verified site."}),!T()&&e.jsx("div",{className:"mt-4",children:e.jsxs(D,{type:"button",variant:"outline",size:"sm",disabled:N||h!==null,onClick:ae(de),children:[e.jsx(Gt,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Sync running…":N?"Queuing…":"Re-sync Bing inbound links"]})})]}):z?e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No Bing inbound links yet"}),e.jsxs("p",{className:"text-sm text-muted mt-1",children:["Bing Webmaster is connected for ",e.jsx("code",{className:"text-neutral",children:t})," but no inbound links have been synced yet. Run a sync to pull them live from your account."]}),!T()&&e.jsx("div",{className:"mt-4",children:e.jsxs(D,{type:"button",size:"sm",disabled:N||h!==null,onClick:ae(de),children:[e.jsx(Ut,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Sync running…":N?"Queuing…":"Sync Bing inbound links"]})})]}):e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Bing Webmaster not connected"}),e.jsxs("p",{className:"text-sm text-muted mt-1",children:["Connect a Bing Webmaster account for ",e.jsx("code",{className:"text-neutral",children:t})," to pull live inbound links, then sync."]}),e.jsxs("pre",{className:"mt-3 rounded bg-bg-elevated border border-base px-3 py-2 text-xs text-neutral overflow-x-auto",children:["canonry bing connect ",t," --api-key <key>"]})]})})]})})}function ve(){const G=r!==null&&r.totalLinkingDomains>0,z=P?.status==="failed",ue=r!==null&&r.totalLinkingDomains===0&&!z,xe=d?.status==="ready",y=d?.status==="failed",I=d&&(d.status==="downloading"||d.status==="querying"||d.status==="queued");return G?ne(e.jsxs(e.Fragment,{children:[!T()&&e.jsxs(e.Fragment,{children:[e.jsxs(D,{type:"button",variant:"outline",size:"sm",disabled:U||h!==null,onClick:ae(Y),children:[e.jsx(Gt,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":U?"Queuing…":"Re-run extract"]}),e.jsxs(Js,{label:"What does Re-run extract do?",children:[e.jsxs("span",{className:"block",children:["Re-queries the ",e.jsx("span",{className:"text-strong",children:"cached release files"})," at"," ",e.jsx("code",{className:"text-neutral",children:"~/.canonry/cache/commoncrawl/"})," for ",e.jsx("span",{className:"text-strong",children:t}),". Replaces existing backlink rows for this project under the current release."]}),e.jsxs("span",{className:"mt-2 block text-secondary",children:[e.jsx("span",{className:"text-strong",children:"No re-download"})," of the ~16 GB dump. Typically ",e.jsx("span",{className:"text-strong",children:"~5 min"}),"."]})]})]}),!T()&&e.jsx(D,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:At("/backlinks"),children:"Open admin"})})]})):e.jsx(W,{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(Qs,{className:"h-5 w-5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1",children:[!d&&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."}),!T()&&e.jsx("div",{className:"mt-4",children:e.jsx(D,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:At("/backlinks"),children:"Set up backlinks"})})})]}),I&&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 (",d.status,d.phaseDetail?` — ${d.phaseDetail}`:"","). Backlinks will appear here once it finishes."]}),!T()&&e.jsx("div",{className:"mt-4",children:e.jsx(D,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:At("/backlinks"),children:"View sync status"})})})]}),y&&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:d.error??"The workspace release sync failed. Retry from the Backlinks admin page."}),!T()&&e.jsx("div",{className:"mt-4",children:e.jsx(D,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:At("/backlinks"),children:"Go to Backlinks admin"})})})]}),xe&&!I&&!ue&&!z&&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-muted mt-1",children:["Release ",e.jsx("code",{className:"text-neutral",children:d.release})," is ready but no backlinks have been extracted for"," ",e.jsx("code",{className:"text-neutral",children:t}),". Run an extract to populate data using the cached release."]}),!T()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(D,{type:"button",size:"sm",disabled:U||h!==null,onClick:ae(Y),children:[e.jsx(Ut,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":U?"Queuing…":"Run extract"]}),e.jsxs(Js,{label:"What does Run extract do?",children:[e.jsxs("span",{className:"block",children:["Runs a DuckDB query against the ",e.jsx("span",{className:"text-strong",children:"cached release files"})," at"," ",e.jsx("code",{className:"text-neutral",children:"~/.canonry/cache/commoncrawl/"})," to find referring domains for ",e.jsx("span",{className:"text-strong",children:t}),"."]}),e.jsxs("span",{className:"mt-2 block text-secondary",children:["No re-download. Typically takes ",e.jsx("span",{className:"text-strong",children:"~5 min"}),"."]})]})]})]}),z&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Last extract failed"}),e.jsxs("p",{className:"text-sm text-muted mt-1",children:["See the error above for details. If the cache files for release"," ",e.jsx("code",{className:"text-neutral",children:d?.release})," are missing, re-sync the release from the Backlinks admin to restore the ~16 GB dump, then re-run the extract."]}),!T()&&e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(D,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:At("/backlinks"),children:"Go to Backlinks admin"})})})]}),ue&&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-muted mt-1",children:["The last extract against release ",e.jsx("code",{className:"text-neutral",children:r.release})," found"," ",e.jsx("span",{className:"text-neutral",children:"0 referring domains"})," for"," ",e.jsx("code",{className:"text-neutral",children:r.targetDomain}),". This can happen when:"]}),e.jsxs("ul",{className:"mt-2 space-y-1 text-xs text-muted list-disc list-inside",children:[e.jsx("li",{children:"the domain is newer than the release’s crawl window"}),e.jsx("li",{children:"the Common Crawl snapshot didn’t capture pages that link to it"}),e.jsx("li",{children:"the extract ran against a cache that was missing or incomplete"})]}),e.jsx("p",{className:"text-sm text-muted mt-3",children:"Try syncing a newer release — each Common Crawl dump is a different snapshot of the web graph."}),!T()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(D,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:At("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(D,{type:"button",variant:"outline",size:"sm",disabled:U||h!==null,onClick:ae(Y),children:[e.jsx(Ut,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":U?"Queuing…":"Re-run extract"]}),e.jsxs(Js,{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:r.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 ne(G){if(!r)return null;const z=a==="bing-webmaster",ue=z?"Inbound links":"Linking hosts",xe=z?"inbound links":"linking hosts",y=z?"window":"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:Bt(r.totalLinkingDomains)})}),e.jsxs("p",{className:"metric-card-sub",children:["unique domains linking to ",r.targetDomain]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("p",{className:"metric-card-eyebrow",children:["Total ",xe]}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:Bt(r.totalHosts)})}),e.jsxs("p",{className:"metric-card-sub",children:["aggregate ",xe," 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:Al(r.top10HostsShare)})}),e.jsxs("p",{className:"metric-card-sub",children:["share of ",xe," from the 10 largest linking domains"]})]})]}),e.jsxs("p",{className:"text-xs text-faint mt-2",children:[e.jsx("span",{className:"text-secondary",children:sa[a]})," · ",y," ",e.jsx("code",{className:"text-secondary",children:r.release})," · queried ",$l(r.queriedAt),X>0&&e.jsxs(e.Fragment,{children:[" · ",e.jsxs("span",{className:"text-muted",children:[X," crawler/proxy domain",X===1?"":"s"," hidden"]})]})]}),e.jsx("p",{className:"text-[11px] text-faint mt-0.5",children:Cl[a]}),fe.length>=2&&e.jsxs(W,{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(Wt,{width:"100%",height:"100%",children:e.jsxs(Vt,{data:fe,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:Qe[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:Qe[0],stopOpacity:0})]})}),e.jsx(Yt,{dataKey:"date",tick:et,stroke:ut,tickFormatter:Ht}),e.jsx(Xt,{tick:et,stroke:ut,allowDecimals:!1}),e.jsx(Jt,{contentStyle:Dt.contentStyle,labelStyle:Dt.labelStyle,itemStyle:Dt.itemStyle,labelFormatter:mt}),e.jsx(Ft,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:Qe[0],fill:"url(#bl-gradient)",strokeWidth:2})]})})})]}),e.jsxs("div",{className:"mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Top referring domains"}),le&&e.jsxs("p",{className:"text-xs text-faint",children:["Page ",ce," of ",$e," · ",Bt(q)," total"]})]}),e.jsx(W,{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:ue})]})}),e.jsxs("tbody",{children:[b.map(I=>e.jsxs("tr",{className:"border-b border-mono-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-strong",children:I.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-secondary tabular-nums",children:Bt(I.numHosts)})]},I.linkingDomain)),b.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-muted",colSpan:2,children:X>0&&q===0?`Every referring domain in this ${y} was a crawler/proxy host (${X} hidden).`:`No referring domains in this ${y}.`})})]})]})}),le&&e.jsxs("div",{className:"flex items-center justify-end gap-2 mt-2",children:[e.jsx(D,{type:"button",variant:"outline",size:"sm",disabled:u===0,onClick:()=>S(I=>Math.max(0,I-Ct)),children:"Previous"}),e.jsx(D,{type:"button",variant:"outline",size:"sm",disabled:u+Ct>=q,onClick:()=>S(I=>I+Ct),children:"Next"})]})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:G})]})}}function Il({projectName:t}){const s=Ie({...lr({client:Z,path:{name:t}}),staleTime:va}),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:i,providersMentioning:r,providersConfigured:o}=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 ",i," of ",o," engines",e.jsx(De,{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 ",r," of ",o," engine answers",e.jsx(De,{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(Rl,{data:n}),e.jsx(Tl,{data:n}),n.competitorGaps.length>0&&e.jsx(Bl,{data:n})]})}function Rl({data:t}){const{totalQueries:s,queriesCitedAndMentioned:n,queriesCitedOnly:a,queriesMentionedOnly:i,queriesInvisible:r}=t.summary;return e.jsxs("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4 mb-4",children:[e.jsx(Ls,{label:"Cited + mentioned",value:`${n} / ${s}`,helper:"In sources AND named in answer",tone:n>0?"positive":"neutral"}),e.jsx(Ls,{label:"Cited only",value:`${a} / ${s}`,helper:"In sources, not named in answer",tone:a>0?"positive-dim":"neutral"}),e.jsx(Ls,{label:"Mentioned only",value:`${i} / ${s}`,helper:"Named in answer, no source link",tone:i>0?"caution":"neutral"}),e.jsx(Ls,{label:"Invisible",value:`${r} / ${s}`,helper:"No engine cites or mentions",tone:r>0?"negative":"neutral"})]})}function Ls({label:t,value:s,helper:n,tone:a}){const i=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 ${i}`,children:s}),e.jsx("p",{className:"text-[11px] text-muted",children:n})]})}function Tl({data:t}){const s=l.useMemo(()=>{const n=new Set;for(const a of t.byQuery)for(const i of a.providers)n.add(i.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(Ml,{}),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(Qt,{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 i=n.providers.find(r=>r.provider===a);return e.jsx("td",{className:"text-center",children:i==null?e.jsx(wo,{className:"inline h-3.5 w-3.5 text-mono-700","aria-label":"no data"}):e.jsx(El,{provider:i})},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 Ml(){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(qt,{active:!0,tone:"cited"}),e.jsx("span",{children:"cited (in sources)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(qt,{active:!0,tone:"mentioned"}),e.jsx("span",{children:"mentioned (in answer)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(qt,{active:!1,tone:"cited"}),e.jsx(qt,{active:!1,tone:"mentioned"}),e.jsx("span",{children:"neither"})]})]})}function El({provider:t}){const s=Ol(t);return e.jsxs("span",{className:"inline-flex items-center justify-center gap-1",title:s,children:[e.jsx(qt,{active:t.cited,tone:"cited"}),e.jsx(qt,{active:t.mentioned,tone:"mentioned"})]})}function Ol(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 qt({active:t,tone:s}){if(!t)return e.jsx("span",{className:"inline-block h-2 w-2 rounded-full border border-strong/80 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 Bl({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(De,{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(Qt,{provider:s.provider})}),e.jsx("td",{className:"text-neutral",children:s.citingCompetitors.join(", ")})]},`${s.queryId}::${s.provider}`))})]})})]})}const gs="__cited__",fs="__mentioned__",Ze="__mentionShare__";function _s(t){return t.trim().toLowerCase()}function pn(t){return Math.round(t*1e3)/10}function na(t){return t.byProvider??{}}function Fl(t,s,n){const a=t.buckets.length>0,i=t.buckets.length===1;if(n==="overall"){const x=s==="cited"?gs:fs,m=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(d=>({date:d.startDate,[x]:pn(d[m])})),series:[x],hasData:a,singleBucket:i}}const r=s==="mentioned"?"mentionRate":"citationRate",o=[...new Set(t.buckets.flatMap(x=>Object.keys(na(x))))].sort();return{rows:t.buckets.map(x=>{const m={date:x.startDate},f=na(x);for(const d of o){const R=f[d];m[d]=R?pn(R[r]):null}return m}),series:o,hasData:a,singleBucket:i}}function Gl(t,s){if(t==="all")return null;const n=t==="7d"?7:t==="30d"?30:90;return s.getTime()-n*24*60*60*1e3}function Zs(t,s,n,a){const i=n?.trim();if(!i)return;let r=t.get(s);r||(r=new Map,t.set(s,r)),r.set(i,Math.max(r.get(i)??Number.NEGATIVE_INFINITY,a))}function ql(t,s,n=new Date){const a=Gl(s,n),i=new Map;for(const r of t){const o=_s(r.provider);if(!o)continue;let p=!1;for(const x of r.runHistory){if(!x.model)continue;const m=Date.parse(x.createdAt);a!==null&&(!Number.isFinite(m)||m<a)||(p=!0,Zs(i,o,x.model,Number.isFinite(m)?m:0))}if(!p&&s==="all"){for(const x of r.modelsSeen??[])Zs(i,o,x,0);Zs(i,o,r.model,Number.MAX_SAFE_INTEGER)}}return Object.fromEntries([...i.entries()].map(([r,o])=>[r,[...o.entries()].sort(([p,x],[m,f])=>f-x||p.localeCompare(m)).map(([p])=>p)]))}function _l(t){const s=t.buckets.map(a=>{const i=a.mentionShare;return{date:a.startDate,[Ze]:i?.rate==null?null:pn(i.rate)}}),n=s.map(a=>a[Ze]).filter(a=>typeof a=="number"&&Number.isFinite(a));return{rows:s,series:[Ze],hasData:n.length>0,singleBucket:n.length===1}}function Ul(t,s,n){return s==="mentionShare"?_l(t):Fl(t,s,n)}function aa(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 ia(t){const[,s,n]=t.slice(0,10).split("-");return!s||!n?t:`${s}/${n}`}function ra(t){return t>0?`+${t}`:`${t}`}function zl(t){if(t.length===0)return null;if(t.length<=2)return`Query set changed: ${t.map(n=>`${ra(n.delta)} on ${ia(n.date)}`).join(", ")}`;const s=[...t].sort((n,a)=>a.date.localeCompare(n.date))[0];return`Query set changed ${t.length} times (latest ${ra(s.delta)} on ${ia(s.date)})`}const Kl=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],Ql=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],Hl=[{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."}],Wl=2,wn=Qe[2],Vl="var(--chart-tooltip-bg)",Yl={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",local:"Local"};function gn(t){const s=_s(t);return Yl[s]??t.charAt(0).toUpperCase()+t.slice(1)}function jt(t){return Math.round(t*10)/10}function Xl(t){return t===gs||t===fs||t===Ze}function Ua(t){return t===gs?"Cited":t===fs?"Mentioned":t===Ze?"Mention share":gn(t)}function ds(t,s){return t===gs?Es.positive:t===fs?Qe[1]:t===Ze?wn:go(_s(t),s)}function Jl(t,s){for(const n of t){const a=n[s];if(typeof a=="number"&&Number.isFinite(a))return a}return null}function Zl(t){return t.map(s=>s.trim().toLowerCase()).filter(Boolean).sort().join(`
|
|
5
|
+
`)}function Ts(t){return t==="cited"?"Cited":t==="mentionShare"?"Mention share":"Mentioned"}function hs(t){return t==="cited"?"citationRate":"mentionRate"}function za(t,s){return s==="cited"?t.cited:t.mentionedCount}function Ka(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 ec(t,s){if(s===void 0)return null;const n=String(s);return t.find(a=>a.startDate===n)??null}function oa(t){return t===null?"no data":`${t}%`}function en(t){return t==null?"undefined":`${jt(t*100)}%`}function tc({active:t,label:s,payload:n,metric:a,mode:i,buckets:r}){if(!t)return null;const o=ec(r,s);if(!o)return null;if(a==="mentionShare"){const x=o.mentionShare.projectMentionSnapshots,m=o.mentionShare.competitorMentionSnapshots,f=x+m,d=o.mentionShare.rate==null?null:jt(o.mentionShare.rate*100);return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:mt(o.startDate)}),e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch trend-tooltip-swatch-ring",style:{borderColor:wn},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:"Mention share"}),e.jsx("span",{className:"trend-tooltip-value",children:oa(d)})]}),f>0?e.jsxs("p",{className:"trend-tooltip-detail",children:["You ",x," / ",f," brand mentions. Competitors ",m,"."]}):e.jsx("p",{className:"trend-tooltip-detail",children:"No project or competitor brand mentions in this bucket."})]})}const p=i==="byProvider"?(n??[]).filter(x=>x.dataKey!==void 0):[{dataKey:a==="cited"?gs:fs,value:jt(o[hs(a)]*100)}];return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:mt(o.startDate)}),p.map((x,m)=>{const f=String(x.dataKey??x.name??""),d=i==="byProvider"?Ka(o,f,a):null,R=d?.count??za(o,a),h=d?.total??o.total,A=typeof x.value=="number"?x.value:jt(d?d.rate*100:o[hs(a)]*100),w=x.color??ds(f,m);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:w},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:Ua(f)}),e.jsx("span",{className:"trend-tooltip-value",children:oa(A)})]}),e.jsxs("p",{className:"trend-tooltip-detail",children:[R," / ",h," snapshots, ",a==="cited"?"source links":"answer text"]})]},`${f}-${m}`)})]})}function sc({buckets:t,metric:s,mode:n,series:a}){return e.jsxs("table",{className:"sr-only",children:[e.jsxs("caption",{children:[Ts(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(i=>{let r;if(s==="mentionShare"){const o=i.mentionShare.projectMentionSnapshots,p=i.mentionShare.competitorMentionSnapshots,x=o+p;r=x>0?`${en(i.mentionShare.rate)} mention share, ${o} of ${x} brand mentions were you`:"mention share undefined, no project or competitor brand mentions"}else n==="byProvider"?r=a.map(o=>{const p=Ka(i,o,s);return p?`${gn(o)} ${en(p.rate)} ${Ts(s).toLowerCase()}, ${p.count} of ${p.total} snapshots`:`${gn(o)} no data`}).join("; "):r=`${en(i[hs(s)])} ${Ts(s).toLowerCase()}, ${za(i,s)} of ${i.total} snapshots`;return e.jsxs("tr",{children:[e.jsx("th",{scope:"row",children:mt(i.startDate)}),e.jsx("td",{children:r})]},i.startDate)})})]})}function tn({options:t,value:s,onChange:n,ariaLabel:a,className:i}){const r=l.useId();return e.jsx("div",{role:"group","aria-label":a,className:`segmented ${i??""}`,children:t.map(o=>{const p=s===o.value,x=o.description?`${r}-${o.value}-description`:void 0;return e.jsxs(l.Fragment,{children:[e.jsx("button",{type:"button","aria-pressed":p,"aria-describedby":x,className:`segmented-option ${p?"segmented-option-active":""}`,onClick:()=>n(o.value),children:o.label}),o.description&&e.jsx("span",{id:x,className:"sr-only",children:o.description})]},o.value)})})}function nc({projectName:t,competitorDomains:s=[],visibilityEvidence:n=[]}){const[a,i]=l.useState("all"),[r,o]=l.useState("mentioned"),[p,x]=l.useState("byProvider"),m=l.useMemo(()=>Zl(s),[s]),f=Ie({queryKey:["analytics-metrics",t,a,m],queryFn:()=>cr(t,a),staleTime:va}),d=f.data??null,R=f.error,h=r==="mentionShare"?"overall":p,A=l.useMemo(()=>d?Ul(d,r,h):null,[d,r,h]),w=l.useMemo(()=>new Date,[n,a]),C=l.useMemo(()=>ql(n,a,w),[n,a,w]),P=r!=="mentionShare"&&h==="byProvider",F=Ts(r),M=r==="cited"?Es.positive:r==="mentionShare"?wn:Qe[1],_=P?ze.textDim:M,u=d?.buckets??[],S=r==="mentionShare"?A?aa(A.rows,Ze):null:u.length>0?jt(u[u.length-1][hs(r)]*100):null,Q=r==="mentionShare"?A?Jl(A.rows,Ze):null:u.length>0?jt(u[0][hs(r)]*100):null,v=r==="mentionShare"?A?.rows.filter(O=>typeof O[Ze]=="number").length??0:u.length,U=S!==null&&Q!==null&&v>1?jt(S-Q):null,L=s.length,N=e.jsxs(e.Fragment,{children:[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(De,{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."})]})]}),S!==null&&e.jsxs("div",{className:"visibility-trend-current",children:[e.jsx("span",{className:"visibility-trend-current-dot",style:{backgroundColor:_},"aria-hidden":"true"}),e.jsx("span",{className:"visibility-trend-current-label",children:F}),P&&e.jsx("span",{className:"visibility-trend-current-qualifier",children:"avg"}),e.jsxs("span",{className:"visibility-trend-current-value",children:[S,"%"]}),U!==null&&e.jsxs("span",{className:`visibility-trend-current-delta ${U>0?"text-positive-400":U<0?"text-negative-400":"text-muted"}`,children:[U>0?"+":"",U.toFixed(1)," pts"]})]})]}),e.jsxs("div",{className:"visibility-trend-controls",children:[e.jsx(tn,{options:Hl,value:r,onChange:o,ariaLabel:"Metric",className:"visibility-trend-metric-control"}),r!=="mentionShare"&&e.jsx(tn,{options:Ql,value:p,onChange:x,ariaLabel:"Series"}),e.jsx(tn,{options:Kl,value:a,onChange:i,ariaLabel:"Time window",className:"sm:ml-auto"})]})]});let E;if(R)E=e.jsx("p",{className:"text-sm text-negative-400",children:R instanceof Error?R.message:String(R)});else if(f.isLoading&&!d)E=e.jsx("div",{className:"visibility-trend-chart animate-pulse rounded-lg bg-bg-elevated/40","aria-hidden":"true"});else if(r==="mentionShare"&&L===0)E=e.jsx("p",{className:"text-sm text-secondary",children:"Add tracked competitors to measure mention share over time."});else if(!d||!A)E=null;else{const{rows:O,series:se,hasData:he,singleBucket:ye}=A,pe=zl(d.queryChanges);if(!he)E=e.jsx("p",{className:"text-sm text-secondary",children:r==="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(P&&se.length===0)E=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 ge=`${F} rate across ${O.length} ${O.length===1?"sweep":"sweeps"}. Latest ${S}%${U!==null?`, ${U>=0?"up":"down"} ${Math.abs(U).toFixed(1)} points over the period`:""}.`;E=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"sr-only",children:ge}),e.jsx(sc,{buckets:u,metric:r,mode:h,series:se}),P&&se.length>0&&e.jsx("ul",{className:"trend-legend","aria-label":"Engines",children:se.map((Y,de)=>{const fe=aa(O,Y),b=C[_s(Y)]??[],q=b.slice(0,Wl),X=b.length-q.length;return e.jsxs("li",{className:"trend-legend-item",children:[e.jsx("span",{className:"trend-legend-swatch",style:{backgroundColor:ds(Y,de)},"aria-hidden":"true"}),e.jsxs("span",{className:"trend-legend-label",children:[e.jsx("span",{className:"trend-legend-name",children:Ua(Y)}),q.map(le=>e.jsxs("span",{className:"trend-legend-model",children:[e.jsx("span",{"aria-hidden":"true",children:"· "}),le]},le)),X>0&&e.jsxs("span",{className:"trend-legend-model-more",children:["+",X]})]}),fe!==null&&e.jsxs("span",{className:"trend-legend-value",children:[fe,"%"]})]},Y)})}),e.jsx("div",{className:"visibility-trend-chart",role:"img","aria-label":`${F} trend chart over ${O.length} ${O.length===1?"bucket":"buckets"}`,children:e.jsx(Wt,{width:"100%",height:"100%",children:e.jsxs(Vt,{data:O,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(yn,{stroke:jn,vertical:!1}),e.jsx(Yt,{dataKey:"date",tick:et,tickLine:!1,axisLine:{stroke:ut},tickFormatter:Ht,minTickGap:24}),e.jsx(Xt,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:Y=>`${Y}%`,tick:et,tickLine:!1,axisLine:!1,width:40}),e.jsx(Jt,{cursor:{stroke:ut,strokeWidth:1},content:e.jsx(tc,{metric:r,mode:h,buckets:u})}),se.map((Y,de)=>e.jsx(vn,{type:"monotone",dataKey:Y,name:Y,stroke:ds(Y,de),strokeDasharray:Y===Ze?"5 4":void 0,strokeWidth:Xl(Y)?2.5:2,dot:Y===Ze?{r:2.75,fill:"var(--chart-tooltip-bg)",stroke:ds(Y,de),strokeWidth:1.5}:{r:2.5,fill:ds(Y,de),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:Vl},connectNulls:Y!==Ze,isAnimationActive:!1},Y))]})})}),ye&&e.jsx("p",{className:"visibility-trend-note",children:r==="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."}),pe&&e.jsx("p",{className:"visibility-trend-note",children:pe})]})}}return e.jsxs("section",{className:"visibility-trend",children:[N,E]})}const fn=new Set(["queued","seeding","probing"]);function ac({projectName:t}){const s=vt(),[n,a]=l.useState(null),[i,r]=l.useState(""),[o,p]=l.useState("100"),x=Ie({...dr({client:Z,path:{name:t},query:{limit:"10"}}),refetchInterval:u=>u.state.data?.some(Q=>fn.has(Q.status))?3e3:!1}),m=x.data??[];l.useEffect(()=>{!n&&m[0]&&a(m[0].id)},[n,m]);const f=m.find(u=>u.id===n)??null,d=Ie({...ur({client:Z,path:{name:t,id:n??""}}),enabled:!!n,refetchInterval:f&&fn.has(f.status)?3e3:!1}),R=d.data??null,h=Ie({...mr({client:Z,path:{name:t,id:n??""}}),enabled:!!(n&&f?.status==="completed")}),A=ms({mutationFn:()=>{const u={},S=i.trim();S&&(u.icpDescription=S);const Q=Number.parseInt(o,10);return Number.isFinite(Q)&&Q>0&&(u.maxProbes=Q),xr(t,u)},onSuccess:async u=>{a(u.sessionId),r(""),await ca(s,t,u.sessionId),K({title:"Discovery started",detail:`Run ${sn(u.sessionId)} is testing questions your customers might ask.`,tone:"neutral",dedupeKey:`discovery:start:${u.sessionId}`,dedupeMode:"replace"})},onError:u=>{K({title:"Discovery failed to start",detail:u instanceof Error?u.message:"Could not start discovery.",tone:"negative"})}}),w=ms({mutationFn:u=>{if(!n)throw new Error("Select a completed discovery session first.");return hr(t,n,u)},onSuccess:async u=>{await ca(s,t,u.sessionId),s.invalidateQueries({queryKey:Na({client:Z})}),s.invalidateQueries({predicate:S=>Array.isArray(S.queryKey)&&S.queryKey[0]==="projects"&&S.queryKey.length>1}),K({title:"Queries added",detail:lc(u),tone:"positive",dedupeKey:`discovery:promote:${u.sessionId}`,dedupeMode:"replace"})},onError:u=>{K({title:"Could not add queries",detail:u instanceof Error?u.message:"Could not add queries from this run.",tone:"negative"})}}),C=R??f,P=h.data??null,F=(P?.queriesByBucket.cited.length??0)+(P?.queriesByBucket.aspirational.length??0),M=l.useMemo(()=>(R?.probes??[]).slice(0,30),[R?.probes]);async function _(){try{const u=await x.refetch();if(u.error)throw u.error;const S=u.data?.length??0;K({title:"Discovery sessions refreshed",detail:`${S} recent session${S===1?"":"s"} loaded.`,tone:"positive",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}catch(u){K({title:"Discovery refresh failed",detail:u instanceof Error?u.message:"Could not reload discovery sessions.",tone:"negative",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}}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:"Discovery"}),e.jsx("h2",{children:"Find new queries to track"}),e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-muted",children:T()?"Generated questions your ideal customers would ask an AI engine, with a check of which ones already cite your site.":"Describe your ideal customer and Canonry generates the questions they would ask an AI engine, checks which ones already cite your site, then lets you add the promising ones to your tracked queries."})]}),e.jsxs(D,{type:"button",variant:"outline",size:"sm",disabled:x.isFetching,onClick:()=>{_()},children:[e.jsx(dt,{className:`size-3.5 ${x.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(W,{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(oe,{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-xs text-muted",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:i,onChange:u=>r(u.target.value)})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-xs text-muted",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:o,onChange:u=>p(u.target.value)}),e.jsx("span",{className:"mt-1 block text-[11px] text-faint",children:"More questions means broader coverage but a longer run. 100 is a good default."})]}),!T()&&e.jsxs(D,{type:"button",size:"sm",disabled:A.isPending,onClick:()=>A.mutate(),children:[e.jsx(Ut,{size:14}),A.isPending?"Starting…":"Find queries"]})]})]}),e.jsxs(W,{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"})]}),x.isFetching&&e.jsx(oe,{tone:"neutral",children:"Loading"})]}),m.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No discovery runs yet. Describe your customer above to start your first one."}):e.jsx("div",{className:"space-y-2",children:m.map(u=>e.jsxs("button",{type:"button",className:`w-full rounded-md border px-3 py-2 text-left transition-colors ${n===u.id?"border-mono-600 bg-bg-elevated/70":"border-default bg-bg/40 hover:border-strong hover:bg-bg-elevated/40"}`,onClick:()=>a(u.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:sn(u.id)}),e.jsx(oe,{tone:la(u.status),children:u.status})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-[11px] text-muted",children:[e.jsxs("span",{children:["Cited ",u.citedCount??0]}),e.jsxs("span",{children:["Opportunity ",u.aspirationalCount??0]}),e.jsxs("span",{children:["Low value ",u.wastedCount??0]})]})]},u.id))})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(W,{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:C?sn(C.id):"No run selected"})]}),C&&e.jsx(oe,{tone:la(C.status),children:C.status})]}),C?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(ft,{label:"Questions tested",value:C.probeCount??0}),e.jsx(ft,{label:"Already cited",value:C.citedCount??0,tone:"positive"}),e.jsx(ft,{label:"Opportunities",value:C.aspirationalCount??0,tone:"caution"}),e.jsx(ft,{label:"Low value",value:C.wastedCount??0,tone:"negative"})]}),C.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:C.error}),C.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:C.warning}),C.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:C.icpDescription})]}),C.competitorMap.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-secondary",children:"Sites that keep getting cited"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:C.competitorMap.slice(0,8).map(u=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[u.domain," ",e.jsx("span",{className:"text-muted",children:u.hits})]},u.domain))})]})]}):e.jsx("p",{className:"text-sm text-muted",children:"Start a run above, or pick one from Recent runs to see its progress."})]}),C?.status==="completed"&&e.jsxs(W,{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:"Add queries to your project"})]}),!T()&&e.jsxs(D,{type:"button",size:"sm",disabled:w.isPending||F===0,onClick:()=>w.mutate(void 0),children:[e.jsx(Pa,{size:14}),w.isPending?"Adding…":"Add recommended queries"]})]}),h.isLoading?e.jsx("p",{className:"text-sm text-muted",children:"Loading recommendations…"}):P?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(ft,{label:"Queries to add",value:F,tone:"positive"}),e.jsx(ft,{label:"Already cited",value:P.queriesByBucket.cited.length,tone:"positive"}),e.jsx(ft,{label:"Opportunities",value:P.queriesByBucket.aspirational.length,tone:"caution"}),e.jsx(ft,{label:"Low value (skipped)",value:P.queriesByBucket["wasted-surface"].length,tone:"negative"})]}),e.jsx("p",{className:"text-xs leading-5 text-muted",children:"Adding queries starts tracking the “already cited” and “opportunity” questions, plus any competitor sites that kept showing up. “Low value” questions are listed below for reference only and are not added."}),P.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:P.suggestedCompetitors.map(u=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[u.domain," ",e.jsx("span",{className:"text-muted",children:u.hits})]},u.domain))})]})]}):e.jsx("p",{className:"text-sm text-muted",children:"No recommendations available for this run."})]}),e.jsxs(W,{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"})]}),d.isFetching&&e.jsx(oe,{tone:"neutral",children:"Loading"})]}),M.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:M.map(u=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:u.query}),e.jsx("td",{children:e.jsx(oe,{tone:ic(u.bucket),children:oc(u.bucket)})}),e.jsx("td",{className:"text-secondary",children:u.citedDomains.length>0?u.citedDomains.slice(0,3).join(", "):"-"})]},u.id))})]})})]})]})]})]})}function ft({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 la(t){return t==="completed"?"positive":t==="failed"?"negative":fn.has(t)?"caution":"neutral"}function ic(t){return t==="cited"?"positive":t==="aspirational"?"caution":t==="wasted-surface"?"negative":"neutral"}const rc={cited:"Already cited",aspirational:"Opportunity","wasted-surface":"Low value"};function oc(t){return t?rc[t]:"Not classified"}function sn(t){return t.length>8?t.slice(0,8):t}function lc(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 ca(t,s,n){await Promise.all([t.invalidateQueries({predicate:a=>{const i=a.queryKey[0];return typeof i?._id=="string"&&i._id.startsWith("getApiV1ProjectsByNameDiscover")}}),t.invalidateQueries({queryKey:wa({client:Z})})])}const cc=100,nn=12;function an(t){return t>=70?"positive":t>=40?"caution":"negative"}function rn(t){return t>=70?"text-positive-400":t>=40?"text-caution-400":"text-negative-400"}function dc(t){return t==="pass"?"positive":t==="partial"?"caution":"negative"}function Is(t){return t>=70?"Pass":t>=40?"Partial":"Fail"}function uc({projectName:t}){const s=vt(),[n,a]=l.useState(!1),[i,r]=l.useState(null),[o,p]=l.useState(!1),x=Ie(pr({client:Z,path:{name:t}})),m=Ie(gr({client:Z,path:{name:t},query:{limit:30}})),f=Ie(fr({client:Z,path:{name:t},query:{limit:cc,sort:"score-asc"}})),d=ms({mutationFn:()=>br(t),onSuccess:()=>{K({title:"Technical audit started",detail:"The audit re-reads your sitemap in the background. Refresh in a minute to see the score.",tone:"positive"}),s.invalidateQueries({queryKey:wa({client:Z})})},onError:v=>{K({title:"Could not start technical audit",detail:v instanceof Error?v.message:"Failed to start technical audit.",tone:"negative"})}}),R=async()=>{p(!0);try{const[v]=await Promise.all([x.refetch(),m.refetch(),f.refetch()]);if(v.error)throw v.error;K({title:"Technical AEO refreshed",detail:v.data?.hasData?`Latest score is ${v.data.aggregateScore}/100 from ${v.data.pagesAudited} audited page${v.data.pagesAudited===1?"":"s"}.`:"No audit data yet. Run an audit to crawl the sitemap.",tone:v.data?.hasData?"positive":"caution",dedupeKey:`technical-aeo:refresh:${t}`,dedupeMode:"replace"})}catch(v){K({title:"Technical AEO refresh failed",detail:v instanceof Error?v.message:"Could not reload technical audit data.",tone:"negative",dedupeKey:`technical-aeo:refresh:${t}`,dedupeMode:"replace"})}finally{p(!1)}},h=x.data;if(x.isLoading)return e.jsx("p",{className:"supporting-copy mt-6",children:"Loading technical audit…"});if(!h||!h.hasData)return e.jsxs(W,{className:"surface-card mt-6 p-8 text-center",children:[e.jsx(ko,{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."}),!T()&&e.jsx("div",{className:"mt-5 flex items-center justify-center gap-3",children:e.jsxs(D,{type:"button",onClick:()=>d.mutate(),disabled:d.isPending,children:[e.jsx(Ut,{className:"mr-1.5 h-4 w-4","aria-hidden":"true"}),d.isPending?"Starting…":"Run first audit"]})}),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 A=h.deltaScore==null?null:`${h.deltaScore>=0?"+":""}${h.deltaScore} vs previous`,w=h.trend==="up"?"positive":h.trend==="down"?"negative":"neutral",C=m.data?.points.map(v=>({date:v.auditedAt,score:v.aggregateScore}))??[],P=f.data?.pages??[],F=P.filter(v=>v.status==="success"),M=h.pagesErrored>0,_=n&&M,u=_?P.filter(v=>v.status==="error"):P,S=h.pagesAudited>P.length;function Q(v){const U=[];for(const L of F){const N=L.factors.find(E=>E.id===v);N&&N.score<70&&U.push({url:L.url,score:N.score})}return U.sort((L,N)=>L.score-N.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:"Technical AEO"}),e.jsxs("div",{className:"mt-1 flex items-baseline gap-3",children:[e.jsx("span",{className:`text-4xl font-semibold tabular-nums ${rn(h.aggregateScore)}`,children:h.aggregateScore}),e.jsx("span",{className:"text-lg text-muted",children:"/ 100"}),e.jsx(oe,{tone:an(h.aggregateScore),children:Is(h.aggregateScore)}),A?e.jsx(oe,{tone:w,children:A}):null]}),e.jsxs("p",{className:"supporting-copy mt-2 tabular-nums",children:[h.pagesDiscovered," URL",h.pagesDiscovered===1?"":"s"," in sitemap · ",h.pagesAudited," audited · ",h.pagesSkipped," skipped · ",h.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:h.sitemapUrl??"#",target:"_blank",rel:"noreferrer",className:"max-w-[22rem] truncate text-secondary underline decoration-mono-700 underline-offset-2 hover:text-strong",children:h.sitemapUrl}),e.jsx(De,{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>`."})]}),h.auditedAt?e.jsxs("p",{className:"mt-0.5 text-xs text-faint",children:["Audited ",new Date(h.auditedAt).toLocaleString()]}):null]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(D,{type:"button",variant:"outline",size:"sm",onClick:()=>{R()},disabled:o,children:[e.jsx(dt,{className:`h-3.5 w-3.5 ${o?"animate-spin":""}`,"aria-hidden":"true"}),o?"Refreshing…":"Refresh"]}),!T()&&e.jsxs(D,{type:"button",size:"sm",onClick:()=>d.mutate(),disabled:d.isPending,children:[e.jsx(Ut,{className:"mr-1.5 h-4 w-4","aria-hidden":"true"}),d.isPending?"Starting…":"Re-run audit"]})]})]}),C.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.jsx("div",{className:"mt-3 h-56",children:e.jsx(Wt,{width:"100%",height:"100%",children:e.jsxs(Vt,{data:C,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(yn,{stroke:jn,vertical:!1}),e.jsx(Yt,{dataKey:"date",tick:et,tickLine:!1,axisLine:{stroke:ut},tickFormatter:Ht,minTickGap:24}),e.jsx(Xt,{domain:[0,100],ticks:[0,25,50,75,100],tick:et,tickLine:!1,axisLine:!1,width:32}),e.jsx(Jt,{...Dt,cursor:{stroke:ut,strokeWidth:1},labelFormatter:mt,formatter:v=>[`${v}/100`,"Site score"]}),e.jsx(vn,{type:"monotone",dataKey:"score",name:"score",stroke:"#34d399",strokeWidth:2.5,dot:{r:2.5,fill:"#34d399",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(De,{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:h.factors.map(v=>{const U=i===v.id,L=h.crossCuttingIssues.find(O=>O.factorId===v.id),N=U?Q(v.id):[],E=v.pagesPartial+v.pagesFailing;return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:U?"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":U,onClick:()=>r(U?null:v.id),children:[U?e.jsx(qs,{className:"h-3.5 w-3.5 shrink-0 text-muted","aria-hidden":"true"}):e.jsx(Gs,{className:"h-3.5 w-3.5 shrink-0 text-muted","aria-hidden":"true"}),v.name]})}),e.jsxs("td",{className:"text-right tabular-nums text-muted",children:[v.weight,"%"]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:v.avgScore}),e.jsx("td",{children:e.jsx(oe,{tone:dc(v.status),children:Is(v.avgScore)})}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[e.jsx("span",{className:"text-positive-400",children:v.pagesPassing})," / ",e.jsx("span",{className:"text-caution-400",children:v.pagesPartial})," / ",e.jsx("span",{className:"text-negative-400",children:v.pagesFailing})]})]}),U?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:[L&&L.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:L.topRecommendations.map((O,se)=>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:O})]},se))})]}):E===0?e.jsx("p",{className:"text-sm text-muted",children:"Every audited page passes this factor."}):null,E>0?e.jsxs("div",{children:[e.jsxs("p",{className:"eyebrow eyebrow-soft mb-1.5 text-muted",children:["Pages below pass (",E,")"]}),e.jsx("ul",{className:"space-y-1",children:N.slice(0,nn).map(O=>e.jsxs("li",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:`w-8 shrink-0 text-right tabular-nums ${rn(O.score)}`,children:O.score}),e.jsx("a",{href:O.url,target:"_blank",rel:"noreferrer",className:"truncate text-neutral hover:text-heading",title:O.url,children:O.url})]},O.url))}),N.length>nn?e.jsxs("p",{className:"mt-1 text-xs text-faint",children:["+ ",N.length-nn," more below pass"]}):null,S?e.jsxs("p",{className:"mt-1 text-xs text-faint",children:["Showing the worst ",P.length," audited pages."]}):null]}):null]})})}):null]},v.id)})})]})})]}),h.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(De,{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:h.crossCuttingIssues.map(v=>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:v.factorName}),e.jsx(oe,{tone:an(v.avgScore),children:Is(v.avgScore)}),e.jsxs("span",{className:"text-xs tabular-nums text-muted",children:["avg ",v.avgScore," · affects ",v.affectedPages," of ",v.totalPages," pages (",v.affectedPct,"%)"]})]}),v.topRecommendations.length>0?e.jsx("ul",{className:"mt-2 space-y-1",children:v.topRecommendations.map((U,L)=>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:U})]},L))}):null]},v.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"})]}),M?e.jsxs("div",{className:"inline-flex items-center gap-1 rounded-full border border-default p-0.5",role:"group","aria-label":"Filter pages",children:[e.jsxs("button",{type:"button",onClick:()=>a(!1),"aria-pressed":!_,className:`rounded-full px-3 py-1 text-xs font-medium tabular-nums transition-colors ${_?"text-muted hover:text-neutral":"bg-mono-800 text-heading"}`,children:["All ",h.pagesAudited]}),e.jsxs("button",{type:"button",onClick:()=>a(!0),"aria-pressed":_,className:`rounded-full px-3 py-1 text-xs font-medium tabular-nums transition-colors ${_?"bg-negative-500/15 text-negative":"text-muted hover:text-neutral"}`,children:["Errors ",h.pagesErrored]})]}):null]}),u.length===0?e.jsx("p",{className:"supporting-copy mt-3",children:"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:u.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-right tabular-nums",children:v.status==="error"?e.jsxs("span",{className:"inline-flex items-center gap-1 text-negative-400",children:[e.jsx(jr,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"err"]}):e.jsx("span",{className:rn(v.overallScore),children:v.overallScore})}),e.jsx("td",{children:v.status==="error"?e.jsx(oe,{tone:"negative",children:"Error"}):e.jsx(oe,{tone:an(v.overallScore),children:Is(v.overallScore)})}),e.jsx("td",{className:"w-full max-w-0",children:e.jsx("a",{href:v.url,target:"_blank",rel:"noreferrer",className:"block truncate text-neutral hover:text-heading",title:v.status==="error"?v.error??v.url:v.url,children:v.url})})]},v.url))})]})}),S?e.jsxs("p",{className:"mt-2 text-xs text-faint",children:["Showing the worst ",P.length," of ",h.pagesAudited," audited pages."]}):null]})]})]})}const mc={critical:"negative",high:"negative",medium:"caution",low:"neutral"};function Re(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 xc(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 hc(t){const s=[t.city,t.region,t.country].filter(Boolean).join(", ");return s?`${t.label} (${s})`:t.label}function pc({projectName:t}){const[s,n]=l.useState(!1),[a,i]=l.useState(null),[r,o]=l.useState(yr),p=Ie({...vr({client:Z,path:{name:t},query:{period:r}}),placeholderData:ai});async function x(){n(!0),i(null);try{await wr(t,"client",r)}catch(f){const d=f instanceof un||f instanceof Error?f.message:"Download failed";i(d)}finally{n(!1)}}if(p.isLoading)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading report…"});if(p.error){const f=p.error instanceof Error?p.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:f})})}const m=p.data;return m?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:m.meta.project.displayName}),e.jsxs("p",{className:"page-subtitle",children:[m.meta.project.canonicalDomain," · ",m.meta.project.country," / ",m.meta.project.language.toUpperCase(),m.meta.location?` · Location: ${hc(m.meta.location)}`:" · No location set"," · ","Last ",m.meta.periodDays," days"," · ","Generated ",xc(m.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(gc,{period:r,onChange:o}),e.jsxs(D,{variant:"secondary",size:"sm",onClick:ae(x),disabled:s,children:[e.jsx(Gt,{className:"size-4"}),s?"Preparing…":"Download report HTML"]})]})]}),e.jsx(wc,{report:m}),e.jsx(Pc,{report:m,audience:"client"}),e.jsx(jc,{report:m}),e.jsx(Cc,{report:m,audience:"client",projectName:t}),e.jsx(Ac,{report:m})]}):null}function gc({period:t,onChange:s}){return e.jsx("div",{className:"inline-flex items-center gap-0.5 rounded-full border border-default bg-bg-elevated/40 p-0.5",role:"group","aria-label":"Report time period",children:Nr.map(n=>{const a=n===t;return e.jsxs("button",{type:"button",onClick:()=>s(n),"aria-pressed":a,className:`rounded-full px-3 py-1 text-xs font-medium transition-colors ${a?"bg-mono-200 text-mono-900":"text-secondary hover:text-heading"}`,children:[n,"d"]},n)})})}const da="AI Visibility — Server-Side",ua="AI engine attention",fc=t=>`What AI engines actually do in your server logs over the last ${t} days — the other half of citations.`,bc="Live telemetry from your server logs.";function jc({report:t}){const s=t.serverActivity;if(!s)return null;if(!s.hasData)return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(ps,{eyebrow:ua,title:da,subtitle:bc}),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:Do(s.verifiedCrawlerHits.current+s.unverifiedCrawlerHits.current,s.verifiedCrawlerHits.prior+s.unverifiedCrawlerHits.prior)},a=t.meta.periodDays,i=`vs prior ${a} days`,r=Vs(n,"requests",i),o=`${Re(s.verifiedCrawlerHits.current)} verified · ${Re(s.unverifiedCrawlerHits.current)} unverified${r?` · ${r}`:""}`,p=Vs(s.aiUserFetchHits,"requests",i),m=[Vs(s.referralArrivals,"sessions",i),s.referralArrivalsClassSummary].filter(Boolean).join(" · "),f=s.byOperator.filter(d=>d.verifiedHits>0||d.unverifiedHits>0||d.userFetchHits>0||d.referralArrivals>0).slice(0,5);return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(ps,{eyebrow:ua,title:da,subtitle:fc(a)}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(cn,{label:"AI bot requests observed",value:Re(n.current),subtitle:o}),e.jsx(cn,{label:"AI user-fetch requests",value:Re(s.aiUserFetchHits.current),subtitle:p||"ChatGPT-User, Perplexity-User, MistralAI-User"}),e.jsx(cn,{label:"AI referral sessions",value:Re(s.referralArrivals.current),subtitle:m})]}),f.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:f.map(d=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:d.operator}),e.jsx("td",{children:Re(d.verifiedHits+d.unverifiedHits)}),e.jsx("td",{children:Re(d.userFetchHits)}),e.jsx("td",{children:Re(d.referralArrivals)})]},d.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 yc(t,s){return t.audience==="both"||t.audience===s}const vc={gemini:"Gemini",openai:"ChatGPT",claude:"Claude",perplexity:"Perplexity",local:"Local model","cdp:chatgpt":"ChatGPT (browser)"};function Bs(t){return vc[t]??t.charAt(0).toUpperCase()+t.slice(1)}function Nc(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 wc({report:t}){const s=t.executiveSummary,n=t.citationScorecard,a=s.totalQueryCount,i=a>0?`${s.mentionRate}%`:"—",r=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.",o=Nc(t.whatsChanged.mentionRate),p=n.providers.length>0?n.providers.map(Bs).join(", "):`${Re(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:i}),e.jsx("p",{className:"mt-3 max-w-2xl text-base text-neutral sm:text-lg",children:r}),o&&e.jsxs("p",{className:`mt-3 text-sm font-medium ${o.tone==="positive"?"text-positive-400":o.tone==="negative"?"text-negative-400":"text-secondary"}`,children:[e.jsx("span",{className:"mr-1",children:o.arrow}),o.text]})]}),e.jsxs("div",{className:"mt-5 grid gap-4 sm:grid-cols-3",children:[e.jsx(on,{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(on,{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(on,{label:"AI tools tested",value:Re(s.providerCount),subtitle:p})]}),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((x,m)=>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(m+1).padStart(2,"0")}),e.jsxs("span",{children:['"',x,'"']})]},m))})]}),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(x=>e.jsxs("div",{className:"grid grid-cols-[120px_1fr_120px] items-center gap-3",children:[e.jsx("span",{className:"text-sm text-neutral",children:Bs(x.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(x.mentionRate,1.5)}%`}})}),e.jsxs("span",{className:"text-right text-sm font-semibold text-heading",children:[x.mentionRate,"% ",e.jsxs("span",{className:"font-normal text-muted",children:["(",x.mentionedCount,"/",x.totalCount,")"]})]})]},x.provider))})]}),t.clientSummary.confidenceNotes.length>0&&e.jsx("div",{className:"mt-4 grid gap-2",children:t.clientSummary.confidenceNotes.map((x,m)=>e.jsx("div",{className:"rounded-lg border border-default bg-surface px-3 py-2 text-xs text-secondary",children:x},m))})]})}function on({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 Sc(t){switch(t){case"immediate":return"Do now";case"short-term":return"This month";case"medium-term":return"Next quarter"}}function kc(t){switch(t){case"high":return"Strong evidence";case"medium":return"Some evidence";case"low":return"Worth trying"}}function Cc({report:t,audience:s,projectName:n}){const a=s==="client"?t.clientSummary.actionItems:t.agencyDiagnostics.priorities.length>0?t.agencyDiagnostics.priorities:t.actionPlan.filter(d=>yc(d,s)),i=Mo(t,a),r=s==="client",o=Sr(),[p,x]=l.useState(new Set),m=p.size>0?i.filter(d=>!d.targetRef||!p.has(d.targetRef)):i,f=d=>{if(!d.targetRef)return;const R=d.targetRef;x(h=>new Set(h).add(R)),o.mutate({projectName:n,body:{targetRef:R}},{onSuccess:()=>{K({tone:"positive",title:`Dismissed "${d.title}"`,detail:"Will not appear in future reports until un-dismissed."})},onError:h=>{K({tone:"negative",title:`Couldn't dismiss "${d.title}"`,detail:String(h)}),x(A=>{const w=new Set(A);return w.delete(R),w})}})};return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(ps,{eyebrow:r?"Action plan":"Agency actions",title:r?"What to do next":"Agency Action Plan",subtitle:r?"Approve these in order. They are sorted by what will move the needle fastest.":"The highest-leverage work, sorted by urgency and evidence strength."}),m.length===0?e.jsx(Cn,{message:"No recommendations yet — run an AI check to populate this."}):e.jsx("div",{className:"grid gap-3 lg:grid-cols-2",children:m.map((d,R)=>{const h=d.evidence.length>0?d.evidence:d.why,A=d.why.length>0||d.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:R+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(oe,{tone:Cr(d),children:r?Sc(d.horizon):kr(d.horizon)}),!r&&e.jsx(oe,{tone:"neutral",children:Ar(d.category)}),e.jsx(oe,{tone:"neutral",children:r?kc(d.confidence):`${$r(d.confidence)} confidence`})]}),e.jsx("p",{className:"text-sm font-medium text-heading",children:d.title})]})]}),e.jsx("p",{className:"mt-3 text-sm text-secondary",children:d.action}),e.jsx(Dc,{items:h,limit:3,className:"mt-3"}),A&&e.jsxs("details",{className:"mt-3 text-xs text-secondary",children:[e.jsx("summary",{className:"cursor-pointer text-muted hover:text-neutral",children:r?"See the data behind this":"Evidence details"}),d.why.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"eyebrow-soft mb-1",children:r?"Why this matters":"Why"}),e.jsx("ul",{className:"list-disc space-y-1 pl-4",children:d.why.map((w,C)=>e.jsx("li",{children:w},C))})]}),d.evidence.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"eyebrow-soft mb-1",children:r?"What we saw":"Evidence"}),e.jsx("ul",{className:"list-disc space-y-1 pl-4",children:d.evidence.map((w,C)=>e.jsx("li",{children:w},C))})]})]}),e.jsxs("p",{className:"mt-3 border-t border-default pt-3 text-xs text-neutral",children:[e.jsx("span",{className:"font-medium",children:r?"What success looks like:":"Win condition:"})," ",d.successMetric]}),d.targetRef&&!T()&&e.jsx("div",{className:"mt-3 flex justify-end",children:e.jsx("button",{type:"button",onClick:()=>f(d),className:"rounded-md border border-strong/60 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"})})]},`${d.priority}-${d.title}`)})})]})}function ma({label:t,value:s,displayValue:n,max:a,barClass:i}){const r=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 ${i}`,style:{width:`${r}%`}})})]}),e.jsx("span",{className:"whitespace-nowrap text-sm font-semibold text-heading",children:n})]})}function Ac({report:t}){const s=t.aiSourceOrigin.topDomains.slice(0,5),n=t.gsc,a=t.indexingHealth,i=Eo(t).slice(0,5),r=s.length>0?Math.max(...s.map(x=>x.count)):0,o=n?Math.max(...n.topQueries.slice(0,5).map(x=>x.impressions),1):0,p=s.length>0||n!==null||a!==null||i.length>0;return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(ps,{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."}),p?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(x=>e.jsx(ma,{label:x.domain+(x.isCompetitor?" (competitor)":""),value:x.count,displayValue:`${Re(x.count)}×`,max:r,barClass:"bg-mono-400/70"},x.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:[Re(a.indexed)," of ",Re(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:Re(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:Re(n.totalImpressions)})," Google searches and got ",e.jsx("span",{className:"font-semibold text-strong",children:Re(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(x=>e.jsx(ma,{label:x.query,value:x.impressions,displayValue:`${Re(x.impressions)} ${x.impressions===1?"search":"searches"}`,max:o,barClass:"bg-info-500/70"},x.query))})]}),i.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:i.map((x,m)=>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:x.query}),e.jsxs("p",{className:"mt-0.5 flex items-center gap-2 text-xs text-secondary",children:[Pr(x.action),x.winnabilityClass==="ceded"&&e.jsx(oe,{tone:"caution",children:"Ceded surface"})]})]},m))})]})]}):e.jsx(Cn,{message:"No supporting evidence yet — this fills in after the first AI check."})]})}function Sn(t){return t==="up"?"positive":t==="down"?"negative":"neutral"}function kn(t){return t==="up"?"↑":t==="down"?"↓":"→"}function ln({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==="%"?"%":"",i=Sn(s.direction),r=i==="positive"?"text-positive-400":i==="negative"?"text-negative-400":"text-heading",o=n==="%"?`${s.deltaAbs>0?"+":""}${s.deltaAbs.toFixed(1)}% vs ${s.prior}%`:Lo(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 ${r}`,children:[s.current,a," ",e.jsx("span",{className:"text-sm font-medium",children:kn(s.direction)})]}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:o})]})}function xa({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 i=Sn(s.direction),r=i==="positive"?"text-positive-400":i==="negative"?"text-negative-400":"text-heading",o=Io(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 ${r}`,children:[Re(s.current)," ",e.jsx("span",{className:"text-sm font-medium",children:kn(s.direction)})]}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:o})]})}function $c({movements:t,audience:s}){const n=t.filter(i=>i.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(i=>{const r=i.deltaAbs>0?"+":"",o=Sn(i.direction),p=o==="positive"?"text-positive-400":o==="negative"?"text-negative-400":"text-neutral";return e.jsxs("tr",{children:[e.jsx("td",{children:a?Bs(i.provider):i.provider}),e.jsxs("td",{children:[i.prior,"%"]}),e.jsxs("td",{children:[i.current,"%"]}),e.jsxs("td",{className:p,children:[r,i.deltaAbs.toFixed(1),"% ",kn(i.direction)]})]},i.provider)})})]})})]})}function ha({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 i=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:[!i&&e.jsx("th",{children:"Severity"}),e.jsx("th",{children:i?"What changed":"Title"}),e.jsx("th",{children:i?"Customer question":"Query"}),e.jsx("th",{children:i?"AI tool":"Provider"})]})}),e.jsx("tbody",{children:t.map(r=>e.jsxs("tr",{children:[!i&&e.jsxs("td",{children:[e.jsx(oe,{tone:mc[r.severity],children:Dr(r.severity)}),r.instanceCount>1&&e.jsxs("span",{className:"ml-2 text-[11px] text-muted",children:["×",r.instanceCount]})]}),e.jsxs("td",{className:"evidence-query-cell",children:[r.title,i&&r.instanceCount>1&&e.jsxs("span",{className:"ml-2 text-[11px] text-muted",children:["×",r.instanceCount]})]}),e.jsx("td",{className:"text-xs text-secondary",children:r.query}),e.jsx("td",{className:"text-xs text-secondary",children:i?Bs(r.provider):r.provider})]},r.id))})]})})]})}function Pc({report:t,audience:s}){const n=t.whatsChanged,a=s==="client",i=!n.enoughHistory&&!n.gscClicksDelta&&!n.aiReferralsDelta&&n.wins.length===0&&n.regressions.length===0,r=e.jsx(ps,{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 i?e.jsxs("section",{className:"page-section-divider",children:[r,e.jsx(Cn,{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:[r,e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(ln,{label:a?"AI mentions your name":"Citation rate",delta:a?n.mentionRate:n.citationRate,unit:"%"}),e.jsx(ln,{label:a?"AI links to your website":"Mention rate",delta:a?n.citationRate:n.mentionRate,unit:"%"}),e.jsx(ln,{label:a?"Questions AI mentioned you in":"Cited queries",delta:a?n.mentionedQueryCount:n.citedQueryCount,unit:"count"}),e.jsx(xa,{label:a?"Visitors from Google":"GSC clicks",delta:n.gscClicksDelta,countLabel:a?"visits":"clicks",comparisonWindowDays:n.comparisonWindowDays}),e.jsx(xa,{label:a?"Visitors from AI tools":"AI referral sessions",delta:n.aiReferralsDelta,countLabel:a?"visits":"sessions",comparisonWindowDays:n.comparisonWindowDays})]}),e.jsx($c,{movements:n.providerMovements,audience:s}),e.jsx(ha,{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(ha,{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 cn({label:t,value:s,tone:n,subtitle:a}){const i=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 ${i}`,children:s}),a&&e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:a})]})}function ps({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 Dc({items:t,limit:s=3,className:n}){if(t.length===0)return null;const a=t.slice(0,s),i=t.length-a.length;return e.jsxs("div",{className:`flex flex-wrap gap-1.5 ${n??""}`,children:[a.map((r,o)=>e.jsx("span",{className:"rounded-md border border-default bg-bg-elevated/40 px-2 py-0.5 text-[11px] text-neutral",children:r},o)),i>0&&e.jsxs("span",{className:"rounded-md border border-default bg-bg-elevated/40 px-2 py-0.5 text-[11px] text-secondary",children:["+",i," more"]})]})}function Cn({message:t}){return e.jsx("p",{className:"text-sm text-muted py-4 text-center",children:t})}function Lc({project:t,onUpdateProject:s,onRefresh:n}){const[a,i]=l.useState(!1),[r,o]=l.useState(!1),[p,x]=l.useState(null),[m,f]=l.useState(t.displayName),[d,R]=l.useState(t.canonicalDomain),[h,A]=l.useState(t.country),[w,C]=l.useState(t.language),[P,F]=l.useState(t.ownedDomains??[]),[M,_]=l.useState(""),[u,S]=l.useState(t.aliases??[]),[Q,v]=l.useState(""),[U,L]=l.useState(null),[N,E]=l.useState(!1),[O,se]=l.useState(!1),[he,ye]=l.useState(""),[pe,ge]=l.useState(""),[Y,de]=l.useState(""),[fe,b]=l.useState(""),[q,X]=l.useState("");l.useEffect(()=>{a||(f(t.displayName),R(t.canonicalDomain),A(t.country),C(t.language),F(t.ownedDomains??[]),S(t.aliases??[]))},[t,a]);function le(){i(!1),x(null),f(t.displayName),R(t.canonicalDomain),A(t.country),C(t.language),F(t.ownedDomains??[]),S(t.aliases??[]),_(""),v("")}function ce(){const y=M.trim();y&&(P.includes(y)||F([...P,y]),_(""))}function $e(y){F(P.filter(I=>I!==y))}function $(){const y=Q.trim();if(!y)return;const I=y.toLowerCase();u.some(Le=>Le.toLowerCase()===I)||S([...u,y]),v("")}function H(y){S(u.filter(I=>I!==y))}async function Te(){if(!(!m.trim()||!d.trim()||!h.trim()||!w.trim())){o(!0),x(null);try{await s(t.name,{displayName:m.trim(),canonicalDomain:d.trim(),ownedDomains:P,aliases:u,country:h.trim(),language:w.trim()}),i(!1),K({title:"Project settings saved",detail:`${m.trim()} was updated.`,tone:"positive",dedupeKey:`project:update:${t.name}`,dedupeMode:"replace"})}catch(y){x(y instanceof Error?y.message:"Failed to save")}finally{o(!1)}}}async function je(){const y=he.trim(),I=pe.trim(),Le=Y.trim(),Be=fe.trim();if(!(!y||!I||!Le||!Be)){E(!0),L(null);try{const we={label:y,city:I,region:Le,country:Be};q.trim()&&(we.timezone=q.trim()),await Rr(t.name,we),n(),ye(""),ge(""),de(""),b(""),X(""),se(!1),K({title:"Location added",detail:`${y} is now available for ${t.name}.`,tone:"positive",dedupeKey:`project:location:add:${t.name}:${y}`,dedupeMode:"drop"})}catch(we){L(we instanceof Error?we.message:"Failed to add location")}finally{E(!1)}}}async function ve(y){E(!0),L(null);try{await Ir(t.name,y),n(),K({title:"Location removed",detail:`${y} was removed from ${t.name}.`,tone:"positive",dedupeKey:`project:location:remove:${t.name}:${y}`,dedupeMode:"drop"})}catch(I){L(I instanceof Error?I.message:"Failed to remove location")}finally{E(!1)}}async function ne(y){E(!0),L(null);try{await Lr(t.name,y),n(),K({title:"Default location updated",detail:`${y} is now the default for ${t.name}.`,tone:"positive",dedupeKey:`project:location:default:${t.name}`,dedupeMode:"replace"})}catch(I){L(I instanceof Error?I.message:"Failed to set default location")}finally{E(!1)}}const G=m!==t.displayName||d!==t.canonicalDomain||h!==t.country||w!==t.language||JSON.stringify(P)!==JSON.stringify(t.ownedDomains??[])||JSON.stringify(u)!==JSON.stringify(t.aliases??[]),z="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",ue="block text-xs font-medium text-secondary mb-1",xe=he.trim()&&pe.trim()&&Y.trim()&&fe.trim();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:"Configuration"}),e.jsx("h2",{children:"Project settings"})]}),!T()&&!a&&e.jsx(D,{type:"button",variant:"outline",size:"sm",onClick:()=>i(!0),children:"Edit settings"})]}),p&&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:[p,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>x(null),children:"×"})]}),!T()&&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:ue,children:"Display name"}),e.jsx("input",{className:z,type:"text",value:m,onChange:y=>f(y.target.value),placeholder:"My Project"})]}),e.jsxs("div",{children:[e.jsx("label",{className:ue,children:"Canonical domain"}),e.jsx("input",{className:z,type:"text",value:d,onChange:y=>R(y.target.value),placeholder:"example.com"})]}),e.jsxs("div",{children:[e.jsx("label",{className:ue,children:"Country"}),e.jsx("input",{className:z,type:"text",value:h,onChange:y=>A(y.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{children:[e.jsx("label",{className:ue,children:"Language"}),e.jsx("input",{className:z,type:"text",value:w,onChange:y=>C(y.target.value),placeholder:"en"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:ue,children:"Owned domains"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:P.map(y=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-mono-700/60 bg-mono-800/40 px-2 py-0.5 text-xs text-neutral",children:[y,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>$e(y),"aria-label":`Remove ${y}`,children:"×"})]},y))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${z} flex-1`,type:"text",placeholder:"docs.example.com",value:M,onChange:y=>_(y.target.value),onKeyDown:y=>y.key==="Enter"&&(y.preventDefault(),ce())}),e.jsx(D,{type:"button",variant:"outline",size:"sm",disabled:!M.trim(),onClick:ce,children:"Add"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:ue,children:"Aliases"}),e.jsx("p",{className:"text-[11px] text-muted mb-1.5",children:'Additional brand names checked against LLM answer text. Use for product names, prior names, or DBAs (e.g. add "Meta" as an alias to facebook.com).'}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:u.map(y=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-mono-700/60 bg-mono-800/40 px-2 py-0.5 text-xs text-neutral",children:[y,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>H(y),"aria-label":`Remove ${y}`,children:"×"})]},y))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${z} flex-1`,type:"text",placeholder:"Facebook",value:Q,onChange:y=>v(y.target.value),onKeyDown:y=>y.key==="Enter"&&(y.preventDefault(),$())}),e.jsx(D,{type:"button",variant:"outline",size:"sm",disabled:!Q.trim(),onClick:$,children:"Add"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-default",children:[e.jsx(D,{type:"button",disabled:r||!G||!m.trim()||!d.trim(),onClick:ae(Te),children:r?"Saving...":"Save changes"}),e.jsx(D,{type:"button",variant:"outline",disabled:r,onClick:le,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(y=>e.jsx("span",{className:"rounded-full border border-mono-700/60 bg-mono-800/40 px-2 py-0.5 text-xs text-neutral",children:y},y))}):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(y=>e.jsx("span",{className:"rounded-full border border-mono-700/60 bg-mono-800/40 px-2 py-0.5 text-xs text-neutral",children:y},y))}):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:[U&&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:[U,e.jsx("button",{type:"button",className:"ml-1 text-negative-400 hover:text-negative-200",onClick:()=>L(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(y=>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-full border px-1.5 py-0.5 text-[10px] font-medium ${y.label===t.defaultLocation?"border-positive-700/60 bg-positive-950/30 text-positive":"border-mono-700/60 bg-mono-800/40 text-neutral"}`,children:[y.label,y.label===t.defaultLocation?" ★":""]})}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:y.city}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:y.region}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:y.country}),e.jsx("td",{className:"py-1.5 pr-3 text-muted",children:y.timezone??"—"}),e.jsx("td",{className:"py-1.5",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[!T()&&y.label!==t.defaultLocation&&e.jsx("button",{type:"button",disabled:N,onClick:()=>{ne(y.label)},className:"text-[10px] text-muted hover:text-positive-400 transition-colors disabled:opacity-40","aria-label":`Set ${y.label} as default location`,children:"Set default"}),!T()&&e.jsx("button",{type:"button",disabled:N,onClick:()=>{ve(y.label)},className:"text-[10px] text-muted hover:text-negative-400 transition-colors disabled:opacity-40","aria-label":`Remove location ${y.label}`,children:"Remove"})]})})]},y.label))})]}):e.jsx("p",{className:"text-muted text-xs mb-2",children:"No locations configured"}),T()?null:O?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-[10px] font-medium uppercase tracking-wide text-muted",children:"Add location"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] text-muted mb-0.5",children:"Label *"}),e.jsx("input",{className:z,type:"text",value:he,onChange:y=>ye(y.target.value),placeholder:"nyc"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] text-muted mb-0.5",children:"City *"}),e.jsx("input",{className:z,type:"text",value:pe,onChange:y=>ge(y.target.value),placeholder:"New York"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] text-muted mb-0.5",children:"Region *"}),e.jsx("input",{className:z,type:"text",value:Y,onChange:y=>de(y.target.value),placeholder:"NY"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] text-muted mb-0.5",children:"Country *"}),e.jsx("input",{className:z,type:"text",value:fe,onChange:y=>b(y.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"block text-[10px] text-muted mb-0.5",children:"Timezone (optional)"}),e.jsx("input",{className:z,type:"text",value:q,onChange:y=>X(y.target.value),placeholder:"America/New_York"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(D,{type:"button",size:"sm",disabled:N||!xe,onClick:ae(je),children:N?"Adding...":"Add location"}),e.jsx(D,{type:"button",size:"sm",variant:"outline",disabled:N,onClick:()=>{se(!1),L(null)},children:"Cancel"})]})]}):e.jsx(D,{type:"button",size:"sm",variant:"outline",onClick:()=>se(!0),children:"+ Add location"})]})]})]})})})]})}const Ic=[{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"}],pa=["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 Rc({projectName:t}){const[s,n]=l.useState("loading"),[a,i]=l.useState(!1),[r,o]=l.useState("daily"),[p,x]=l.useState(6),[m,f]=l.useState(""),[d,R]=l.useState("UTC"),[h,A]=l.useState(!1),[w,C]=l.useState(""),[P,F]=l.useState(!1),[M,_]=l.useState(!1),[u,S]=l.useState(null);l.useEffect(()=>{Tr(t).then(n).catch(()=>n(null))},[t]);const Q=()=>{if(s&&s!=="loading"){const N=Er(s.preset??null,s.cronExpr);o(N.freq),x(N.hour),f(N.customCron);const E=pa.includes(s.timezone);R(E?s.timezone:"Other"),A(!E),C(E?"":s.timezone)}else o("daily"),x(6),f(""),R("UTC"),A(!1),C("");S(null),i(!0)},v=async()=>{F(!0),S(null);try{const E={timezone:h?w.trim()||"UTC":d};r==="custom"?E.cron=m.trim():E.preset=Br(r,p);const O=await Fn(t,E);n(O),i(!1),K({title:"Schedule saved",detail:Hs(O.preset??null,O.cronExpr,O.timezone),tone:"positive",dedupeKey:`schedule:${t}`,dedupeMode:"replace"})}catch(N){S(N instanceof Error?N.message:"Failed to save schedule")}finally{F(!1)}},U=async()=>{if(!(!s||s==="loading")){F(!0),S(null);try{const N={timezone:s.timezone,enabled:!s.enabled};s.preset?N.preset=s.preset:N.cron=s.cronExpr;const E=await Fn(t,N);n(E),K({title:E.enabled?"Schedule resumed":"Schedule paused",detail:Hs(E.preset??null,E.cronExpr,E.timezone),tone:"positive",dedupeKey:`schedule:toggle:${t}`,dedupeMode:"replace"})}catch(N){S(N instanceof Error?N.message:"Failed to update schedule")}finally{F(!1)}}},L=async()=>{_(!0),S(null);try{await Or(t),n(null),i(!1),K({title:"Schedule removed",detail:`${t} will no longer run automatically.`,tone:"positive",dedupeKey:`schedule:remove:${t}`,dedupeMode:"drop"})}catch(N){S(N instanceof Error?N.message:"Failed to remove schedule")}finally{_(!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"})]}),!T()&&s!=="loading"&&!a&&e.jsx(D,{type:"button",variant:"outline",size:"sm",onClick:Q,children:s?"Edit schedule":"+ Set schedule"})]}),s==="loading"&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),s!=="loading"&&!a&&s===null&&e.jsx(W,{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(W,{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:Hs(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(oe,{tone:s.enabled?"positive":"neutral",children:s.enabled?"Active":"Paused"}),!T()&&e.jsx(D,{type:"button",variant:"outline",size:"sm",disabled:P,onClick:ae(U),children:s.enabled?"Pause":"Resume"}),!T()&&e.jsx(D,{type:"button",variant:"ghost",size:"sm",disabled:M,onClick:ae(L),children:M?"Removing...":"Remove"})]})]}),u&&e.jsx("p",{className:"text-negative-400 text-sm mt-2",children:u})]}),!T()&&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:r,onChange:N=>o(N.target.value),children:Ic.map(N=>e.jsx("option",{value:N.value,children:N.label},N.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:p,disabled:r==="twice-daily"||r==="custom",onChange:N=>x(parseInt(N.target.value)),children:Array.from({length:24},(N,E)=>e.jsx("option",{value:E,children:Mr(E)},E))})]})]}),r==="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:m,onChange:N=>f(N.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:h?"Other":d,onChange:N=>{N.target.value==="Other"?(A(!0),R("Other")):(A(!1),R(N.target.value))},children:[pa.map(N=>e.jsx("option",{value:N,children:N},N)),e.jsxs("option",{value:"Other",children:["Other (enter manually)","…"]})]}),h&&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:w,onChange:N=>C(N.target.value)})]}),u&&e.jsx("p",{className:"text-negative-400 text-sm",children:u}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(D,{type:"button",variant:"outline",size:"sm",onClick:()=>{i(!1),S(null)},children:"Cancel"}),e.jsx(D,{type:"button",size:"sm",disabled:P||r==="custom"&&!m.trim(),onClick:ae(v),children:P?"Saving...":"Save schedule"})]})]})]})}const Tc=[{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 Mc({projectName:t}){const[s,n]=l.useState("loading"),[a,i]=l.useState(!1),[r,o]=l.useState(""),[p,x]=l.useState(["citation.lost","citation.gained"]),[m,f]=l.useState(!1),[d,R]=l.useState(null),[h,A]=l.useState({}),[w,C]=l.useState(new Set);l.useEffect(()=>{Fr(t).then(n).catch(()=>n([]))},[t]);const P=u=>{x(S=>S.includes(u)?S.filter(Q=>Q!==u):[...S,u])},F=async()=>{if(!(!r.trim()||p.length===0)){f(!0),R(null);try{const u=await Gr(t,{channel:"webhook",url:r.trim(),events:p});n(S=>S==="loading"?[u]:[...S,u]),o(""),x(["citation.lost","citation.gained"]),i(!1),K({title:"Webhook added",detail:`Notifications will be sent to ${u.url}.`,tone:"positive",dedupeKey:`notification:add:${t}`,dedupeMode:"drop"})}catch(u){R(u instanceof Error?u.message:"Failed to add webhook")}finally{f(!1)}}},M=async u=>{if(!w.has(u)){C(S=>new Set(S).add(u));try{await _r(t,u),n(S=>S==="loading"?S:S.filter(Q=>Q.id!==u)),K({title:"Webhook removed",detail:`${t} no longer sends notifications to this endpoint.`,tone:"positive",dedupeKey:`notification:remove:${t}:${u}`,dedupeMode:"drop"})}catch(S){R(S instanceof Error?S.message:"Failed to remove webhook")}finally{C(S=>{const Q=new Set(S);return Q.delete(u),Q})}}},_=async u=>{A(S=>({...S,[u]:{state:"testing"}}));try{const S=await qr(t,u);A(Q=>({...Q,[u]:{state:S.ok?"ok":"fail",status:S.status}})),S.ok&&K({title:"Test notification sent",detail:`Webhook returned status ${S.status}.`,tone:"positive",dedupeKey:`notification:test:${t}:${u}`,dedupeMode:"replace"})}catch{A(S=>({...S,[u]:{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"})]}),!T()&&s!=="loading"&&e.jsx(D,{type:"button",variant:"outline",size:"sm",onClick:()=>{i(!a),R(null)},children:a?"Cancel":"+ Add webhook"})]}),!T()&&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:r,onChange:u=>o(u.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:Tc.map(u=>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:p.includes(u.value),onChange:()=>P(u.value)}),e.jsx("span",{className:"text-sm text-neutral",children:u.label})]},u.value))})]}),d&&e.jsx("p",{className:"text-negative-400 text-sm",children:d}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(D,{type:"button",variant:"outline",size:"sm",onClick:()=>{i(!1),R(null)},children:"Cancel"}),e.jsx(D,{type:"button",size:"sm",disabled:m||!r.trim()||p.length===0,onClick:ae(F),children:m?"Adding...":"Add webhook"})]})]}),s==="loading"&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),s!=="loading"&&s.length===0&&!a&&e.jsx(W,{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(u=>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:u.urlHost,children:u.urlDisplay??u.url})}),e.jsx("td",{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:u.events.map(S=>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:S.replace("."," ")},S))})}),e.jsx("td",{children:e.jsx(oe,{tone:u.enabled?"positive":"neutral",children:u.enabled?"Active":"Paused"})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[h[u.id]&&(()=>{const S=h[u.id],Q=S.state==="testing"?"Sending…":S.state==="ok"?`Delivered${S.status?` (${S.status})`:""}`:`Failed${S.status?` (${S.status})`:""}`;return e.jsx(oe,{tone:S.state==="ok"?"positive":S.state==="fail"?"negative":"neutral",children:Q})})(),!T()&&e.jsx(D,{variant:"ghost",size:"sm",type:"button",disabled:h[u.id]?.state==="testing",onClick:()=>{_(u.id)},children:"Test"}),!T()&&e.jsx(D,{variant:"ghost",size:"sm",type:"button",disabled:w.has(u.id),onClick:()=>{M(u.id)},children:w.has(u.id)?"Removing…":"Remove"})]})})]},u.id))})]}),d&&e.jsx("p",{className:"text-negative-400 text-sm mt-2",children:d})]})]})}function _t(t,s){return t.invalidateQueries({predicate:n=>{const a=n.queryKey[0];return typeof a?._id=="string"&&a._id.startsWith(s)}})}function Ec({projectName:t,refreshNonce:s}){const n=vt(),[a,i]=l.useState(null),[r,o]=l.useState([]),[p,x]=l.useState(null),[m,f]=l.useState([]),[d,R]=l.useState([]),[h,A]=l.useState(null),[w,C]=l.useState(""),[P,F]=l.useState(""),[M,_]=l.useState(""),[u,S]=l.useState(!0),[Q,v]=l.useState(!1),[U,L]=l.useState(null),[N,E]=l.useState("performance");l.useEffect(()=>{O()},[t,s]);async function O(){S(!0),L(null);try{const b=await n.fetchQuery({...Sa({client:Z,path:{name:t}}),staleTime:Oe});if(i(b),b.connected){const[q,X,le,ce]=await Promise.all([n.fetchQuery({...ka({client:Z,path:{name:t}}),staleTime:Oe}).catch(()=>null),n.fetchQuery({...Ca({client:Z,path:{name:t}}),staleTime:Oe}).catch(()=>[]),n.fetchQuery({...lo({client:Z,path:{name:t}}),staleTime:Oe}).catch(()=>[]),b.siteUrl?Promise.resolve([]):n.fetchQuery({...co({client:Z,path:{name:t}}),staleTime:Oe}).then($e=>$e.sites).catch(()=>[])]);x(q),f(X),R(le),o(ce)}else x(null),f([]),R([]),o([])}catch(b){L(b instanceof Error?b.message:"Failed to load Bing data")}finally{S(!1)}}async function se(){if(P.trim()){L(null);try{const b=await uo(t,P.trim());await _t(n,"getApiV1ProjectsByNameBing"),F(""),b.availableSites.length>0&&o(b.availableSites),await O()}catch(b){L(b instanceof Error?b.message:"Failed to connect")}}}async function he(){try{await mo(t),await _t(n,"getApiV1ProjectsByNameBing"),i(null),o([]),x(null),f([]),R([]),A(null),_(""),L(null)}catch(b){L(b instanceof Error?b.message:"Failed to disconnect")}}async function ye(){if(M)try{await xo(t,M),await _t(n,"getApiV1ProjectsByNameBing"),await O()}catch(b){L(b instanceof Error?b.message:"Failed to set site")}}async function pe(){if(w.trim())try{const b=await Aa(t,w.trim());await _t(n,"getApiV1ProjectsByNameBing"),A(b),f(q=>[b,...q])}catch(b){L(b instanceof Error?b.message:"Inspection failed")}}async function ge(b){v(!0),L(null);try{const q=await Un(t,{urls:[b]}),{succeeded:X,failed:le,total:ce}=q.summary;K({title:"Bing submission requested",detail:le===0?`${X} URL submitted to Bing.`:`${X}/${ce} submitted successfully, ${le} failed.`,tone:le===0?"positive":"caution",dedupeKey:`bing:indexing:${t}:${b}`,dedupeMode:"replace"})}catch(q){const X=q instanceof Error?q.message:"Submission failed";L(X),K({title:"Bing submission failed",detail:X,tone:"negative",dedupeKey:`bing:indexing:${t}:${b}`,dedupeMode:"replace"})}finally{v(!1)}}async function Y(){v(!0),L(null),K({title:"Submitting URLs to Bing",detail:"Requesting indexing for all currently unindexed URLs.",tone:"neutral",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"});try{const b=await Un(t,{allUnindexed:!0}),{succeeded:q,failed:X,total:le}=b.summary;K({title:"Bing submissions requested",detail:X===0?`${q}/${le} URL${le!==1?"s":""} submitted to Bing.`:`${q}/${le} submitted successfully, ${X} failed.`,tone:X===0?"positive":"caution",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}catch(b){const q=b instanceof Error?b.message:"Batch submission failed";L(q),K({title:"Bing submissions failed",detail:q,tone:"negative",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}finally{v(!1)}}if(u)return e.jsx(W,{className:"surface-card",children:e.jsx("div",{className:"text-sm text-secondary",children:"Loading Bing data..."})});if(!a?.connected)return T()?e.jsxs(W,{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(oe,{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(W,{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(oe,{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:P,onChange:b=>F(b.target.value),onKeyDown:b=>{b.key==="Enter"&&se()}}),e.jsx(D,{size:"sm",disabled:!P.trim(),onClick:ae(se),children:"Connect"})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-muted",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"})]})]}),U&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:U})]});if(!a.siteUrl)return e.jsxs(W,{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(oe,{tone:"positive",children:"Connected"}),!T()&&e.jsx(D,{size:"sm",variant:"ghost",onClick:ae(he),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?Je(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"}),r.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:M,onChange:b=>_(b.target.value),children:[e.jsx("option",{value:"",children:"Select a site..."}),r.map(b=>e.jsxs("option",{value:b.url,children:[b.url,b.verified?" (verified)":""]},b.url))]}),!T()&&e.jsx(D,{size:"sm",disabled:!M,onClick:ae(ye),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."})]})]}),U&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:U})]});const de=[{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"}],fe=de.find(b=>b.key===N)??de[0];return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(W,{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(oe,{tone:"positive",children:"Connected"}),!T()&&e.jsx(D,{size:"sm",variant:"ghost",onClick:ae(he),children:"Disconnect"})]})]}),U&&e.jsx("p",{className:"mb-3 text-xs text-negative-400",children:U}),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:T()?e.jsxs(e.Fragment,{children:["This project is currently mapped to ",e.jsx("code",{children:a.siteUrl}),"."]}):e.jsxs(e.Fragment,{children:["Canonry stores Bing connections per canonical domain. This project is currently mapped to ",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?Je(a.updatedAt):"—"})]})]})]})]}),e.jsxs(W,{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:fe.eyebrow}),e.jsx("h3",{children:fe.title})]}),e.jsx("p",{className:"text-xs text-muted",children:p?.lastInspectedAt?`Last inspected ${Je(p.lastInspectedAt)}`:"No inspection history yet"})]}),e.jsx("div",{className:"flex gap-1 border-b border-base",children:de.map(b=>e.jsx("button",{className:`px-3 py-1.5 text-xs font-medium border-b-2 transition-colors ${N===b.key?"border-mono-200 text-strong":"border-transparent text-muted hover:text-neutral"}`,onClick:()=>E(b.key),children:b.label},b.key))}),N==="coverage"&&p&&e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(As,{label:"Indexed",value:p.summary.indexed,tone:"positive"}),e.jsx(As,{label:"Not in index",value:p.summary.notIndexed+(p.summary.unknown??0),tone:"negative"}),e.jsx(As,{label:"Status unknown",value:p.summary.unknown??0,tone:"neutral"}),e.jsx(As,{label:"Coverage",value:`${p.summary.percentage}%`,tone:"neutral"})]}),p.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 (",p.notIndexed.length,")"]}),!T()&&e.jsx(D,{size:"sm",variant:"ghost",disabled:Q,onClick:ae(Y),children:Q?"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"}),!T()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:p.notIndexed.map(b=>e.jsxs("tr",{className:"border-b border-base/50",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:b.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:b.httpCode??"—"}),!T()&&e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-[10px] text-secondary hover:text-strong underline underline-offset-2",disabled:Q,onClick:()=>{ge(b.url)},children:"Submit"})})]},b.id))})]})})]}),(p.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-xs font-medium text-secondary",children:["Unknown — not yet confirmed (",(p.unknown??[]).length,")"]}),!T()&&e.jsx(D,{size:"sm",variant:"ghost",disabled:Q,onClick:ae(Y),children:Q?"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"}),!T()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:(p.unknown??[]).map(b=>e.jsxs("tr",{className:"border-b border-base/50",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:b.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:b.lastCrawledDate?Je(b.lastCrawledDate):"—"}),!T()&&e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-[10px] text-secondary hover:text-strong underline underline-offset-2",disabled:Q,onClick:()=>{ge(b.url)},children:"Submit"})})]},b.id))})]})})]}),p.indexed.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"mb-2 text-xs font-medium text-secondary",children:["Indexed (",p.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:p.indexed.map(b=>e.jsxs("tr",{className:"border-b border-base/50",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:b.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:b.lastCrawledDate?Je(b.lastCrawledDate):"—"})]},b.id))})]})})]})]}),N==="coverage"&&!p&&e.jsx("p",{className:"mt-4 text-xs text-muted",children:"No coverage data yet. Inspect URLs to build coverage data."}),N==="inspections"&&e.jsxs("div",{className:"mt-4 space-y-3",children:[!T()&&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:w,onChange:b=>C(b.target.value),onKeyDown:b=>{b.key==="Enter"&&pe()}}),e.jsx(D,{size:"sm",disabled:!w.trim(),onClick:ae(pe),children:"Inspect"})]}),h&&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:h.url}),e.jsxs("div",{className:"text-secondary",children:["In Index: ",e.jsx("span",{className:h.inIndex?"text-positive-400":"text-negative-400",children:h.inIndex?"Yes":"No"})," · ","HTTP: ",h.httpCode??"—"," · ","Crawled: ",h.lastCrawledDate??"—"]})]}),m.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:m.map(b=>e.jsxs("tr",{className:"border-b border-base/50",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:b.url}),e.jsx("td",{className:"py-1.5 px-3",children:e.jsx(oe,{tone:b.inIndex?"positive":"negative",children:b.inIndex?"Yes":"No"})}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:b.httpCode??"—"}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:Je(b.inspectedAt)})]},b.id))})]})})]}),N==="performance"&&e.jsx("div",{className:"mt-4",children:d.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:Cs[Pt.Clicks]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-16",children:Cs[Pt.Impressions]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:Cs[Pt.CTR]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:Cs[Pt.Position]})]})}),e.jsx("tbody",{children:d.map((b,q)=>e.jsxs("tr",{className:"border-b border-base/50",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:b.query}),e.jsx("td",{className:"py-1.5 px-3 text-right text-strong",children:b.clicks}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:b.impressions}),e.jsxs("td",{className:"py-1.5 px-3 text-right text-secondary",children:[(Number.isFinite(b.ctr)?b.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:b.averagePosition.toFixed(1)})]},q))})]})})})]})]})}function Oc({projectName:t}){const s=vt(),[n,a]=l.useState("google"),[i,r]=l.useState(!0),[o,p]=l.useState("idle"),[x,m]=l.useState(null),f=l.useRef(null),[d,R]=l.useState(!1),[h,A]=l.useState(null),[w,C]=l.useState(null),[P,F]=l.useState(!1),[M,_]=l.useState(null),[u,S]=l.useState(null),[Q,v]=l.useState(0);async function U(b=!1){b||r(!0),m(null);try{const[q,X,le]=await Promise.all([s.fetchQuery(io({client:Z})).catch(()=>null),s.fetchQuery({...bn({client:Z,path:{name:t}}),staleTime:Oe}).catch(()=>[]),s.fetchQuery({...Sa({client:Z,path:{name:t}}),staleTime:Oe}).catch(()=>null)]),ce=X.find(H=>H.connectionType==="gsc")??null;R(!!q?.google?.configured),F(!!q?.bing?.configured),A(ce),_(le);const[$e,$]=await Promise.all([ce?s.fetchQuery({...ba({client:Z,path:{name:t}}),staleTime:Oe}).catch(()=>null):Promise.resolve(null),le?.connected?s.fetchQuery({...ka({client:Z,path:{name:t}}),staleTime:Oe}).catch(()=>null):Promise.resolve(null)]);C($e),S($)}catch(q){m(q instanceof Error?q.message:"Failed to load search console overview")}finally{r(!1)}}async function L(){if(o!=="idle")return;f.current?.abort();const b=new AbortController;f.current=b;const q=b.signal;p("syncing"),m(null),K({title:"Refreshing search coverage",detail:"Queueing Google and Bing checks, then reloading the workspaces.",tone:"neutral",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"});const X=[];try{async function le(){if(!h)return;const H=await ro(t);if(!H?.id)return;const Te=2e3,ve=Date.now()+12e4;for(;Date.now()<ve;){if(q.aborted||(await new Promise(G=>setTimeout(G,Te)),q.aborted))return;const ne=await ya(H.id).catch(()=>null);if(!ne)break;if(["completed","failed","cancelled"].includes(ne.status)){ne.status!=="completed"&&X.push(`Google sync ${ne.status}`);break}}}const ce=10;async function $e(){if(!M?.connected)return;const H=await s.fetchQuery({...Ca({client:Z,path:{name:t}}),staleTime:0}).catch(()=>[]),Te=[...new Set(H.map(je=>je.url))];if(Te.length===0){await oo(t).catch(()=>null);return}for(let je=0;je<Te.length;je+=ce){if(q.aborted)return;const ve=Te.slice(je,je+ce),G=(await Promise.allSettled(ve.map(z=>Aa(t,z)))).filter(z=>z.status==="rejected").length;G>0&&X.push(`${G} Bing inspection(s) failed`)}}const $=await Promise.allSettled([le(),$e()]);for(const H of $)H.status==="rejected"&&X.push(H.reason instanceof Error?H.reason.message:"Sync failed");if(q.aborted)return;if(p("reloading"),await Promise.all([_t(s,"getApiV1ProjectsByNameGoogleGsc"),_t(s,"getApiV1ProjectsByNameBing")]),await U(!0),v(H=>H+1),X.length>0){const H=`Partial refresh: ${X.join("; ")}`;m(H),K({title:"Search coverage partially refreshed",detail:H,tone:"caution",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}else K({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(le){if(!q.aborted){const ce=le instanceof Error?le.message:"Refresh failed";m(ce),K({title:"Search coverage refresh failed",detail:ce,tone:"negative",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}}finally{q.aborted||p("idle")}}l.useEffect(()=>(U(),()=>{f.current?.abort()}),[t]);const N=h?"positive":d?"caution":"negative",E=h?"Connected":d?"Ready to connect":"Needs setup",O=w?`${w.summary.percentage}% indexed`:h?"Awaiting coverage":"No coverage data",se=w?`${w.summary.notIndexed} not indexed${w.summary.deindexed>0?` · ${w.summary.deindexed} deindexed`:""}`:h?"Run sitemap inspection to populate coverage":d?"Connect Search Console for this domain":"Add Google OAuth credentials in Settings",he=w?.lastSyncedAt??w?.lastInspectedAt??h?.updatedAt??null,ye=M?.connected?"positive":P?"caution":"negative",pe=M?.connected?"Connected":P?"Ready to connect":"Needs setup",ge=u?`${u.summary.percentage}% indexed`:M?.connected?"Awaiting coverage":"No coverage data",Y=u?u.summary.notIndexed+(u.summary.unknown??0):0,de=u?`${Y} not in index`:M?.connected?"Inspect URLs to populate coverage":P?"Connect Bing Webmaster Tools for this domain":"Add a Bing API key in Settings",fe=u?.lastInspectedAt??M?.updatedAt??null;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(W,{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 & performance"}),e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-muted",children:"Scan both engines at a glance, then open the Google or Bing workspace when you need to inspect coverage or take action."})]}),!T()&&e.jsxs(D,{type:"button",variant:"outline",size:"sm",disabled:i||o!=="idle",onClick:()=>{L()},children:[e.jsx(dt,{className:`h-3.5 w-3.5 ${o!=="idle"?"animate-spin":""}`,"aria-hidden":"true"}),i?"Loading…":o==="syncing"?"Refreshing Google & Bing…":o==="reloading"?"Reloading workspaces…":"Refresh all"]})]}),x&&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:x}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsx(Jn,{eyebrow:"Google",title:"Google Search Console",status:i?"Loading…":E,tone:i?"neutral":N,targetLabel:"Selected property",targetValue:h?.propertyId??"No property selected",coverageValue:i?"Loading…":O,note:i?"Loading overview…":se,updatedAt:he,active:n==="google",onClick:()=>a("google")}),e.jsx(Jn,{eyebrow:"Bing",title:"Bing Webmaster Tools",status:i?"Loading…":pe,tone:i?"neutral":ye,targetLabel:"Selected site",targetValue:M?.siteUrl??"No site selected",coverageValue:i?"Loading…":ge,note:i?"Loading overview…":de,updatedAt:fe,active:n==="bing",onClick:()=>a("bing")})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",role:"tablist","aria-label":"Search engine workspaces",children:[["google","Google"],["bing","Bing"]].map(([b,q])=>e.jsx("button",{type:"button",role:"tab","aria-selected":n===b,className:`project-subnav-link ${n===b?"project-subnav-link-active":""}`,onClick:()=>a(b),children:q},b))}),n==="google"&&e.jsx(rl,{projectName:t,refreshNonce:Q}),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(Ec,{projectName:t,refreshNonce:Q})]})]})}function Bc(t,s=4){return t.length<=s?t.map(a=>`"${a}"`).join(", "):`${t.slice(0,s).map(a=>`"${a}"`).join(", ")}, and ${t.length-s} more`}function us({label:t,summary:s,displayValue:n,tooltip:a}){const i=s.value.trim()!==""&&Number.isFinite(Number(s.value)),r=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(De,{text:a||s.tooltip||""})]}),e.jsx("p",{className:`aeo-hero-row-value ${Jr[s.tone]}`,children:n??e.jsxs(e.Fragment,{children:[s.value,i?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:`${r}%`}})}),e.jsx("p",{className:"aeo-hero-row-detail",children:s.delta})]})}function Fc({model:t,sweepRunning:s,onJumpToEvidence:n,onJumpToActions:a}){const i=t.citationMovement,r=t.mentionMovement,o=t.movementComparison,p=t.recentRuns.find(M=>M.kind===xs["answer-visibility"]),x=t.insights.find(M=>M.actionGroup==="investigate")??t.insights.find(M=>M.actionGroup==="write")??t.insights.at(0),m=t.suggestedQueries.rows.at(0),f=new Set(t.providerScores.map(M=>M.provider)).size,d=t.project.locations.length,R=M=>M.tone==="positive"?"improved":M.tone==="negative"?"declined":M.gained>0||M.lost>0?"mixed":"steady",h=R(r),A=R(i),w=(()=>{if(s)return"A fresh sweep is running now";if(!o.hasPreviousRun)return"Baseline captured. The next sweep will show change.";if(o.querySetChanged)return"Tracking scope changed since the previous sweep";if(h===A)return h==="steady"?"Answer mentions and citation coverage held steady":h==="mixed"?"Answer mention and citation movement was mixed":`Answer mentions and citation coverage ${h}`;const M=h==="mixed"?"Answer mention movement was mixed":h==="steady"?"Answer mentions held steady":`Answer mentions ${h}`,_=A==="mixed"?"citation movement was mixed":A==="steady"?"citation coverage held steady":`citation coverage ${A}`;return`${M}; ${_}`})(),C=[...new Set([...r.lostQueries??[],...i.lostQueries??[],...r.gainedQueries??[],...i.gainedQueries??[]])],P=`${t.queryCounts.total} ${t.queryCounts.total===1?"query":"queries"} across ${f} ${f===1?"engine":"engines"}`,F=d>0?`${d} ${d===1?"location":"locations"}`:"project-wide";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:["Operator brief",e.jsx(De,{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:w}),e.jsxs("p",{className:"overview-brief-scope",children:["Tracking ",P,", ",F,"."]})]}),e.jsx("p",{className:"overview-brief-updated",children:p?`Latest sweep ${p.startedAt}`:"No sweep completed yet"})]}),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(us,{label:"Mentioned",summary:t.mentionSummary}),e.jsx(us,{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 previous sweep"}),o.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"}),e.jsxs("span",{className:"text-positive-400",children:["+",r.gained]}),e.jsxs("span",{className:"text-negative-400",children:["-",r.lost]})]}),e.jsxs("div",{className:"overview-signal-change-row",children:[e.jsx("span",{className:"overview-signal-change-label",children:"Cited"}),e.jsxs("span",{className:"text-positive-400",children:["+",i.gained]}),e.jsxs("span",{className:"text-negative-400",children:["-",i.lost]})]})]}),e.jsx("p",{className:`overview-brief-panel-copy ${o.querySetChanged?"text-caution-400/80":""}`,children:o.querySetChanged?`Query basket changed: +${o.addedQueryCount} added, -${o.removedQueryCount} removed. Movement compares ${o.comparableQueryCount} shared queries.`:`Same ${o.comparableQueryCount}-query basket${o.previousRunAt?` since ${Je(o.previousRunAt)}`:""}.`}),C.length>0&&e.jsxs("p",{className:"overview-brief-panel-copy",children:["Affected: ",Bc(C,2)]}),e.jsx("button",{type:"button",className:"overview-brief-link",onClick:n,children:"Review query evidence"})]}):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."})]})]}),e.jsxs("div",{className:"overview-brief-panel",children:[e.jsx("p",{className:"overview-brief-label",children:"Next action"}),x?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"overview-brief-panel-title",children:x.title}),x.detail&&e.jsx("p",{className:"overview-brief-panel-copy",children:x.detail}),e.jsx("button",{type:"button",className:"overview-brief-link",onClick:a,children:"Open action queue"})]}):m?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"overview-brief-panel-title",children:["Consider tracking “",m.query,"”"]}),e.jsx("p",{className:"overview-brief-panel-copy",children:m.reason}),e.jsx("button",{type:"button",className:"overview-brief-link",onClick:a,children:"Review query suggestions"})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"overview-brief-panel-title",children:"No outstanding action"}),e.jsx("p",{className:"overview-brief-panel-copy",children:T()?"Keep monitoring. Regressions and new query opportunities will surface here.":"Keep monitoring. Canonry will surface regressions and new query opportunities here."})]})]})]})]})}function dn({id:t,eyebrow:s,title:n,meta:a,defaultOpen:i=!1,children:r}){return e.jsxs("details",{id:t,className:"overview-disclosure page-section-divider scroll-mt-24",open:i||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(qs,{className:"overview-disclosure-icon",size:16,"aria-hidden":"true"})]})]}),e.jsx("div",{className:"overview-disclosure-body",children:r})]})}function Gc({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 i=[{label:`${s} (you)`,mentions:n.projectMentionSnapshots,isYou:!0},...n.perCompetitor.map(o=>({label:o.domain,mentions:o.mentionSnapshots,isYou:!1}))].sort((o,p)=>p.mentions-o.mentions),r=i[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:i.map(o=>{const p=o.mentions/a*100;return e.jsxs("li",{className:"mention-share-breakdown-row",children:[e.jsx("span",{className:`mention-share-breakdown-label ${o.isYou?"text-heading font-medium":"text-secondary"}`,children:o.label}),e.jsx("div",{className:"mention-share-breakdown-bar",children:e.jsx("div",{className:`mention-share-breakdown-bar-fill ${o.isYou?"bg-positive-500/70":"bg-mono-500/60"}`,style:{width:`${Math.max(o.mentions/r*100,2)}%`}})}),e.jsx("span",{className:"mention-share-breakdown-count",children:o.mentions}),e.jsxs("span",{className:"mention-share-breakdown-share",children:[p.toFixed(1),"%"]})]},o.label)})})]})}const qc={write:{title:"Write or update content",subtitle:"Queries with no answer, persistent gaps, or competitors winning the spot"},investigate:{title:"Investigate what changed",subtitle:"Citations or mentions you lost since the previous run"},monitor:{title:"Keep monitoring",subtitle:"Gains, new providers picking you up, holding ground"}};function _c({insights:t,suggestedQueries:s,projectName:n}){const{openEvidence:a}=ga(),[i,r]=l.useState(null),o=s.rows.length>0;if(t.length===0&&!o)return e.jsx("p",{className:"text-sm text-muted",children:"No outstanding opportunities. Trigger a sweep to surface fresh signals."});const p=["investigate","write","monitor"],x=new Map;for(const m of t){const f=x.get(m.actionGroup)??[];f.push(m),x.set(m.actionGroup,f)}return e.jsxs("div",{className:"opportunities-grid",children:[p.map(m=>{const f=x.get(m);if(!f||f.length===0)return null;const d=qc[m],R=e.jsx("div",{className:"opportunity-card-list",children:f.map(h=>{const A=i===h.id,w=h.affectedPhrases.length>0;return e.jsxs("div",{children:[e.jsx("div",{className:`opportunity-item opportunity-item-${h.tone} ${w?"cursor-pointer focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400":""}`,onClick:w?()=>r(A?null:h.id):void 0,onKeyDown:w?C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),r(A?null:h.id))}:void 0,tabIndex:w?0:void 0,role:w?"button":void 0,"aria-expanded":w?A:void 0,children:e.jsxs("div",{className:"flex items-start gap-1.5 min-w-0",children:[w&&e.jsx(Gs,{size:12,className:`mt-1 shrink-0 text-muted transition-transform duration-150 ${A?"rotate-90":""}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-heading leading-snug",children:h.title}),h.detail&&e.jsx("p",{className:"text-[11px] text-muted mt-0.5 leading-snug",children:h.detail})]})]})}),A&&e.jsx("div",{className:"opportunity-item-detail",children:h.affectedPhrases.map((C,P)=>e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[e.jsx(mn,{state:C.citationState}),e.jsx("span",{className:"text-xs text-neutral truncate",children:C.query}),C.provider&&e.jsx(Qt,{provider:C.provider})]}),C.evidenceId&&e.jsx("button",{type:"button",className:"text-[11px] text-secondary hover:text-strong whitespace-nowrap",onClick:F=>{F.stopPropagation(),a(C.evidenceId)},children:"View →"})]},C.evidenceId||`${h.id}-${P}`))})]},h.id)})});return m==="monitor"?e.jsxs("details",{className:"opportunity-card opportunity-card-monitor opportunity-monitor",children:[e.jsxs("summary",{className:"opportunity-monitor-summary",children:[e.jsxs("span",{children:[e.jsx("span",{className:"opportunity-card-title",children:d.title}),e.jsx("span",{className:"opportunity-card-subtitle mt-1 block",children:d.subtitle})]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"opportunity-card-count",children:f.length}),e.jsx(qs,{className:"opportunity-monitor-icon text-muted",size:14,"aria-hidden":"true"})]})]}),R]},m):e.jsxs("div",{className:`opportunity-card opportunity-card-${m}`,children:[e.jsxs("div",{className:"opportunity-card-head",children:[e.jsx("p",{className:"opportunity-card-title",children:d.title}),e.jsx("span",{className:"opportunity-card-count",children:f.length})]}),e.jsx("p",{className:"opportunity-card-subtitle",children:d.subtitle}),R]},m)}),o&&e.jsx(Uc,{suggestedQueries:s,projectName:n})]})}function Uc({suggestedQueries:t,projectName:s}){const n=ao(),[a,i]=l.useState(new Set),r=f=>{i(d=>new Set(d).add(f)),n.mutate({projectName:s,queries:[f]},{onSuccess:()=>{K({tone:"positive",title:`Tracking "${f}"`}),i(d=>{const R=new Set(d);return R.delete(f),R})},onError:d=>{K({tone:"negative",title:`Couldn't add "${f}"`,detail:String(d)}),i(R=>{const h=new Set(R);return h.delete(f),h})}})},{rows:o,totalCandidates:p,skippedAlreadyTracked:x}=t,m=x>0?`GSC queries you're getting impressions for · ${x} already tracked`:"GSC queries you're getting impressions for but aren't tracking yet";return e.jsxs("div",{className:"opportunity-card opportunity-card-track",children:[e.jsxs("div",{className:"opportunity-card-head",children:[e.jsx("p",{className:"opportunity-card-title",children:"Track new queries"}),e.jsx("span",{className:"opportunity-card-count",children:p>o.length?`${o.length} of ${p}`:o.length})]}),e.jsx("p",{className:"opportunity-card-subtitle",children:m}),e.jsx("div",{className:"opportunity-card-list",children:o.map(f=>{const d=a.has(f.query);return e.jsxs("div",{className:"opportunity-item opportunity-item-neutral flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium text-heading leading-snug truncate",title:f.query,children:f.query}),e.jsx("p",{className:"text-[11px] text-muted mt-0.5 leading-snug",children:f.reason})]}),e.jsx("button",{type:"button",className:"suggested-query-add",disabled:d,onClick:()=>r(f.query),children:d?"Adding…":"+ Track"})]},f.query)})})]})}function td(t){const{projectName:s}=ii({from:"/projects/$projectName"}),a=Ur()?.dashboard.projects.find(d=>d.project.name===s||d.project.id===s)?.project.name??null,i=Ie({...zr({client:Z}),enabled:!a}),r=a??i.data?.find(d=>d.name===s||d.id===s)?.name??null,{commandCenter:o,isLoading:p,refetch:x}=Kr(r),m=!a&&i.isLoading||p;return!r&&!a&&i.isSuccess&&!p?e.jsx("div",{className:"page-container",children:e.jsxs(W,{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(D,{asChild:!0,children:e.jsx(yt,{to:"/",children:"Return to overview"})})]})}):!o||m?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(d=>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"})]},d))}),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(d=>e.jsx("div",{className:"skeleton-text-sm w-full"},d))})]})]}):e.jsx(Kc,{model:o,refetch:x,...t})}function zc({items:t,activeTab:s}){const[n,a]=l.useState(!1),i=l.useRef(null);if(l.useEffect(()=>{if(!n)return;const o=x=>{i.current&&!i.current.contains(x.target)&&a(!1)},p=x=>{x.key==="Escape"&&a(!1)};return document.addEventListener("pointerdown",o),document.addEventListener("keydown",p),()=>{document.removeEventListener("pointerdown",o),document.removeEventListener("keydown",p)}},[n]),t.length===0)return null;const r=t.some(o=>o.key===s);return e.jsxs("div",{className:"project-subnav-more",ref:i,children:[e.jsxs("button",{type:"button",className:`project-subnav-link project-subnav-more-trigger ${r?"project-subnav-link-active":""}`,"aria-haspopup":"menu","aria-expanded":n,onClick:()=>a(o=>!o),children:["More",e.jsx(qs,{className:"h-3.5 w-3.5","aria-hidden":"true"})]}),n?e.jsx("div",{className:"project-subnav-menu",role:"menu",children:t.map(o=>e.jsx(yt,{to:o.href,role:"menuitem",className:`project-subnav-menu-item ${o.key===s?"project-subnav-menu-item-active":""}`,"aria-current":o.key===s?"page":void 0,onClick:()=>a(!1),children:o.label},o.key))}):null]})}function Kc({tab:t,model:s,refetch:n}){const a=ri(),i=vt(),r=l.useMemo(()=>Qr()?.projectTabs,[]),o=Hr(t,r),p=l.useMemo(()=>s.competitors.map(g=>g.domain),[s.competitors]),[x,m]=l.useState(!1),[f,d]=l.useState(!1),[R,h]=l.useState(!1),[A,w]=l.useState(""),[C,P]=l.useState(!1),[F,M]=l.useState(null),[_,u]=l.useState(!1),[S,Q]=l.useState(""),[v,U]=l.useState(!1),[L,N]=l.useState(!1),[E,O]=l.useState(""),[se,he]=l.useState(!1),[ye,pe]=l.useState(!1),[ge,Y]=l.useState(""),[de,fe]=l.useState(!1),[b,q]=l.useState(void 0),[X,le]=l.useState(!1),[ce,$e]=l.useState(null),[$,H]=l.useState(null),[Te,je]=l.useState(!1),ve=s?.visibilityEvidence??[],ne=s?.project.name??"",G=s?.project.displayName||s?.project.name||ne,z=Wr(),ue=(s?.recentRuns??[]).some(g=>g.kind===xs["answer-visibility"]&&(g.status===Gn.running||g.status===Gn.queued)),xe=l.useMemo(()=>(s?.project.locations??[]).map(g=>g.label),[s?.project.locations]),y=l.useMemo(()=>new Set(ve.map(g=>g.location??"")),[ve]),I=y.has(""),Le=l.useMemo(()=>[...new Set(ve.map(g=>g.query))].sort((g,J)=>g.localeCompare(J)),[ve]),Be=l.useMemo(()=>{const g=[...y].filter(Boolean);return g.length>1?g:xe},[y,xe]);l.useEffect(()=>{if(b===void 0||b===""||!ne){H(null),je(!1);return}je(!0),Vr(ne,b).then(g=>{H(g),je(!1)}).catch(()=>{H(null),je(!1)})},[b,ne]);const we=l.useMemo(()=>{if(!$)return null;const g=new Map;for(const J of $){for(const[ee,Ee]of Object.entries(J.providerRuns??{}))g.set(`${J.query}::${ee}`,Ee.map(ke=>({runId:ke.runId,citationState:ke.citationState,createdAt:ke.createdAt,answerMentioned:ke.answerMentioned,visibilityState:ke.visibilityState,visibilityTransition:ke.visibilityTransition,mentionState:ke.mentionState,mentionTransition:ke.mentionTransition})));(!J.providerRuns||Object.keys(J.providerRuns).length===0)&&g.set(`${J.query}::`,J.runs.map(ee=>({runId:ee.runId,citationState:ee.citationState,createdAt:ee.createdAt,answerMentioned:ee.answerMentioned,visibilityState:ee.visibilityState,visibilityTransition:ee.visibilityTransition,mentionState:ee.mentionState,mentionTransition:ee.mentionTransition})))}return g},[$]),Nt=l.useMemo(()=>{let g=b!==void 0?ve.filter(J=>b===""?!J.location:J.location===b):ve;if(ce){const J=ce.toLowerCase();g=g.filter(ee=>ee.competitorDomains.some(Ee=>Ee.toLowerCase()===J))}return we?g.map(J=>{const ee=we.get(`${J.query}::${J.provider}`)??we.get(`${J.query}::`);return ee?{...J,runHistory:ee}:J}):g},[ve,b,ce,we]);async function xt(){try{await z.mutateAsync({projectName:ne,projectLabel:G,sourceAction:"project-run"}),n()}catch{}}async function We(){d(!0);try{await Yr(ne),K({title:"Project deleted",detail:`${G} was removed.`,tone:"positive",dedupeKey:`project:delete:${ne}`,dedupeMode:"drop"}),a({to:"/"}),n()}catch(g){console.error("Failed to delete project:",g)}finally{d(!1)}}async function wt(){try{const g=await Xr(ne),J=typeof g=="string"?g:JSON.stringify(g,null,2),ee=new Blob([J],{type:"text/yaml"}),Ee=URL.createObjectURL(ee),ke=document.createElement("a");ke.href=Ee,ke.download=`${ne}.yaml`,ke.click()}catch(g){K({title:"Export failed",detail:g instanceof Error?g.message:"Could not export project YAML.",tone:"negative"})}}async function _e(){const g=A.split(`
|
|
6
|
+
`).map(J=>J.trim()).filter(Boolean);if(g.length!==0){P(!0);try{await so(ne,g),n(),w("")}finally{P(!1)}}}async function st(g){M(g);try{await to(ne,[g]),n()}catch(J){K({title:"Could not remove query",detail:J instanceof Error?J.message:`Failed to remove "${g}"`,tone:"negative",dedupeKey:"query:remove",dedupeMode:"replace"})}finally{M(null)}}async function nt(){const g=S.trim();if(g){U(!0);try{await Zr(ne,[g]),await i.invalidateQueries({queryKey:["analytics-metrics",ne]}),n(),Q(""),u(!1)}finally{U(!1)}}}async function Lt(g){const J=s.competitors.find(ee=>ee.domain===g);if(!J){K({title:"Could not remove competitor",detail:`Could not find ${g} in the tracked competitor list`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"});return}try{await eo(ne,J.id),await i.invalidateQueries({queryKey:["analytics-metrics",ne]}),n()}catch(ee){K({title:"Could not remove competitor",detail:ee instanceof Error?ee.message:`Failed to remove ${J.domain}`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"})}}async function St(){const g=E.trim();if(g){he(!0);try{const J=s?.project.ownedDomains??[];await qn(ne,[...J,g]),n(),O(""),N(!1)}finally{he(!1)}}}async function es(g){he(!0);try{const J=s?.project.ownedDomains??[];await qn(ne,J.filter(ee=>ee!==g)),n()}finally{he(!1)}}async function Pe(){const g=ge.trim();if(g){fe(!0);try{const J=s?.project.aliases??[],ee=g.toLowerCase();if(J.some(Ee=>Ee.toLowerCase()===ee)){Y(""),pe(!1);return}await _n(ne,[...J,g]),n(),Y(""),pe(!1)}finally{fe(!1)}}}async function ts(g){fe(!0);try{const J=s?.project.aliases??[];await _n(ne,J.filter(ee=>ee!==g)),n()}finally{fe(!1)}}async function Fe(g,J){await no(g,J),await i.invalidateQueries({queryKey:Na({client:Z})})}const He=`/projects/${encodeURIComponent(s.project.name)}`,kt=[{key:"overview",label:"Overview",href:He},{key:"search-console",label:"Search Engines",href:`${He}/search-console`},{key:"activity",label:"Activity",href:`${He}/activity`},{key:"technical-aeo",label:"Technical AEO",href:`${He}/technical-aeo`},{key:"local",label:"Local Presence",href:`${He}/local`},{key:"discovery",label:"Query Discovery",href:`${He}/discovery`},{key:"backlinks",label:"Backlinks",href:`${He}/backlinks`}],ht=[{key:"report",label:"Report",href:`${He}/report`}],ss=kt.filter(g=>Ws(g.key,r)),bs=ht.filter(g=>Ws(g.key,r)),it=Ws("settings",r)?{key:"settings",label:"Settings",href:`${He}/settings`}:null;function Me(g,J=!1){const ee=document.getElementById(g);if(!ee)return;J&&ee instanceof HTMLDetailsElement&&(ee.open=!0);const Ee=window.matchMedia("(prefers-reduced-motion: reduce)").matches;window.requestAnimationFrame(()=>{ee.scrollIntoView({behavior:Ee?"auto":"smooth",block:"start"}),(ee instanceof HTMLDetailsElement?ee.querySelector("summary"):ee)?.focus({preventScroll:!0})})}return e.jsxs("div",{className:"page-container",children:[x?e.jsxs(W,{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(D,{type:"button",variant:"destructive",disabled:f,onClick:ae(We),children:f?"Deleting...":"Yes, delete project"}),e.jsx(D,{type:"button",variant:"outline",disabled:f,onClick:()=>m(!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,!T()&&(s.project.ownedDomains??[]).length===0&&!L&&e.jsx("button",{type:"button",className:"ml-2 rounded px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-secondary hover:text-strong hover:bg-surface-inset transition-colors",onClick:()=>N(!0),children:"+ add domain"})," "," · ",s.contextLabel]}),!T()&&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(g=>e.jsx("span",{className:"tag",children:g},g))]}),((s.project.ownedDomains??[]).length>0||L)&&e.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted mr-1",children:"Also tracking"}),(s.project.ownedDomains??[]).map(g=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-strong/60 bg-surface-inset-hover px-2 py-0.5 text-xs text-neutral",children:[g,!T()&&e.jsx("button",{type:"button",className:"-mr-1 ml-0.5 inline-flex items-center justify-center rounded p-1 leading-none text-muted hover:bg-mono-700/40 hover:text-strong transition-colors",disabled:se,onClick:()=>{es(g)},"aria-label":`Remove ${g}`,children:"×"})]},g)),T()?null:L?e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx("input",{className:"rounded border border-strong bg-transparent px-1.5 py-0.5 text-xs text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none w-40",type:"text",placeholder:"docs.example.com",value:E,onChange:g=>O(g.target.value),onKeyDown:g=>{g.key==="Enter"&&St()},autoFocus:!0}),e.jsx(D,{type:"button",size:"sm",disabled:!E.trim()||se,onClick:ae(St),children:se?"...":"Add"}),e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-neutral",onClick:()=>{N(!1),O("")},children:"Cancel"})]}):e.jsx("button",{type:"button",className:"rounded-full border border-dashed border-strong px-2 py-0.5 text-[10px] uppercase tracking-wide text-muted hover:text-neutral hover:border-mono-500 transition-colors",onClick:()=>N(!0),children:"+ domain"})]}),(!T()||(s.project.aliases??[]).length>0)&&e.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] uppercase tracking-wide text-muted mr-1",children:["Also known as",e.jsx(De,{text:"Extra brand names checked against LLM answer text alongside the project name. Use for product names, prior names, or DBAs (e.g. add Meta as an alias to facebook.com). Changing these recomputes mentions on historical runs."})]}),(s.project.aliases??[]).map(g=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-strong/60 bg-surface-inset-hover px-2 py-0.5 text-xs text-neutral",children:[g,!T()&&e.jsx("button",{type:"button",className:"-mr-1 ml-0.5 inline-flex items-center justify-center rounded p-1 leading-none text-muted hover:bg-mono-700/40 hover:text-strong transition-colors",disabled:de,onClick:()=>{ts(g)},"aria-label":`Remove ${g}`,children:"×"})]},g)),T()?null:ye?e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx("input",{className:"rounded border border-strong bg-transparent px-1.5 py-0.5 text-xs text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none w-40",type:"text",placeholder:"LlamaParse",value:ge,onChange:g=>Y(g.target.value),onKeyDown:g=>{g.key==="Enter"&&Pe()},autoFocus:!0}),e.jsx(D,{type:"button",size:"sm",disabled:!ge.trim()||de,onClick:ae(Pe),children:de?"...":"Add"}),e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-neutral",onClick:()=>{pe(!1),Y("")},children:"Cancel"})]}):e.jsx("button",{type:"button",className:"rounded-full border border-dashed border-strong px-2 py-0.5 text-[10px] uppercase tracking-wide text-muted hover:text-neutral hover:border-mono-500 transition-colors",onClick:()=>pe(!0),children:"+ alias"})]})]}),e.jsxs("div",{className:"page-header-right",children:[e.jsx("p",{className:"text-sm text-muted",children:s.dateRangeLabel}),!T()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(D,{type:"button",variant:"outline",size:"icon",onClick:ae(wt),"aria-label":"Export project as YAML",children:e.jsx(Gt,{className:"h-4 w-4 text-secondary"})}),e.jsx(D,{type:"button",variant:"outline",size:"icon",onClick:()=>m(!0),"aria-label":"Delete project",children:e.jsx(vo,{className:"h-4 w-4 text-secondary"})}),e.jsx(D,{type:"button",disabled:z.isPending||ue,onClick:ae(xt),children:z.isPending?"Starting…":ue?"Sweep running…":"Run now"})]})]})]}),e.jsxs("nav",{className:"project-subnav","aria-label":"Project sections",children:[ss.map(g=>e.jsx(yt,{to:g.href,className:`project-subnav-link ${g.key===o?"project-subnav-link-active":""}`,"aria-current":g.key===o?"page":void 0,children:g.label},g.key)),e.jsxs("div",{className:"project-subnav-trailing",children:[e.jsx(zc,{items:bs,activeTab:o}),it&&e.jsx(yt,{to:it.href,className:`project-subnav-link ${o==="settings"?"project-subnav-link-active":""}`,"aria-current":o==="settings"?"page":void 0,children:it.label},it.key)]})]}),o==="overview"?e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"page-section-divider",children:e.jsx(nc,{projectName:s.project.name,competitorDomains:p,visibilityEvidence:s.visibilityEvidence})}),e.jsx(Fc,{model:s,sweepRunning:ue,onJumpToEvidence:()=>Me("evidence-section",!0),onJumpToActions:()=>Me("action-queue")}),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"]}),!T()&&e.jsx(D,{type:"button",variant:"outline",size:"sm",onClick:()=>u(!_),children:_?"Cancel":"+ Add competitor"})]})]}),e.jsxs("div",{className:"aeo-hero competitive-summary",children:[e.jsxs("div",{className:"aeo-hero-rows",children:[e.jsx(us,{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(us,{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(us,{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(Gc,{summary:s.mentionShareSummary,projectLabel:s.project.displayName||s.project.name})]}),_&&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:S,onChange:g=>Q(g.target.value),onKeyDown:g=>{g.key==="Enter"&&nt()}}),e.jsx(D,{type:"button",size:"sm",disabled:!S.trim()||v,onClick:ae(nt),children:v?"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(Ko,{competitors:s.competitors,onSelectCompetitor:g=>{$e(g),Me("evidence-section",!0)},onRemoveCompetitor:T()?void 0:g=>{Lt(g)},activeFilter:ce})})]})]}),e.jsxs(dn,{id:"evidence-section",eyebrow:"Tracked coverage",title:"Query evidence",meta:`${s.queryCounts.total} ${s.queryCounts.total===1?"query":"queries"}`,defaultOpen:T(),children:[!T()&&e.jsx("div",{className:"mb-3 flex items-center justify-end",children:e.jsx(D,{type:"button",variant:"outline",size:"sm",onClick:()=>h(!R),children:R?"Done":"Manage queries"})}),!T()&&R&&e.jsxs("div",{className:"mb-3 rounded-lg border border-base bg-bg-elevated/40 p-3",children:[Le.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:Le.map(g=>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:g,children:g}),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 ${g}`,title:`Stop tracking "${g}"`,disabled:F!==null,onClick:()=>{st(g)},children:F===g?"Removing…":"Remove"})]},g))}):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:A,onChange:g=>w(g.target.value)}),e.jsxs("div",{className:"mt-2 flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-muted",children:[A.split(`
|
|
7
|
+
`).filter(g=>g.trim()).length," to add"]}),e.jsx(D,{type:"button",size:"sm",disabled:!A.trim()||C,onClick:ae(_e),children:C?"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:()=>{q(void 0)},children:"All locations"}),s.project.locations.map(g=>e.jsx("button",{className:`filter-chip ${b===g.label?"filter-chip-active":""}`,type:"button","aria-pressed":b===g.label,onClick:()=>{q(g.label),le(!1)},children:g.label},g.label)),I&&e.jsx("button",{className:`filter-chip ${b===""?"filter-chip-active":""}`,type:"button","aria-pressed":b==="",onClick:()=>{q(""),le(!1)},children:"No location"}),Be.length>1&&b===void 0&&e.jsx("button",{className:`filter-chip filter-chip-compare ${X?"filter-chip-active":""}`,type:"button","aria-pressed":X,onClick:()=>le(g=>!g),title:"Side-by-side location comparison",children:"Compare"})]}),ce&&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:ce})," surfaced"]}),e.jsx("button",{type:"button",className:"ml-auto text-xs text-secondary hover:text-strong",onClick:()=>$e(null),children:"Clear filter ×"})]}),e.jsx(qo,{evidence:Nt,compareLocations:X})]}),e.jsxs(dn,{eyebrow:"Analysis",title:"Citation and engine diagnostics",meta:"Deep dive",defaultOpen:T(),children:[e.jsx(Il,{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(De,{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(g=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"flex flex-col items-start gap-0.5",children:[e.jsx(Qt,{provider:g.provider}),g.model&&e.jsx("span",{className:"text-[11px] font-mono text-muted",children:g.model})]})}),e.jsx("td",{children:e.jsxs("span",{className:"font-semibold text-strong",children:[g.score,"%"]})}),e.jsxs("td",{className:"text-muted",children:[g.cited," of ",g.total]})]},`${g.provider}::${g.model??"unknown"}`))})]})})]})]}),!T()&&e.jsx(dn,{eyebrow:"Run history",title:"Recent execution history",meta:`${s.recentRuns.length} recent`,children:e.jsx("div",{className:"run-list",children:s.recentRuns.map(g=>e.jsx(ho,{run:g},g.id))})}),e.jsxs("section",{id:"action-queue",className:"page-section-divider scroll-mt-24 rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",tabIndex:-1,children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Action queue"}),e.jsx("h2",{children:"What needs your attention"})]})}),e.jsx(_c,{insights:s.insights,suggestedQueries:s.suggestedQueries,projectName:ne})]})]}):o==="settings"?e.jsxs(e.Fragment,{children:[e.jsx(Lc,{project:{...s.project,displayName:s.project.displayName??s.project.name,defaultLocation:s.project.defaultLocation??null},onUpdateProject:Fe,onRefresh:()=>{n()}}),e.jsx(Rc,{projectName:s.project.name}),e.jsx(Mc,{projectName:s.project.name})]}):o==="report"?e.jsx(pc,{projectName:s.project.name}):o==="discovery"?e.jsx(ac,{projectName:ne}):o==="technical-aeo"?e.jsx(uc,{projectName:s.project.name}):o==="activity"?e.jsx(Yo,{projectName:s.project.name}):o==="backlinks"?e.jsx(Ll,{projectName:s.project.name}):o==="local"?e.jsx(ll,{projectName:s.project.name,projectId:s.project.id}):e.jsx(Oc,{projectName:s.project.name})]})}export{td as ProjectPage};
|