@ainyc/canonry 4.116.0 → 4.117.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/README.md +0 -1
- package/assets/agent-workspace/skills/aero/references/reporting.md +10 -0
- package/assets/agent-workspace/skills/canonry/references/canonry-cli.md +6 -0
- package/assets/assets/{BacklinksPage-Dy6Xc-LT.js → BacklinksPage-Bkafm10m.js} +1 -1
- package/assets/assets/{ChartPrimitives-CHJh5M8x.js → ChartPrimitives-NV_GgqFn.js} +1 -1
- package/assets/assets/{ProjectPage-Bjfa4CI5.js → ProjectPage-0-NnRxys.js} +1 -1
- package/assets/assets/{RunRow-DmvQnWPf.js → RunRow-df0d24S6.js} +1 -1
- package/assets/assets/{RunsPage-BxkxQEKE.js → RunsPage-CU6-4YTM.js} +1 -1
- package/assets/assets/{SettingsPage-DCyqHqDh.js → SettingsPage-BKw6B6cd.js} +1 -1
- package/assets/assets/{TrafficPage-BT_ae5aO.js → TrafficPage-CzpiYHKj.js} +1 -1
- package/assets/assets/{TrafficSourceDetailPage-Cps-tSHn.js → TrafficSourceDetailPage-CC5nuqM1.js} +1 -1
- package/assets/assets/{arrow-left-D8vdqhx4.js → arrow-left-CbQcW2pL.js} +1 -1
- package/assets/assets/{extract-error-message-BOY5txUA.js → extract-error-message-CvqIZ-le.js} +1 -1
- package/assets/assets/index-LjcWHaNZ.js +210 -0
- package/assets/assets/{trash-2-ap_Fa4zA.js → trash-2-3J2u0woR.js} +1 -1
- package/assets/index.html +1 -1
- package/dist/{chunk-WEAXJ25Y.js → chunk-FVVKNMZW.js} +353 -19
- package/dist/{chunk-IQPMK36Y.js → chunk-IAJ5TQ4S.js} +155 -3
- package/dist/{chunk-RVH6QPTA.js → chunk-PJATAPZW.js} +37 -1
- package/dist/{chunk-GV665WOU.js → chunk-ZZEA774R.js} +4 -4
- package/dist/cli.js +93 -4
- package/dist/index.js +4 -4
- package/dist/{intelligence-service-HEN5HLUM.js → intelligence-service-J7G4CMI5.js} +2 -2
- package/dist/mcp.js +2 -2
- package/package.json +9 -9
- package/assets/assets/index-DxjY63VC.js +0 -210
|
@@ -1,4 +1,4 @@
|
|
|
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}
|
|
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-LjcWHaNZ.js";import{R as ho}from"./RunRow-df0d24S6.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-NV_GgqFn.js";import{u as fo,t as bo,R as dt,e as zn}from"./extract-error-message-CvqIZ-le.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-3J2u0woR.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
2
|
Clicks: ${be.clicks}
|
|
3
3
|
Impressions: ${be.impressions}
|
|
4
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(`
|