@ainyc/canonry 4.112.1 → 4.112.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/assets/BacklinksPage-D00sAx6q.js +1 -0
- package/assets/assets/{ChartPrimitives-DlR18JC8.js → ChartPrimitives-BjcDtBSv.js} +1 -1
- package/assets/assets/{ProjectPage-YPn3c4hw.js → ProjectPage-DVED6lF7.js} +1 -1
- package/assets/assets/{RunRow-CSbZ7ZRo.js → RunRow-Chc7eyZU.js} +1 -1
- package/assets/assets/RunsPage-DQ8ip0Tf.js +1 -0
- package/assets/assets/SettingsPage-CZokCKF4.js +1 -0
- package/assets/assets/{TrafficPage-CbHemY4N.js → TrafficPage-C0nEB9tv.js} +1 -1
- package/assets/assets/TrafficSourceDetailPage-CKsWe8kA.js +1 -0
- package/assets/assets/{arrow-left-DXeXxwzj.js → arrow-left-CeWmJYLI.js} +1 -1
- package/assets/assets/{extract-error-message-nw2axb0s.js → extract-error-message-b-rZowjX.js} +1 -1
- package/assets/assets/{index-BERU9Kvl.css → index-D01sTTr1.css} +1 -1
- package/assets/assets/{index-Cg-EISGh.js → index-DB_F_WFv.js} +52 -52
- package/assets/assets/{trash-2-DhPiFFSU.js → trash-2-6CLXNfZm.js} +1 -1
- package/assets/index.html +2 -2
- package/package.json +9 -9
- package/assets/assets/BacklinksPage-B8Vtj78r.js +0 -1
- package/assets/assets/RunsPage-CSo26DbG.js +0 -1
- package/assets/assets/SettingsPage-Dxdr95It.js +0 -1
- package/assets/assets/TrafficSourceDetailPage-BxMqtq8o.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{j as e,r,L as ft,n as yt,u as Pe,o as os,A as Xa,B as Ja,h as Za}from"./vendor-tanstack-Be8JdV5M.js";import{c as Ts,T as ae,t as ei,a as ti,u as la,C as si,b as Is,P as Ht,B as L,h as ni,d as ai,e as ii,f as Je,g as W,i as ee,I as ke,j as ss,k as ri,l as K,m as li,n as oi,o as ci,p as di,q as oa,r as ui,s as mi,S as $t,v as xi,w as hi,x as pi,y as Bt,z as gi,A as Pn,D as fi,G as Re,E as xn,F as bi,H as ji,J as yi,K as vi,L as Ni,M as re,N as Ln,O as ca,Q as wi,R as Si,U as ki,V as Ci,W as Ai,X as $i,Y as Pi,Z as Li,_ as zi,$ as Di,a0 as Ti,a1 as Ii,a2 as Ri,a3 as Ei,a4 as Mi,a5 as Oi,a6 as cs,a7 as Fi,a8 as Bi,a9 as zn,aa as qi,ab as Gi,ac as _i,ad as Ui,ae as Ps,af as Qi,ag as Ki,ah as Hi,ai as Wi,aj as ln,ak as Vi,al as Yi,am as Xi,an as Ji,ao as Us,ap as Ut,aq as da,ar as ua,as as Zi,at as er,au as hn,av as tr,aw as ma,ax as sr,ay as nr,az as ar,aA as ir,aB as xa,aC as rr,aD as ha,aE as lr,aF as or,aG as cr,aH as dr,aI as Rs,aJ as ur,aK as mr,aL as xr,aM as hr,aN as pr,aO as gr,aP as fr,aQ as br,aR as jr,aS as yr,aT as vr,aU as Nr,aV as wr,aW as Sr,aX as kr,aY as Cr,aZ as Ar,a_ as $r,a$ as Pr,b0 as Qs,b1 as Lr,b2 as zr,b3 as Dn,b4 as Dr,b5 as Tr,b6 as Ir,b7 as Rr,b8 as Er,b9 as Mr,ba as Or,bb as Fr,bc as Br,bd as qr,be as Gr,bf as _r,bg as Tn,bh as Ur,bi as Ks,bj as Qr,bk as In,bl as Rn,bm as Kr,bn as Hr,bo as Wr,bp as Vr,bq as Yr,br as Xr,bs as Jr,bt as Zr,bu as el,bv as tl,bw as pa,bx as ga,by as sl,bz as fa,bA as nl,bB as ba,bC as al,bD as il,bE as js,bF as rl,bG as ll,bH as ol,bI as En}from"./index-Cg-EISGh.js";import{R as cl}from"./RunRow-CSbZ7ZRo.js";import{f as Pt,C as et,a as _e,b as jt,c as ct,d as qe,e as Qe,g as bt,h as dl,i as Es,p as ul}from"./ChartPrimitives-DlR18JC8.js";import{u as ml,t as xl,R as Ls,e as hl}from"./extract-error-message-nw2axb0s.js";import{R as Lt,C as zt,X as Dt,Y as Tt,T as It,L as ja,A as qt,a as Ms,b as pl,d as Os}from"./vendor-recharts-C9EZkgbP.js";import{C as ya,D as rs,a as gl,T as fl}from"./trash-2-DhPiFFSU.js";import"./vendor-radix-CQ77EO2y.js";import"./vendor-markdown-6dwjPOKK.js";const bl=[["path",{d:"M5 12h14",key:"1ays0h"}]],jl=Ts("minus",bl);const yl=[["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"}]],vl=Ts("scan-search",yl);const Nl=[["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"}]],wl=Ts("unplug",Nl);const Sl=[["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"}]],kl=Ts("upload",Sl),Cl=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function va(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function Na(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 wa(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(va).map(Na).filter(Boolean)):new Set}function Sa(t,s){const n=va(t).map(Na).filter(Boolean).filter(a=>!Cl.has(a)).filter(a=>!s.has(a));return[...new Set(n)].sort().join(" ")}function Al(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function $l(t,s){const n=wa(t);if(s.length<=1||n.size===0)return[...s];const a=new Set,i=[];for(const l of s){if(l.category!=="content"){i.push(l);continue}const o=Sa(Al(l),n);!o||a.has(o)||(a.add(o),i.push(l))}return i}function Pl(t){const s=wa(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const a=new Set;return n.filter(i=>{const l=Sa(i.query,s);return!l||a.has(l)?!1:(a.add(l),!0)})}function Cs(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 Ll(t,s){return s<=0?null:Math.round((t-s)/s*100)}function Hs(t,s,n="vs prior 7 days"){return t.deltaPct===null?t.prior===0?"First baseline week":"":t.deltaPct>0?`Up ${t.deltaPct}% ${n} (${Cs(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${Cs(t.prior)} ${s})`:`Flat ${n} (${Cs(t.prior)} ${s})`}const ka=30;function Mn(t){return Math.round(t*10)/10}function zl(t){return t.prior>=ka&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% vs prior`:`${t.deltaAbs>0?"+":""}${Mn(t.deltaAbs)} vs ${Mn(t.prior)}`}function Dl(t,s,n){return t.prior>=ka&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% ${n}`:`${t.deltaAbs>0?"+":""}${Cs(Math.round(t.deltaAbs))} ${s} ${n}`}function on({state:t,label:s}){return e.jsx(ae,{tone:ti(t),children:s??ei(t)})}function On({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"}),l=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:l})]})}function cn(t){const s=new Map;for(const a of t)for(const i of a.runHistory){const l=s.get(i.createdAt);l?l.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:l}])=>({runId:l,createdAt:a,citationState:i.includes("cited")?"cited":i.includes("emerging")?"emerging":"not-cited"}))}const Tl=320;function Fn(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 Bn(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 qn(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,l=t[t.length-2].citationState;if(l!=="cited"&&i==="cited")return`Newly ${n}`;if(l==="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 Il(t,s){return t.map(n=>Ca(n,s))}function Ca(t,s){return s==="citations"?t:{...t,citationState:Fn(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:Fn(n,s)}))}}function Gn(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,l=t.length>=2?t[t.length-2].citationState:null,o=i==="cited"||i==="emerging",p=l==="cited"||l==="emerging";return i==="lost"||l!==null&&p&&!o?{key:s,label:`Lost ${n}`,tone:"negative"}:i==="emerging"||l!==null&&!p&&o?{key:s,label:`New ${n}`,tone:"positive"}:l===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 Rl(t){const s=cn(Il(t,"mentions")),n=cn(t);return[Gn(s,"mentions"),Gn(n,"citations")]}function El({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 _n({items:t}){return e.jsx("div",{className:"mt-1 flex flex-wrap gap-1","aria-label":"Latest run mention and citation signals",children:Rl(t).map(s=>e.jsx(El,{signal:s},s.key))})}function Ml({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:a}=la(),[i,l]=r.useState(new Set),[o,p]=r.useState("mentions"),[g,u]=r.useState(n),m=r.useMemo(()=>{const v=new Map;for(const C of t){const z=C.query,R=s?C.location??null:null,I=s?JSON.stringify([z,R]):z,N=v.get(I)??{key:I,phrase:z,location:R,items:[],rawItems:[]};N.items.push(Ca(C,o)),N.rawItems.push(C),v.set(I,N)}return[...v.values()]},[t,o,s]),d=v=>{l(C=>{const z=new Set(C);return z.has(v)?z.delete(v):z.add(v),z})},P=o==="mentions"?"mentioned":"cited",b=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:()=>{l(v=>v.size===m.length?new Set:new Set(m.map(C=>C.key)))},children:i.size===m.length&&m.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":g==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${g==="compact"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>u("compact"),children:"Compact"}),e.jsx("button",{type:"button",role:"tab","aria-selected":g==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${g==="detailed"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>u("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:b}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:m.map(({key:v,phrase:C,location:z,items:R,rawItems:I})=>{const N=i.has(v),j=R.map(T=>T.citationState),x=j.includes("cited")?"cited":j.includes("emerging")?"emerging":j.includes("lost")?"lost":j.every(T=>T==="pending")?"pending":"not-cited",E=cn(R),_=R.filter(T=>T.citationState===si.cited||T.citationState==="emerging").length,H=qn(E,o);return e.jsxs(r.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(v),onKeyDown:T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),d(v))},tabIndex:0,role:"button","aria-expanded":N,children:[e.jsx("td",{children:e.jsx(Is,{size:14,className:`transition-transform duration-150 text-muted ${N?"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:z??"No location"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:R.map(T=>e.jsx(Ht,{provider:T.provider},T.id))})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(on,{state:x,label:Bn(x,o)}),e.jsxs("span",{className:"text-[11px] text-muted",title:`${_} of ${R.length} engines ${A}`,children:[_,"/",R.length]})]})}),e.jsx("td",{children:e.jsx(On,{history:E})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:H}),e.jsx(_n,{items:I})]}),e.jsx("td",{})]}),N&&R.map((T,S)=>e.jsxs(r.Fragment,{children:[e.jsxs("tr",{className:"bg-surface",children:[e.jsx("td",{}),e.jsx("td",{className:"evidence-query-cell pl-5",children:e.jsx(Ht,{provider:T.provider})}),e.jsx("td",{children:e.jsx(on,{state:T.citationState,label:Bn(T.citationState,o)})}),e.jsx("td",{children:e.jsx(On,{history:T.runHistory})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:qn(T.runHistory,o)}),e.jsx(_n,{items:[I[S]??T]})]}),e.jsx("td",{children:e.jsx(L,{variant:"ghost",size:"sm",type:"button",onClick:M=>{M.stopPropagation(),a(T.id)},children:"View"})})]}),g==="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(Bl,{item:T,onViewFull:()=>a(T.id)})})]})]},T.id))]},v)})})]})}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",P==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function Ol(t){const s=(t.matchedTerms??[]).filter(i=>i.trim().length>2),n=[...t.competitorDomains.flatMap(i=>{const l=ai(i);return l.length>=4?[l]:[]}),...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 Fl(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 Bl({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}=Fl(t.answerSnippet,Tl),l=Ol(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:ni(a,l)}),(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 ql({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,l=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"}),l&&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(),g=[i?"cursor-pointer hover:bg-mono-800/30 transition-colors":"",p?"bg-negative-950/20":""].filter(Boolean).join(" ");return e.jsxs("tr",{className:g,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(ae,{tone:ii(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"}),l&&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:u=>{u.stopPropagation(),n(o.domain)},children:"Remove"})})]},o.id)})})]})})}function Un({eyebrow:t,title:s,status:n,tone:a,targetLabel:i,targetValue:l,coverageValue:o,note:p,updatedAt:g,active:u,onClick:m}){return e.jsxs("button",{type:"button",onClick:m,className:`surface-card w-full text-left transition-colors ${u?"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(ae,{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:l})]}),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:g?`Updated ${Je(g)}`:"No recent sync yet"})]})]})}function ys({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 Gl=6,Wt="__other__",Qt="_socialTotal";function _l(t,s=Gl){const n=new Map;for(const m of t)n.set(m.source,(n.get(m.source)??0)+m.sessions);const a=[...n.entries()].sort((m,d)=>d[1]!==m[1]?d[1]-m[1]:m[0].localeCompare(d[0])),i=a.slice(0,s),l=new Set(i.map(([m])=>m)),o=Math.max(0,a.length-s),p=new Map;for(const m of t){let d=p.get(m.date);d||(d={date:m.date,[Qt]:0},p.set(m.date,d));const P=l.has(m.source)?m.source:Wt;d[P]=(d[P]??0)+m.sessions,d[Qt]=(d[Qt]??0)+m.sessions}const g=[...p.values()].sort((m,d)=>String(m.date).localeCompare(String(d.date))),u=i.map(([m])=>m);return o>0&&u.push(Wt),{data:g,sources:u,otherCount:o}}function Kt(t){return t.replace(/\+/g," ")}function Aa(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const Ul=["7d","30d","90d","all"],pt=Qe,dn=qe.textDim,$a=qe.textFaint,ns=25,vs=50;function Ns(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function Pa(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 Ql({projectName:t}){const{data:s,isLoading:n,isError:a}=ml(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."," ",e.jsx(ft,{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."," ",e.jsx(ft,{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(l=>e.jsxs("tr",{className:"border-t border-default",children:[e.jsx("td",{className:"px-4 py-3 text-heading",children:l.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(ae,{tone:xl(l.status),children:l.status})}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:l.totals24h.crawlerHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:l.totals24h.aiUserFetchHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:l.totals24h.aiReferralHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right text-secondary text-xs",children:l.lastSyncedAt?Pa(l.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsx(ft,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:l.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},l.id))})]})})]})}function Kl({projectName:t}){return e.jsxs("div",{className:"space-y-10",children:[e.jsx(Ql,{projectName:t}),e.jsx(Hl,{projectName:t})]})}function Hl({projectName:t}){const s=yt(),[n,a]=r.useState(null),[i,l]=r.useState(null),[o,p]=r.useState(!0),[g,u]=r.useState(!1),[m,d]=r.useState(!1),[P,b]=r.useState(null),[A,v]=r.useState(null),[C,z]=r.useState("sessions"),[R,I]=r.useState("desc"),[N,j]=r.useState("sessions"),[x,E]=r.useState("desc"),[_,H]=r.useState("sessions"),[T,S]=r.useState("desc"),[M,U]=r.useState("sessions"),[G,ne]=r.useState("desc"),[fe,ue]=r.useState(1),[pe,me]=r.useState([]),[he,je]=r.useState([]),[f,B]=r.useState([]),[te,le]=r.useState(!1),[de,Ce]=r.useState("30d");async function $(k){p(!0),b(null);try{const F=await s.fetchQuery({...ri({client:K,path:{name:t}}),staleTime:ss});if(k.current)return;if(a(F),!F.connected){l(null),me([]),je([]),B([]),p(!1);return}const Q=de==="all"?void 0:de,[Z,nt,Zt,we]=await Promise.all([s.fetchQuery({...li({client:K,path:{name:t},query:Q?{window:Q}:void 0}),staleTime:ss}).then(We=>We),s.fetchQuery({...oi({client:K,path:{name:t},query:Q?{window:Q}:void 0}),staleTime:ss}).catch(()=>[]),s.fetchQuery({...ci({client:K,path:{name:t},query:Q?{window:Q}:void 0}),staleTime:ss}).catch(()=>[]),s.fetchQuery({...di({client:K,path:{name:t},query:Q?{window:Q}:void 0}),staleTime:ss}).catch(()=>[])]);if(k.current)return;l(Z),me(nt),je(Zt),B(we),p(!1)}catch(F){if(k.current)return;b(F instanceof Error?F.message:"Failed to load GA4 data"),p(!1)}}r.useEffect(()=>{const k={current:!1};return $(k),()=>{k.current=!0}},[t,de,s]);async function V(){u(!0),b(null),v(null);try{const k=await oa(t);v(`Synced ${k.rowCount.toLocaleString()} page rows, ${k.aiReferralCount.toLocaleString()} AI and ${k.socialReferralCount.toLocaleString()} social referral rows (${k.days} days)`),await s.invalidateQueries({predicate:F=>{const Q=F.queryKey[0];return typeof Q?._id=="string"&&Q._id.startsWith("getApiV1ProjectsByNameGa")}}),await $({current:!1})}catch(k){b(k instanceof Error?k.message:"Sync failed")}finally{u(!1)}}async function Te(){d(!0),b(null),v(null);try{await ui(t),await s.invalidateQueries({predicate:k=>{const F=k.queryKey[0];return typeof F?._id=="string"&&F._id.startsWith("getApiV1ProjectsByNameGa")}}),a({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),l(null),v("GA4 disconnected")}catch(k){b(k instanceof Error?k.message:"Disconnect failed")}finally{d(!1)}}function be(k){C===k?I(F=>F==="desc"?"asc":"desc"):(z(k),I("desc"))}function ye(k){N===k?E(F=>F==="desc"?"asc":"desc"):(j(k),E("desc"))}function X(k){_===k?S(F=>F==="desc"?"asc":"desc"):(H(k),S("desc"))}function O(k){ue(1),M===k?ne(F=>F==="desc"?"asc":"desc"):(U(k),ne("desc"))}const q=r.useMemo(()=>i?.topPages?[...i.topPages].sort((k,F)=>{const Q=k[C],Z=F[C];return typeof Q=="string"&&typeof Z=="string"?R==="asc"?Q.localeCompare(Z):Z.localeCompare(Q):R==="asc"?Q-Z:Z-Q}):[],[i?.topPages,C,R]),ie=r.useMemo(()=>i?.aiReferrals?[...i.aiReferrals].sort((k,F)=>{const Q=k[N],Z=F[N];return typeof Q=="string"&&typeof Z=="string"?x==="asc"?Q.localeCompare(Z):Z.localeCompare(Q):x==="asc"?Q-Z:Z-Q}):[],[i?.aiReferrals,N,x]),oe=r.useMemo(()=>i?.aiReferralLandingPages?[...i.aiReferralLandingPages].sort((k,F)=>{const Q=k[M],Z=F[M];return typeof Q=="string"&&typeof Z=="string"?G==="asc"?Q.localeCompare(Z):Z.localeCompare(Q):G==="asc"?Q-Z:Z-Q}):[],[i?.aiReferralLandingPages,M,G]),y=Math.max(1,Math.ceil(oe.length/vs)),D=Math.min(Math.max(1,fe),y),Ae=(D-1)*vs,Oe=r.useMemo(()=>oe.slice(Ae,Ae+vs),[oe,Ae]),Ne=r.useMemo(()=>i?.socialReferrals?[...i.socialReferrals].sort((k,F)=>{const Q=k[_],Z=F[_];return typeof Q=="string"&&typeof Z=="string"?T==="asc"?Q.localeCompare(Z):Z.localeCompare(Q):T==="asc"?Q-Z:Z-Q}):[],[i?.socialReferrals,_,T]),{socialChartData:vt,socialChartSources:dt,socialOtherCount:Ke}=r.useMemo(()=>{const k=_l(f);return{socialChartData:k.data,socialChartSources:k.sources,socialOtherCount:k.otherCount}},[f]),{chartData:Nt,chartSources:Fe,dateRange:tt}=r.useMemo(()=>{const k=[...new Set(pe.map(we=>we.source))],F=new Map;for(const we of he)F.set(we.date,{_totalSessions:we.sessions,_organicSessions:we.organicSessions});const Q=new Map;for(const we of pe){const We=`${we.date}::${we.source}`,Et=Q.get(We)??0;Q.set(We,Math.max(Et,we.sessions))}for(const[we,We]of Q){const[Et,ut]=we.split("::");let at=F.get(Et);at||(at={_totalSessions:0,_organicSessions:0},F.set(Et,at)),at[ut]=(at[ut]??0)+We}const Z=[...F.entries()].sort(([we],[We])=>we.localeCompare(We)).map(([we,We])=>({date:we,...We})),nt=Z.map(we=>we.date),Zt=nt.length>0?{start:nt[0],end:nt[nt.length-1]}:null;return{chartData:Z,chartSources:k,dateRange:Zt}},[pe,he]);if(o&&!n)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!n?.connected)return e.jsx(Wl,{projectName:t,onConnected:()=>{(async()=>(await s.invalidateQueries({predicate:k=>{const F=k.queryKey[0];return typeof F?._id=="string"&&F._id.startsWith("getApiV1ProjectsByNameGa")}}),await $({current:!1})))()}});const st=i?.organicSharePctDisplay??"0%",Rt=i?.channelBreakdown?.organic.sharePctDisplay??st,wt=i?.channelBreakdown?.organic.sessions??i?.totalOrganicSessions??0,Vt=i?.aiSessionsDeduped??0,$e=i?.channelBreakdown?.ai.sessions??i?.aiSessionsBySession??0,Yt=i?.channelBreakdown?.ai.sharePctDisplay??i?.aiSharePctBySessionDisplay??"0%",Ue=i?new Set(i.aiReferrals.map(k=>k.source.toLowerCase())).size:0,Ee=ie[0]??null,St=i?.totalDirectSessions??0,Xt=i?.directSharePctDisplay??"0%",Jt=i?.channelBreakdown?.direct.sessions??St,us=i?.channelBreakdown?.direct.sharePctDisplay??Xt,it=i?.channelBreakdown?.other.sessions??i?.otherSessions??0,Ie=i?.channelBreakdown?.other.sharePctDisplay??i?.otherSharePctDisplay??"0%",h=i?.socialSessions??0,Y=i?.socialSharePctDisplay??"0%",se=i?.channelBreakdown?.social.sessions??h,Le=i?.channelBreakdown?.social.sharePctDisplay??Y,ve=i?new Set(i.socialReferrals.map(k=>k.source.toLowerCase())).size:0,He=Ne[0]??null;return e.jsxs(e.Fragment,{children:[P&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative",children:P}),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})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(L,{variant:"outline",size:"sm",disabled:g,onClick:ee(V),children:[e.jsx(Ls,{className:`w-3.5 h-3.5 mr-1.5 ${g?"animate-spin":""}`}),g?"Syncing…":"Sync"]}),e.jsxs(L,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:m,onClick:ee(Te),children:[e.jsx(wl,{className:"w-3.5 h-3.5 mr-1.5"}),"Disconnect"]})]})]}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4 flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Traffic Overview"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Site Traffic",e.jsx(ke,{text:`Aggregated traffic metrics from Google Analytics 4. Sessions and users are summed across the selected period.${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:Ul.map(k=>e.jsx("button",{type:"button",className:`px-3 py-1 text-xs rounded-full border transition-colors ${de===k?"bg-mono-700 border-mono-600 text-primary":"border-base text-secondary hover:border-strong hover:text-neutral"}`,onClick:()=>Ce(k),children:k==="all"?"All":k},k))})]}),i?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(Ws,{value:Ns(i.totalSessions),label:"Total Sessions",subtitle:i.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(Ws,{value:Ns(i.totalOrganicSessions),label:"Organic Sessions",subtitle:`${st} of total`,tone:"positive"}),e.jsx(Ws,{value:Ns(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."}),e.jsxs(L,{variant:"outline",size:"sm",disabled:g,onClick:ee(V),children:[e.jsx(Ls,{className:`w-3.5 h-3.5 mr-1.5 ${g?"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(ke,{text:"Decomposes GA4 sessions into five disjoint channels — known AI referrers first, then organic search, social, direct, and other channels. Known AI referrers are removed from their native GA4 channel before the residual Other bucket is computed. Other channels are the remaining GA4 session default channel groups, such as Referral, Email, Paid Search, Display, Cross-network, Shopping, Video, Affiliates, SMS, and Paid Other."})]})]}),tt&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(tt.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(tt.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),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",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:Fe.length>0?"AI vs. total sessions":"All sessions (baseline)"}),Fe.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),Fe.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(Lt,{width:"100%",height:"100%",children:e.jsxs(zt,{data:Nt,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Dt,{dataKey:"date",tick:_e,tickLine:!1,axisLine:{stroke:et},tickFormatter:Pt}),e.jsx(Tt,{tick:_e,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(It,{...ct,labelFormatter:jt,formatter:(k,F)=>{const Q=typeof k=="number"?k.toLocaleString():String(k??0),Z=String(F??"");return Z==="_totalSessions"?[Q,"Total Sessions"]:Z==="_organicSessions"?[Q,"Organic Sessions"]:[Q,Z]}}),e.jsx(ja,{wrapperStyle:{fontSize:11,color:qe.text},formatter:k=>k==="_totalSessions"?"Total Sessions":k==="_organicSessions"?"Organic Sessions":k}),e.jsx(qt,{type:"monotone",dataKey:"_totalSessions",stroke:qe.textFaint,fill:qe.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),Fe.map((k,F)=>e.jsx(qt,{type:"monotone",dataKey:k,stackId:"ai",stroke:pt[F%pt.length],fill:pt[F%pt.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(Ze,{label:"Organic",value:Rt,hint:`${wt.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(Ze,{label:"Social",value:Le,hint:`${se.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(Ze,{label:"Direct",value:us,hint:`${Jt.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(Ze,{label:"Known AI referrers (lower bound)",value:Yt,hint:`${$e.toLocaleString()} sessions`,tone:"positive",tooltip:"Sessions whose current sessionSource matched a known AI engine (e.g. chatgpt.com, claude.ai, gemini.google.com). These sessions are removed from their native GA4 channel in this card grid so the five buckets stay disjoint. This is a strict lower bound: most AI traffic strips the referrer and falls into Direct, so the true AI share is typically higher than what's shown here. The detail table below also surfaces firstUserSource and UTM-tagged AI signals."}),e.jsx(Ze,{label:"Other channels",value:Ie,hint:`${it.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."})]}),Ee&&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:Ee.source})," via ",Ee.medium,", accounting for ",Ee.sessions.toLocaleString()," sessions."]})]}),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?`${Ue} 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(Me,{label:"Source",sortKey:"source",current:N,dir:x,onSort:ye,align:"left"}),e.jsx(Me,{label:"Medium",sortKey:"medium",current:N,dir:x,onSort:ye,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(Me,{label:"Sessions",sortKey:"sessions",current:N,dir:x,onSort:ye,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(Me,{label:"Users",sortKey:"users",current:N,dir:x,onSort:ye,align:"right"})]})}),e.jsx("tbody",{children:ie.map(k=>e.jsx(Yl,{referral:k,totalSessions:Vt},`${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:oe.length>vs?`${Ae+1}–${Ae+Oe.length} of ${oe.length} rows`:oe.length>0?`${oe.length} rows`:"No landing-page rows"})]}),oe.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(Me,{label:"Landing Page",sortKey:"landingPage",current:M,dir:G,onSort:O,align:"left"}),e.jsx(Me,{label:"Source",sortKey:"source",current:M,dir:G,onSort:O,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(Me,{label:"Sessions",sortKey:"sessions",current:M,dir:G,onSort:O,align:"right"}),e.jsx(Me,{label:"Users",sortKey:"users",current:M,dir:G,onSort:O,align:"right"})]})}),e.jsx("tbody",{children:Oe.map(k=>e.jsx(Xl,{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:()=>ue(D-1),disabled:D<=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 ",D," of ",y]}),e.jsx("button",{type:"button",onClick:()=>ue(D+1),disabled:D>=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(ke,{text:"Tracks sessions classified as social traffic by GA4's default channel grouping (Organic Social and Paid Social). Google maintains the source-to-channel mapping."})]})]}),vt.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"})]}),Ke>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",dt.length-1," sources · ",Ke," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(Lt,{width:"100%",height:"100%",children:e.jsxs(zt,{data:vt,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Dt,{dataKey:"date",tick:_e,tickLine:!1,axisLine:{stroke:et},tickFormatter:Pt}),e.jsx(Tt,{tick:_e,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(It,{...ct,labelFormatter:jt,formatter:(k,F)=>{const Q=typeof k=="number"?k.toLocaleString():String(k??0),Z=String(F??"");if(Z===Qt)return[Q,"Total Social"];if(Z===Wt){const nt=`Other (${Ke} source${Ke===1?"":"s"})`;return[Q,nt]}return[Q,Kt(Z)]}}),e.jsx(qt,{type:"monotone",dataKey:Qt,stroke:$a,fill:qe.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),dt.map((k,F)=>{const Z=k===Wt?dn:pt[F%pt.length];return e.jsx(qt,{type:"monotone",dataKey:k,stackId:"social",stroke:Z,fill:Z,fillOpacity:.4,strokeWidth:1.5},k)})]})})}),e.jsx(Zl,{sources:dt,otherCount:Ke})]}),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(Ze,{label:"Social Sessions",value:Ns(h),hint:`${h.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(Ze,{label:"Share of Traffic",value:Y,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(Ze,{label:"Platforms",value:String(ve),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."})]}),He&&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:`${He.source} via ${He.medium}`,children:Aa(Kt(He.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:He.medium,children:["via ",Kt(He.medium)," · ",He.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(Ze,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(Ze,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(Ze,{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?Ne.length>ns&&!te?`Top ${ns} of ${Ne.length}`:`${Ne.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(Me,{label:"Source",sortKey:"source",current:_,dir:T,onSort:X,align:"left"}),e.jsx(Me,{label:"Medium",sortKey:"medium",current:_,dir:T,onSort:X,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(Me,{label:"Sessions",sortKey:"sessions",current:_,dir:T,onSort:X,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(Me,{label:"Users",sortKey:"users",current:_,dir:T,onSort:X,align:"right"})]})}),e.jsx("tbody",{children:(te?Ne:Ne.slice(0,ns)).map(k=>e.jsx(Jl,{referral:k,totalSessions:h},`${k.source}:${k.medium}:${k.channelGroup}`))})]})}),Ne.length>ns&&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:te?`Show top ${ns}`:`Show all ${Ne.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(ke,{text:"Landing pages ranked by session volume. Click column headers to sort. Organic % shows the share of sessions coming from Google organic search."})]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(Me,{label:"Landing Page",sortKey:"landingPage",current:C,dir:R,onSort:be,align:"left"}),e.jsx(Me,{label:"Sessions",sortKey:"sessions",current:C,dir:R,onSort:be,align:"right"}),e.jsx(Me,{label:"Organic",sortKey:"organicSessions",current:C,dir:R,onSort:be,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"}),e.jsx(Me,{label:"Users",sortKey:"users",current:C,dir:R,onSort:be,align:"right"})]})}),e.jsx("tbody",{children:q.map(k=>e.jsx(Vl,{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 ${Pa(i.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:i?`${i.topPages.length} pages · ${i.aiReferrals.length} AI rows · ${i.socialReferrals.length} social rows`:""})]})]})}function Wl({projectName:t,onConnected:s}){const[n,a]=r.useState(""),[i,l]=r.useState(null),[o,p]=r.useState(null),[g,u]=r.useState(!1),[m,d]=r.useState(null),P=r.useRef(null),b=r.useCallback(v=>{const C=v.target.files?.[0];if(!C)return;d(null),l(C.name);const z=new FileReader;z.onload=()=>{const R=z.result;try{const I=JSON.parse(R);if(!I.client_email||!I.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(R)}catch{d("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),p(null)}},z.onerror=()=>{d("Failed to read file."),p(null)},z.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}u(!0);try{await mi(t,{propertyId:n.trim(),keyJson:o});try{await oa(t)}catch{}s()}catch(v){d(v instanceof Error?v.message:"Failed to connect GA4")}finally{u(!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."}),m&&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:m}),e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{htmlFor:"ga4-property-id",className:"block text-xs font-medium text-secondary mb-1.5",children:"GA4 Property ID"}),e.jsx("input",{id:"ga4-property-id",type:"text",placeholder:"e.g. 123456789",value:n,onChange:v=>a(v.target.value),className:"w-full rounded-lg bg-bg-elevated/60 border border-default px-3 py-2 text-sm text-strong placeholder-mono-600 focus:outline-none focus:ring-1 focus:ring-mono-600"}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:"Find this in GA4 → Admin → Property Settings. It's a numeric ID, not the Measurement ID (G-XXXXXX)."})]}),e.jsxs("div",{className:"mb-5",children:[e.jsx("label",{className:"block text-xs font-medium text-secondary mb-1.5",children:"Service Account Key File"}),e.jsx("input",{ref:P,type:"file",accept:".json,application/json",onChange:b,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>P.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(kl,{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(L,{variant:"default",size:"sm",disabled:g||!n.trim()||!o,onClick:ee(A),children:g?"Connecting & syncing…":"Connect GA4"})]})}function Me({label:t,sortKey:s,current:n,dir:a,onSort:i,align:l}){const o=n===s;return e.jsx("th",{className:`py-1 ${l==="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 La={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function Ws({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 ${La[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Ze({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(ke,{text:i})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${La[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Vl({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 za={session:"Session",first_user:"First Visit",manual_utm:"UTM"},Da={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 Yl({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=za[t.sourceDimension]??t.sourceDimension,i=Da[t.sourceDimension]??"";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 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 Xl({row:t}){const s=za[t.sourceDimension]??t.sourceDimension,n=Da[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 Jl({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),l=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:l}),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 Zl({sources:t,otherCount:s}){const n=[{key:Qt,color:$a,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const i=t[a];if(i===Wt)n.push({key:Wt,color:dn,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const l=Kt(i);n.push({key:i,color:pt[a%pt.length]??dn,label:Aa(l,32),tooltip:l})}}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 eo(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 to=["7d","30d","90d","all"],ws=500,xt=25;function so({projectName:t,refreshNonce:s}){const n=yt(),[a,i]=r.useState(!1),[l,o]=r.useState([]),[p,g]=r.useState([]),[u,m]=r.useState([]),[d,P]=r.useState(null),[b,A]=r.useState([]),[v,C]=r.useState([]),[z,R]=r.useState(null),[I,N]=r.useState(""),[j,x]=r.useState(""),[E,_]=r.useState("30"),[H,T]=r.useState(!1),[S,M]=r.useState("30d"),[U,G]=r.useState({startDate:"",endDate:"",query:"",page:"",limit:"20"}),[ne,fe]=r.useState(0),[ue,pe]=r.useState(!1),[me,he]=r.useState(0),[je,f]=r.useState(!1),[B,te]=r.useState(""),[le,de]=r.useState(!0),[Ce,$]=r.useState(!1),[V,Te]=r.useState(!1),[be,ye]=r.useState(!1),[X,O]=r.useState(!1),[q,ie]=r.useState(!1),[oe,y]=r.useState(!1),[D,Ae]=r.useState(null),[Oe,Ne]=r.useState(!1),[vt,dt]=r.useState(!1),[Ke,Nt]=r.useState(null),[Fe,tt]=r.useState(""),[st,Rt]=r.useState(!1),[wt,Vt]=r.useState(!1),[$e,Yt]=r.useState("indexed"),[Ue,Ee]=r.useState(null),St=!!(U.query.trim()||U.page.trim()||Ue),Xt=Ue!==null,Jt=r.useMemo(()=>{if(!Ue)return u;const{key:c,dir:w}=Ue;return[...u].sort((J,ce)=>{const ze=c===$t.CTR?Number.isFinite(J.ctr)?J.ctr:0:J[c],Ge=c===$t.CTR?Number.isFinite(ce.ctr)?ce.ctr:0:ce[c];return w==="asc"?ze-Ge:Ge-ze})},[u,Ue]),[us,it]=r.useState([]),[Ie,h]=r.useState(null),[Y,se]=r.useState(1);r.useEffect(()=>{se(1)},[D,$e,Ie]);const Le=r.useMemo(()=>Ie?(D?.reasonGroups??[]).find(c=>c.reason===Ie):void 0,[D,Ie]),ve=r.useMemo(()=>D?$e==="indexed"?D.indexed:$e==="deindexed"?D.deindexed:$e==="notIndexed"?Ie?Le?.urls??[]:(D.reasonGroups??[]).length===0?D.notIndexed:[]:[]:[],[D,$e,Ie,Le]),He=Math.max(1,Math.ceil(ve.length/xt)),k=Math.min(Math.max(1,Y),He),F=(k-1)*xt,Q=ve.length>xt,Z=ve.length===0?0:F+1,nt=Math.min(F+xt,ve.length),Zt=r.useMemo(()=>D?.indexed.slice(F,F+xt)??[],[D,F]),we=r.useMemo(()=>D?.notIndexed.slice(F,F+xt)??[],[D,F]),We=r.useMemo(()=>D?.deindexed.slice(F,F+xt)??[],[D,F]),Et=r.useMemo(()=>(Le?.urls??[]).slice(F,F+xt),[Le,F]),[ut,at]=r.useState(!1),[jn,xe]=r.useState(null),[rt,ms]=r.useState(null),[yn,lt]=r.useState(null);function Fa(c,w){const J=hl(c),ce=eo(J);ce?(ms(ce),xe(null)):(ms(null),xe(J.message||w))}const Se=l.find(c=>c.connectionType==="gsc"),Ba=u.length>0||b.length>0||v.length>0,qs=xi(),es=hi(),Gs=pi();async function vn(c){if(!c){g([]),N("");return}Te(!0);try{const{sites:w}=await n.fetchQuery({...Ai({client:K,path:{name:t}}),staleTime:Re});g(w),N(c.propertyId??w[0]?.siteUrl??""),ms(null)}catch(w){g([]),Fa(w,"Failed to load Search Console properties")}finally{Te(!1)}}async function Mt(c){O(!0);const w=c??ne;try{const J=parseInt(U.limit,10)||20,ce=St?ws:J+1,ze=St?0:w,Ge={limit:String(ce)};U.startDate&&(Ge.startDate=U.startDate),U.endDate&&(Ge.endDate=U.endDate),U.query&&(Ge.query=U.query),U.page&&(Ge.page=U.page),ze>0&&(Ge.offset=String(ze)),S&&S!=="all"&&!U.startDate&&(Ge.window=S);const Ve=await n.fetchQuery({...bi({client:K,path:{name:t},query:Ge}),staleTime:Re});St?(pe(!1),m(Ve),he(Ve.length),f(!0)):(pe(Ve.length>J),m(Ve.slice(0,J)),he(0),f(!1))}catch(J){m([]),pe(!1),he(0),xe(J instanceof Error?J.message:"Failed to load GSC performance data")}finally{O(!1)}}async function _s(){try{const c={};U.startDate&&(c.startDate=U.startDate),U.endDate&&(c.endDate=U.endDate),S&&S!=="all"&&!U.startDate&&(c.window=S);const w=await n.fetchQuery({...ji({client:K,path:{name:t},query:c}),staleTime:Re});P(w)}catch{P(null)}}async function xs(){ie(!0);try{const c=B.trim()||void 0,w={limit:"20"};c&&(w.url=c);const[J,ce]=await Promise.all([n.fetchQuery({...ki({client:K,path:{name:t},query:w}),staleTime:Re}),n.fetchQuery({...Ci({client:K,path:{name:t}}),staleTime:Re})]);A(J),C(ce)}catch(c){A([]),C([]),xe(c instanceof Error?c.message:"Failed to load GSC inspection history")}finally{ie(!1)}}async function Nn(){Ne(!0);try{const[c,w]=await Promise.all([n.fetchQuery({...ca({client:K,path:{name:t}}),staleTime:Re}),n.fetchQuery({...wi({client:K,path:{name:t}}),staleTime:Re}).catch(()=>[])]);Ae(c),it(w)}catch(c){Ae(null),it([]),xe(c instanceof Error?c.message:"Failed to load coverage data")}finally{Ne(!1)}}async function wn(c){at(!0),xe(null);try{const w=await Ln(t,{urls:c}),{succeeded:J,failed:ce,total:ze}=w.summary;re({title:"Indexing requested",detail:ce===0?`${J} URL${J!==1?"s":""} submitted for indexing.`:`${J}/${ze} submitted successfully, ${ce} failed.`,tone:ce===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(w){xe(w instanceof Error?w.message:"Failed to request indexing")}finally{at(!1)}}async function qa(){at(!0),xe(null);try{const c=await Ln(t,{urls:[],allUnindexed:!0}),{succeeded:w,failed:J,total:ce}=c.summary;re({title:"Indexing requested",detail:J===0?`${w} unindexed URL${w!==1?"s":""} submitted for indexing.`:`${w}/${ce} submitted successfully, ${J} failed.`,tone:J===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(c){xe(c instanceof Error?c.message:"Failed to request indexing")}finally{at(!1)}}async function hs(){if(Fe.trim()){Rt(!0),xe(null);try{await Ni(t,"gsc",Fe.trim()),await n.invalidateQueries({predicate:c=>{const w=c.queryKey[0];return typeof w?._id=="string"&&w._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),o(c=>c.map(w=>w.connectionType==="gsc"?{...w,sitemapUrl:Fe.trim()}:w)),re({title:"Sitemap URL saved",detail:`${t} will use the updated sitemap URL.`,tone:"positive",dedupeKey:`gsc:sitemap:${t}`,dedupeMode:"drop"}),tt("")}catch(c){xe(c instanceof Error?c.message:"Failed to save sitemap URL")}finally{Rt(!1)}}}async function Sn(){xe(null);try{const c=await es.mutateAsync({projectName:t,projectLabel:t});Nt(c.sitemaps),o(w=>w.map(J=>J.connectionType==="gsc"?{...J,sitemapUrl:c.primarySitemapUrl}:J))}catch{}}async function Ga(){dt(!0),xe(null);try{const c=await Pi(t);n.setQueryData(Li({client:K,path:{name:t}}),c),Nt(c.sitemaps),c.sitemaps.length===0&<("No sitemaps found in this GSC property. Submit a sitemap in Google Search Console first.")}catch(c){xe(c instanceof Error?c.message:"Failed to list sitemaps")}finally{dt(!1)}}async function kn(){de(!0),xe(null);try{const[c,w]=await Promise.all([fi().catch(()=>null),n.fetchQuery({...xn({client:K,path:{name:t}}),staleTime:Re}).catch(()=>[])]);i(!!c?.google?.configured),o(w);const J=w.find(ce=>ce.connectionType==="gsc");await Promise.all([vn(J),Mt(),_s(),xs(),Nn()])}finally{de(!1)}}r.useEffect(()=>{kn()},[t,s]),r.useEffect(()=>{fe(0),Mt(0),_s()},[S]);const Cn=r.useRef(!1);r.useEffect(()=>{if(!Cn.current){Cn.current=!0;return}fe(0),Mt(0)},[Xt]);async function _a(){if(!a){xe("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}$(!0),xe(null),lt(null);try{const{authUrl:c}=await vi(t,"gsc");if(!c.startsWith("https://accounts.google.com/")){xe("Unexpected OAuth redirect URL. Please try again.");return}const w=window.open(c,"_blank","width=600,height=700");if(!w){window.location.assign(c);return}lt("Finish the Google consent flow in the popup, then close it to refresh this project.");const J=window.setInterval(()=>{w.closed&&(window.clearInterval(J),lt(null),n.invalidateQueries({predicate:ce=>{const ze=ce.queryKey[0];return typeof ze?._id=="string"&&ze._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),kn())},1e3)}catch(c){xe(c instanceof Error?c.message:"Failed to start OAuth flow")}finally{$(!1)}}async function Ua(){xe(null),lt(null);try{await yi(t,"gsc"),await n.invalidateQueries({predicate:c=>{const w=c.queryKey[0];return typeof w?._id=="string"&&w._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),o(c=>c.filter(w=>w.connectionType!=="gsc")),g([]),N("")}catch(c){xe(c instanceof Error?c.message:"Failed to disconnect")}}async function Qa(){if(I){ye(!0),xe(null);try{await $i(t,"gsc",I),await n.invalidateQueries({predicate:c=>{const w=c.queryKey[0];return typeof w?._id=="string"&&w._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),o(c=>c.map(w=>w.connectionType==="gsc"?{...w,propertyId:I}:w)),re({title:"GSC property updated",detail:`${t} is now linked to ${I}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(c){xe(c instanceof Error?c.message:"Failed to save GSC property")}finally{ye(!1)}}}async function Ka(){xe(null),lt(null);try{await qs.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(E,10)||void 0,full:H||void 0}}),await n.invalidateQueries({predicate:c=>{const w=c.queryKey[0];return typeof w?._id=="string"&&w._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}})}catch{}}async function An(){if(j.trim()){y(!0),xe(null),lt(null);try{const c=await Si(t,j.trim());await n.invalidateQueries({predicate:w=>{const J=w.queryKey[0];return typeof J?._id=="string"&&J._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),R(c),x(""),await xs()}catch(c){xe(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"})]})}),rt&&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:rt.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:rt.message}),(Bt(rt.enableUrl)||Bt(rt.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[Bt(rt.enableUrl)&&e.jsx("a",{href:Bt(rt.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 ↗"}),Bt(rt.indexingApiUrl)&&e.jsx("a",{href:Bt(rt.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:()=>ms(null),children:"×"})]})}),jn&&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:[jn,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>xe(null),children:"×"})]}),yn&&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:[yn,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:[Se?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:Se.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Last updated ",Je(Se.updatedAt)]}),e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:ee(Ua),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(ae,{tone:a?"caution":"negative",children:a?"Ready to connect":"App credentials missing"})]}),e.jsxs("div",{className:"mt-3 rounded-lg border border-default bg-surface px-4 py-5",children:[e.jsx("p",{className:"text-sm text-neutral",children:a?"Generate a Google OAuth link for this project and have the client sign in with a Google account that already has access to the correct Search Console property.":"Set Google OAuth client credentials first. Once configured, you can generate a consent link for this project domain."}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[a?e.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:Ce,onClick:ee(_a),children:Ce?"Opening…":"Connect Google Search Console"}):e.jsx(L,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(ft,{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."})]})]})]}),Se&&!Se.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."}),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(L,{type:"button",size:"sm",disabled:es.isPending||!Se.propertyId,onClick:ee(Sn),children:es.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:Fe,onChange:c=>tt(c.target.value),onKeyDown:c=>c.key==="Enter"&&void hs()}),e.jsx(L,{type:"button",size:"sm",variant:"outline",disabled:st||!Fe.trim(),onClick:ee(hs),children:st?"Saving…":"Save sitemap URL"})]})]})]})]})}),(Se||Ba)&&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:[D&&D.notIndexed.length>0&&e.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:ut,onClick:()=>{qa()},children:ut?"Requesting…":`Request indexing (${D.notIndexed.length})`}),e.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:Oe,onClick:()=>{Nn()},children:Oe?"Loading…":"Refresh coverage"})]})]}),D&&D.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const c=D.summary.indexed+D.summary.notIndexed,w=c>0?D.summary.indexed/c:0,J=c>0?D.summary.notIndexed/c:0,ce=54,ze=2*Math.PI*ce,Ge=ze*(1-w),Ve=ze*J,Ot=ze*w;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:ce,fill:"none",stroke:qe.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:ce,fill:"none",stroke:bt.positiveDeep,strokeWidth:"14",strokeDasharray:ze,strokeDashoffset:Ge,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),D.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:ce,fill:"none",stroke:qe.textFaint,strokeWidth:"14",strokeDasharray:`${Ve} ${ze-Ve}`,strokeDashoffset:-Ot,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:[(w*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:D.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:D.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:["Not indexed",(D.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-faint",children:["· ",(D.reasonGroups??[]).length," ",(D.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),D.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:D.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 w=c==="indexed"?D.indexed.length:c==="notIndexed"?D.notIndexed.length:D.deindexed.length,J=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 ${$e===c?"bg-mono-700 text-heading":"text-secondary hover:bg-mono-800 hover:text-strong"}`,onClick:()=>{Yt(c),h(null)},children:[J," (",w,")"]},c)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[$e==="indexed"&&D.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:Zt.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))})]}),$e==="notIndexed"&&!Ie&&(D.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:(D.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:()=>h(c.reason),onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),h(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))})]}),$e==="notIndexed"&&!Ie&&(D.reasonGroups??[]).length===0&&D.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:we.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))})]}),$e==="notIndexed"&&Ie&&(()=>{const c=(D.reasonGroups??[]).find(w=>w.reason===Ie);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:()=>h(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":""]})]}),e.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:ut,onClick:()=>{wn(c.urls.map(w=>w.url))},children:ut?"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"}),e.jsx("th",{className:"w-8"})]})}),e.jsx("tbody",{children:Et.map(w=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:w.url}),e.jsx("td",{className:"text-secondary",children:w.crawlTime?w.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-strong transition-colors",disabled:ut,onClick:()=>{wn([w.url])},title:"Request indexing",children:"Index"})})]},w.id))})]})]}):null})(),$e==="deindexed"&&D.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:We.map((c,w)=>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}-${w}`))})]}),($e==="indexed"&&D.indexed.length===0||$e==="notIndexed"&&!Ie&&D.notIndexed.length===0||$e==="deindexed"&&D.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),Q&&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:Z.toLocaleString("en-US")}),"–",e.jsx("span",{className:"text-neutral",children:nt.toLocaleString("en-US")})," of"," ",e.jsx("span",{className:"text-neutral",children:ve.length.toLocaleString("en-US")})," URLs"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>se(c=>Math.max(1,c-1)),disabled:k<=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(dl,{className:"size-3.5"}),"Prev"]}),e.jsxs("span",{className:"tabular-nums",children:["Page ",e.jsx("span",{className:"text-strong",children:k})," of"," ",e.jsx("span",{className:"text-strong",children:He})]}),e.jsxs("button",{type:"button",onClick:()=>se(c=>Math.min(He,c+1)),disabled:k>=He,"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(Is,{className:"size-3.5"})]})]})]})]})]}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:Oe?"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:to.map(c=>e.jsx("button",{type:"button",role:"tab","aria-selected":S===c,className:`px-2.5 py-1 text-xs rounded-full border transition-colors ${S===c?"bg-mono-700 border-mono-600 text-primary":"border-base text-secondary hover:border-strong hover:text-neutral"}`,onClick:()=>M(c),children:c==="all"?"All":c},c))}),e.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:X,onClick:()=>{fe(0),Mt(0),_s()},children:X?"Loading…":"Apply filters"})]})]}),d&&d.daily.length>0&&(()=>{const c=d.daily,w=Math.max(...c.map(ge=>ge.impressions),1),{clicks:J,impressions:ce,ctr:ze}=d.totals,Ge=(ze*100).toFixed(1),Ve=700,Ot=220,Ye={top:12,bottom:36,left:48,right:12},Ha=Ve-Ye.left-Ye.right,Ft=Ot-Ye.top-Ye.bottom,ts=Ha/c.length,ps=Math.max(Math.min(ts*.35,24),4),$n=Math.max(ps*.15,1),Wa=ge=>{if(ge<=0)return 1;const ot=Math.pow(10,Math.floor(Math.log10(ge))),Xe=ge/ot,mt=Xe<=1.5?1.5:Xe<=3?3:Xe<=5?5:10;return Math.ceil(mt*ot)},gs=4,fs=Math.ceil(Wa(w)/gs)*gs,Va=Array.from({length:gs+1},(ge,ot)=>fs/gs*ot),Ya=ge=>ge>=1e3?`${(ge/1e3).toFixed(ge>=1e4?0:1)}k`:String(ge);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:J.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:ce.toLocaleString()})]})]}),e.jsxs("span",{className:"text-xs text-muted",children:["CTR ",e.jsxs("span",{className:"text-caution-400 tabular-nums font-medium",children:[Ge,"%"]})]})]}),e.jsx("div",{className:"relative w-full",style:{aspectRatio:`${Ve} / ${Ot}`},children:e.jsxs("svg",{viewBox:`0 0 ${Ve} ${Ot}`,className:"h-full w-full",children:[Va.map((ge,ot)=>{const Xe=Ye.top+Ft-ge/fs*Ft;return e.jsxs("g",{children:[e.jsx("line",{x1:Ye.left,y1:Xe,x2:Ve-Ye.right,y2:Xe,stroke:qe.gridLine,strokeWidth:"1"}),e.jsx("text",{x:Ye.left-6,y:Xe+3.5,textAnchor:"end",fill:qe.text,fontSize:"10",fontFamily:"inherit",children:Ya(ge)})]},`t-${ot}`)}),c.map((ge,ot)=>{const Xe=Ye.left+ts*ot+ts/2,mt=ge.impressions/fs*Ft,bs=ge.clicks/fs*Ft;return e.jsxs("g",{children:[e.jsx("title",{children:`${ge.date}
|
|
1
|
+
import{j as e,r,L as ft,n as yt,u as Pe,o as os,A as Xa,B as Ja,h as Za}from"./vendor-tanstack-Be8JdV5M.js";import{c as Ts,T as ae,t as ei,a as ti,u as la,C as si,b as Is,P as Ht,B as L,h as ni,d as ai,e as ii,f as Je,g as W,i as ee,I as ke,j as ss,k as ri,l as K,m as li,n as oi,o as ci,p as di,q as oa,r as ui,s as mi,S as $t,v as xi,w as hi,x as pi,y as Bt,z as gi,A as Pn,D as fi,G as Re,E as xn,F as bi,H as ji,J as yi,K as vi,L as Ni,M as re,N as Ln,O as ca,Q as wi,R as Si,U as ki,V as Ci,W as Ai,X as $i,Y as Pi,Z as Li,_ as zi,$ as Di,a0 as Ti,a1 as Ii,a2 as Ri,a3 as Ei,a4 as Mi,a5 as Oi,a6 as cs,a7 as Fi,a8 as Bi,a9 as zn,aa as qi,ab as Gi,ac as _i,ad as Ui,ae as Ps,af as Qi,ag as Ki,ah as Hi,ai as Wi,aj as ln,ak as Vi,al as Yi,am as Xi,an as Ji,ao as Us,ap as Ut,aq as da,ar as ua,as as Zi,at as er,au as hn,av as tr,aw as ma,ax as sr,ay as nr,az as ar,aA as ir,aB as xa,aC as rr,aD as ha,aE as lr,aF as or,aG as cr,aH as dr,aI as Rs,aJ as ur,aK as mr,aL as xr,aM as hr,aN as pr,aO as gr,aP as fr,aQ as br,aR as jr,aS as yr,aT as vr,aU as Nr,aV as wr,aW as Sr,aX as kr,aY as Cr,aZ as Ar,a_ as $r,a$ as Pr,b0 as Qs,b1 as Lr,b2 as zr,b3 as Dn,b4 as Dr,b5 as Tr,b6 as Ir,b7 as Rr,b8 as Er,b9 as Mr,ba as Or,bb as Fr,bc as Br,bd as qr,be as Gr,bf as _r,bg as Tn,bh as Ur,bi as Ks,bj as Qr,bk as In,bl as Rn,bm as Kr,bn as Hr,bo as Wr,bp as Vr,bq as Yr,br as Xr,bs as Jr,bt as Zr,bu as el,bv as tl,bw as pa,bx as ga,by as sl,bz as fa,bA as nl,bB as ba,bC as al,bD as il,bE as js,bF as rl,bG as ll,bH as ol,bI as En}from"./index-DB_F_WFv.js";import{R as cl}from"./RunRow-Chc7eyZU.js";import{f as Pt,C as et,a as _e,b as jt,c as ct,d as qe,e as Qe,g as bt,h as dl,i as Es,p as ul}from"./ChartPrimitives-BjcDtBSv.js";import{u as ml,t as xl,R as Ls,e as hl}from"./extract-error-message-b-rZowjX.js";import{R as Lt,C as zt,X as Dt,Y as Tt,T as It,L as ja,A as qt,a as Ms,b as pl,d as Os}from"./vendor-recharts-C9EZkgbP.js";import{C as ya,D as rs,a as gl,T as fl}from"./trash-2-6CLXNfZm.js";import"./vendor-radix-CQ77EO2y.js";import"./vendor-markdown-6dwjPOKK.js";const bl=[["path",{d:"M5 12h14",key:"1ays0h"}]],jl=Ts("minus",bl);const yl=[["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"}]],vl=Ts("scan-search",yl);const Nl=[["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"}]],wl=Ts("unplug",Nl);const Sl=[["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"}]],kl=Ts("upload",Sl),Cl=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function va(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function Na(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 wa(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(va).map(Na).filter(Boolean)):new Set}function Sa(t,s){const n=va(t).map(Na).filter(Boolean).filter(a=>!Cl.has(a)).filter(a=>!s.has(a));return[...new Set(n)].sort().join(" ")}function Al(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function $l(t,s){const n=wa(t);if(s.length<=1||n.size===0)return[...s];const a=new Set,i=[];for(const l of s){if(l.category!=="content"){i.push(l);continue}const o=Sa(Al(l),n);!o||a.has(o)||(a.add(o),i.push(l))}return i}function Pl(t){const s=wa(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const a=new Set;return n.filter(i=>{const l=Sa(i.query,s);return!l||a.has(l)?!1:(a.add(l),!0)})}function Cs(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 Ll(t,s){return s<=0?null:Math.round((t-s)/s*100)}function Hs(t,s,n="vs prior 7 days"){return t.deltaPct===null?t.prior===0?"First baseline week":"":t.deltaPct>0?`Up ${t.deltaPct}% ${n} (${Cs(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${Cs(t.prior)} ${s})`:`Flat ${n} (${Cs(t.prior)} ${s})`}const ka=30;function Mn(t){return Math.round(t*10)/10}function zl(t){return t.prior>=ka&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% vs prior`:`${t.deltaAbs>0?"+":""}${Mn(t.deltaAbs)} vs ${Mn(t.prior)}`}function Dl(t,s,n){return t.prior>=ka&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% ${n}`:`${t.deltaAbs>0?"+":""}${Cs(Math.round(t.deltaAbs))} ${s} ${n}`}function on({state:t,label:s}){return e.jsx(ae,{tone:ti(t),children:s??ei(t)})}function On({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"}),l=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:l})]})}function cn(t){const s=new Map;for(const a of t)for(const i of a.runHistory){const l=s.get(i.createdAt);l?l.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:l}])=>({runId:l,createdAt:a,citationState:i.includes("cited")?"cited":i.includes("emerging")?"emerging":"not-cited"}))}const Tl=320;function Fn(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 Bn(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 qn(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,l=t[t.length-2].citationState;if(l!=="cited"&&i==="cited")return`Newly ${n}`;if(l==="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 Il(t,s){return t.map(n=>Ca(n,s))}function Ca(t,s){return s==="citations"?t:{...t,citationState:Fn(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:Fn(n,s)}))}}function Gn(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,l=t.length>=2?t[t.length-2].citationState:null,o=i==="cited"||i==="emerging",p=l==="cited"||l==="emerging";return i==="lost"||l!==null&&p&&!o?{key:s,label:`Lost ${n}`,tone:"negative"}:i==="emerging"||l!==null&&!p&&o?{key:s,label:`New ${n}`,tone:"positive"}:l===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 Rl(t){const s=cn(Il(t,"mentions")),n=cn(t);return[Gn(s,"mentions"),Gn(n,"citations")]}function El({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 _n({items:t}){return e.jsx("div",{className:"mt-1 flex flex-wrap gap-1","aria-label":"Latest run mention and citation signals",children:Rl(t).map(s=>e.jsx(El,{signal:s},s.key))})}function Ml({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:a}=la(),[i,l]=r.useState(new Set),[o,p]=r.useState("mentions"),[g,u]=r.useState(n),m=r.useMemo(()=>{const v=new Map;for(const C of t){const z=C.query,R=s?C.location??null:null,I=s?JSON.stringify([z,R]):z,N=v.get(I)??{key:I,phrase:z,location:R,items:[],rawItems:[]};N.items.push(Ca(C,o)),N.rawItems.push(C),v.set(I,N)}return[...v.values()]},[t,o,s]),d=v=>{l(C=>{const z=new Set(C);return z.has(v)?z.delete(v):z.add(v),z})},P=o==="mentions"?"mentioned":"cited",b=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:()=>{l(v=>v.size===m.length?new Set:new Set(m.map(C=>C.key)))},children:i.size===m.length&&m.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":g==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${g==="compact"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>u("compact"),children:"Compact"}),e.jsx("button",{type:"button",role:"tab","aria-selected":g==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${g==="detailed"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>u("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:b}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:m.map(({key:v,phrase:C,location:z,items:R,rawItems:I})=>{const N=i.has(v),j=R.map(T=>T.citationState),x=j.includes("cited")?"cited":j.includes("emerging")?"emerging":j.includes("lost")?"lost":j.every(T=>T==="pending")?"pending":"not-cited",E=cn(R),_=R.filter(T=>T.citationState===si.cited||T.citationState==="emerging").length,H=qn(E,o);return e.jsxs(r.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(v),onKeyDown:T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),d(v))},tabIndex:0,role:"button","aria-expanded":N,children:[e.jsx("td",{children:e.jsx(Is,{size:14,className:`transition-transform duration-150 text-muted ${N?"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:z??"No location"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:R.map(T=>e.jsx(Ht,{provider:T.provider},T.id))})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(on,{state:x,label:Bn(x,o)}),e.jsxs("span",{className:"text-[11px] text-muted",title:`${_} of ${R.length} engines ${A}`,children:[_,"/",R.length]})]})}),e.jsx("td",{children:e.jsx(On,{history:E})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:H}),e.jsx(_n,{items:I})]}),e.jsx("td",{})]}),N&&R.map((T,S)=>e.jsxs(r.Fragment,{children:[e.jsxs("tr",{className:"bg-surface",children:[e.jsx("td",{}),e.jsx("td",{className:"evidence-query-cell pl-5",children:e.jsx(Ht,{provider:T.provider})}),e.jsx("td",{children:e.jsx(on,{state:T.citationState,label:Bn(T.citationState,o)})}),e.jsx("td",{children:e.jsx(On,{history:T.runHistory})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:qn(T.runHistory,o)}),e.jsx(_n,{items:[I[S]??T]})]}),e.jsx("td",{children:e.jsx(L,{variant:"ghost",size:"sm",type:"button",onClick:M=>{M.stopPropagation(),a(T.id)},children:"View"})})]}),g==="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(Bl,{item:T,onViewFull:()=>a(T.id)})})]})]},T.id))]},v)})})]})}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",P==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function Ol(t){const s=(t.matchedTerms??[]).filter(i=>i.trim().length>2),n=[...t.competitorDomains.flatMap(i=>{const l=ai(i);return l.length>=4?[l]:[]}),...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 Fl(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 Bl({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}=Fl(t.answerSnippet,Tl),l=Ol(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:ni(a,l)}),(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 ql({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,l=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"}),l&&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(),g=[i?"cursor-pointer hover:bg-mono-800/30 transition-colors":"",p?"bg-negative-950/20":""].filter(Boolean).join(" ");return e.jsxs("tr",{className:g,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(ae,{tone:ii(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"}),l&&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:u=>{u.stopPropagation(),n(o.domain)},children:"Remove"})})]},o.id)})})]})})}function Un({eyebrow:t,title:s,status:n,tone:a,targetLabel:i,targetValue:l,coverageValue:o,note:p,updatedAt:g,active:u,onClick:m}){return e.jsxs("button",{type:"button",onClick:m,className:`surface-card w-full text-left transition-colors ${u?"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(ae,{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:l})]}),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:g?`Updated ${Je(g)}`:"No recent sync yet"})]})]})}function ys({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 Gl=6,Wt="__other__",Qt="_socialTotal";function _l(t,s=Gl){const n=new Map;for(const m of t)n.set(m.source,(n.get(m.source)??0)+m.sessions);const a=[...n.entries()].sort((m,d)=>d[1]!==m[1]?d[1]-m[1]:m[0].localeCompare(d[0])),i=a.slice(0,s),l=new Set(i.map(([m])=>m)),o=Math.max(0,a.length-s),p=new Map;for(const m of t){let d=p.get(m.date);d||(d={date:m.date,[Qt]:0},p.set(m.date,d));const P=l.has(m.source)?m.source:Wt;d[P]=(d[P]??0)+m.sessions,d[Qt]=(d[Qt]??0)+m.sessions}const g=[...p.values()].sort((m,d)=>String(m.date).localeCompare(String(d.date))),u=i.map(([m])=>m);return o>0&&u.push(Wt),{data:g,sources:u,otherCount:o}}function Kt(t){return t.replace(/\+/g," ")}function Aa(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const Ul=["7d","30d","90d","all"],pt=Qe,dn=qe.textDim,$a=qe.textFaint,ns=25,vs=50;function Ns(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function Pa(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 Ql({projectName:t}){const{data:s,isLoading:n,isError:a}=ml(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."," ",e.jsx(ft,{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."," ",e.jsx(ft,{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(l=>e.jsxs("tr",{className:"border-t border-default",children:[e.jsx("td",{className:"px-4 py-3 text-heading",children:l.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(ae,{tone:xl(l.status),children:l.status})}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:l.totals24h.crawlerHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:l.totals24h.aiUserFetchHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:l.totals24h.aiReferralHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right text-secondary text-xs",children:l.lastSyncedAt?Pa(l.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsx(ft,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:l.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},l.id))})]})})]})}function Kl({projectName:t}){return e.jsxs("div",{className:"space-y-10",children:[e.jsx(Ql,{projectName:t}),e.jsx(Hl,{projectName:t})]})}function Hl({projectName:t}){const s=yt(),[n,a]=r.useState(null),[i,l]=r.useState(null),[o,p]=r.useState(!0),[g,u]=r.useState(!1),[m,d]=r.useState(!1),[P,b]=r.useState(null),[A,v]=r.useState(null),[C,z]=r.useState("sessions"),[R,I]=r.useState("desc"),[N,j]=r.useState("sessions"),[x,E]=r.useState("desc"),[_,H]=r.useState("sessions"),[T,S]=r.useState("desc"),[M,U]=r.useState("sessions"),[G,ne]=r.useState("desc"),[fe,ue]=r.useState(1),[pe,me]=r.useState([]),[he,je]=r.useState([]),[f,B]=r.useState([]),[te,le]=r.useState(!1),[de,Ce]=r.useState("30d");async function $(k){p(!0),b(null);try{const F=await s.fetchQuery({...ri({client:K,path:{name:t}}),staleTime:ss});if(k.current)return;if(a(F),!F.connected){l(null),me([]),je([]),B([]),p(!1);return}const Q=de==="all"?void 0:de,[Z,nt,Zt,we]=await Promise.all([s.fetchQuery({...li({client:K,path:{name:t},query:Q?{window:Q}:void 0}),staleTime:ss}).then(We=>We),s.fetchQuery({...oi({client:K,path:{name:t},query:Q?{window:Q}:void 0}),staleTime:ss}).catch(()=>[]),s.fetchQuery({...ci({client:K,path:{name:t},query:Q?{window:Q}:void 0}),staleTime:ss}).catch(()=>[]),s.fetchQuery({...di({client:K,path:{name:t},query:Q?{window:Q}:void 0}),staleTime:ss}).catch(()=>[])]);if(k.current)return;l(Z),me(nt),je(Zt),B(we),p(!1)}catch(F){if(k.current)return;b(F instanceof Error?F.message:"Failed to load GA4 data"),p(!1)}}r.useEffect(()=>{const k={current:!1};return $(k),()=>{k.current=!0}},[t,de,s]);async function V(){u(!0),b(null),v(null);try{const k=await oa(t);v(`Synced ${k.rowCount.toLocaleString()} page rows, ${k.aiReferralCount.toLocaleString()} AI and ${k.socialReferralCount.toLocaleString()} social referral rows (${k.days} days)`),await s.invalidateQueries({predicate:F=>{const Q=F.queryKey[0];return typeof Q?._id=="string"&&Q._id.startsWith("getApiV1ProjectsByNameGa")}}),await $({current:!1})}catch(k){b(k instanceof Error?k.message:"Sync failed")}finally{u(!1)}}async function Te(){d(!0),b(null),v(null);try{await ui(t),await s.invalidateQueries({predicate:k=>{const F=k.queryKey[0];return typeof F?._id=="string"&&F._id.startsWith("getApiV1ProjectsByNameGa")}}),a({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),l(null),v("GA4 disconnected")}catch(k){b(k instanceof Error?k.message:"Disconnect failed")}finally{d(!1)}}function be(k){C===k?I(F=>F==="desc"?"asc":"desc"):(z(k),I("desc"))}function ye(k){N===k?E(F=>F==="desc"?"asc":"desc"):(j(k),E("desc"))}function X(k){_===k?S(F=>F==="desc"?"asc":"desc"):(H(k),S("desc"))}function O(k){ue(1),M===k?ne(F=>F==="desc"?"asc":"desc"):(U(k),ne("desc"))}const q=r.useMemo(()=>i?.topPages?[...i.topPages].sort((k,F)=>{const Q=k[C],Z=F[C];return typeof Q=="string"&&typeof Z=="string"?R==="asc"?Q.localeCompare(Z):Z.localeCompare(Q):R==="asc"?Q-Z:Z-Q}):[],[i?.topPages,C,R]),ie=r.useMemo(()=>i?.aiReferrals?[...i.aiReferrals].sort((k,F)=>{const Q=k[N],Z=F[N];return typeof Q=="string"&&typeof Z=="string"?x==="asc"?Q.localeCompare(Z):Z.localeCompare(Q):x==="asc"?Q-Z:Z-Q}):[],[i?.aiReferrals,N,x]),oe=r.useMemo(()=>i?.aiReferralLandingPages?[...i.aiReferralLandingPages].sort((k,F)=>{const Q=k[M],Z=F[M];return typeof Q=="string"&&typeof Z=="string"?G==="asc"?Q.localeCompare(Z):Z.localeCompare(Q):G==="asc"?Q-Z:Z-Q}):[],[i?.aiReferralLandingPages,M,G]),y=Math.max(1,Math.ceil(oe.length/vs)),D=Math.min(Math.max(1,fe),y),Ae=(D-1)*vs,Oe=r.useMemo(()=>oe.slice(Ae,Ae+vs),[oe,Ae]),Ne=r.useMemo(()=>i?.socialReferrals?[...i.socialReferrals].sort((k,F)=>{const Q=k[_],Z=F[_];return typeof Q=="string"&&typeof Z=="string"?T==="asc"?Q.localeCompare(Z):Z.localeCompare(Q):T==="asc"?Q-Z:Z-Q}):[],[i?.socialReferrals,_,T]),{socialChartData:vt,socialChartSources:dt,socialOtherCount:Ke}=r.useMemo(()=>{const k=_l(f);return{socialChartData:k.data,socialChartSources:k.sources,socialOtherCount:k.otherCount}},[f]),{chartData:Nt,chartSources:Fe,dateRange:tt}=r.useMemo(()=>{const k=[...new Set(pe.map(we=>we.source))],F=new Map;for(const we of he)F.set(we.date,{_totalSessions:we.sessions,_organicSessions:we.organicSessions});const Q=new Map;for(const we of pe){const We=`${we.date}::${we.source}`,Et=Q.get(We)??0;Q.set(We,Math.max(Et,we.sessions))}for(const[we,We]of Q){const[Et,ut]=we.split("::");let at=F.get(Et);at||(at={_totalSessions:0,_organicSessions:0},F.set(Et,at)),at[ut]=(at[ut]??0)+We}const Z=[...F.entries()].sort(([we],[We])=>we.localeCompare(We)).map(([we,We])=>({date:we,...We})),nt=Z.map(we=>we.date),Zt=nt.length>0?{start:nt[0],end:nt[nt.length-1]}:null;return{chartData:Z,chartSources:k,dateRange:Zt}},[pe,he]);if(o&&!n)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!n?.connected)return e.jsx(Wl,{projectName:t,onConnected:()=>{(async()=>(await s.invalidateQueries({predicate:k=>{const F=k.queryKey[0];return typeof F?._id=="string"&&F._id.startsWith("getApiV1ProjectsByNameGa")}}),await $({current:!1})))()}});const st=i?.organicSharePctDisplay??"0%",Rt=i?.channelBreakdown?.organic.sharePctDisplay??st,wt=i?.channelBreakdown?.organic.sessions??i?.totalOrganicSessions??0,Vt=i?.aiSessionsDeduped??0,$e=i?.channelBreakdown?.ai.sessions??i?.aiSessionsBySession??0,Yt=i?.channelBreakdown?.ai.sharePctDisplay??i?.aiSharePctBySessionDisplay??"0%",Ue=i?new Set(i.aiReferrals.map(k=>k.source.toLowerCase())).size:0,Ee=ie[0]??null,St=i?.totalDirectSessions??0,Xt=i?.directSharePctDisplay??"0%",Jt=i?.channelBreakdown?.direct.sessions??St,us=i?.channelBreakdown?.direct.sharePctDisplay??Xt,it=i?.channelBreakdown?.other.sessions??i?.otherSessions??0,Ie=i?.channelBreakdown?.other.sharePctDisplay??i?.otherSharePctDisplay??"0%",h=i?.socialSessions??0,Y=i?.socialSharePctDisplay??"0%",se=i?.channelBreakdown?.social.sessions??h,Le=i?.channelBreakdown?.social.sharePctDisplay??Y,ve=i?new Set(i.socialReferrals.map(k=>k.source.toLowerCase())).size:0,He=Ne[0]??null;return e.jsxs(e.Fragment,{children:[P&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative",children:P}),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})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(L,{variant:"outline",size:"sm",disabled:g,onClick:ee(V),children:[e.jsx(Ls,{className:`w-3.5 h-3.5 mr-1.5 ${g?"animate-spin":""}`}),g?"Syncing…":"Sync"]}),e.jsxs(L,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:m,onClick:ee(Te),children:[e.jsx(wl,{className:"w-3.5 h-3.5 mr-1.5"}),"Disconnect"]})]})]}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4 flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Traffic Overview"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Site Traffic",e.jsx(ke,{text:`Aggregated traffic metrics from Google Analytics 4. Sessions and users are summed across the selected period.${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:Ul.map(k=>e.jsx("button",{type:"button",className:`px-3 py-1 text-xs rounded-full border transition-colors ${de===k?"bg-mono-700 border-mono-600 text-primary":"border-base text-secondary hover:border-strong hover:text-neutral"}`,onClick:()=>Ce(k),children:k==="all"?"All":k},k))})]}),i?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(Ws,{value:Ns(i.totalSessions),label:"Total Sessions",subtitle:i.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(Ws,{value:Ns(i.totalOrganicSessions),label:"Organic Sessions",subtitle:`${st} of total`,tone:"positive"}),e.jsx(Ws,{value:Ns(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."}),e.jsxs(L,{variant:"outline",size:"sm",disabled:g,onClick:ee(V),children:[e.jsx(Ls,{className:`w-3.5 h-3.5 mr-1.5 ${g?"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(ke,{text:"Decomposes GA4 sessions into five disjoint channels — known AI referrers first, then organic search, social, direct, and other channels. Known AI referrers are removed from their native GA4 channel before the residual Other bucket is computed. Other channels are the remaining GA4 session default channel groups, such as Referral, Email, Paid Search, Display, Cross-network, Shopping, Video, Affiliates, SMS, and Paid Other."})]})]}),tt&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(tt.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(tt.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),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",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:Fe.length>0?"AI vs. total sessions":"All sessions (baseline)"}),Fe.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),Fe.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(Lt,{width:"100%",height:"100%",children:e.jsxs(zt,{data:Nt,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Dt,{dataKey:"date",tick:_e,tickLine:!1,axisLine:{stroke:et},tickFormatter:Pt}),e.jsx(Tt,{tick:_e,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(It,{...ct,labelFormatter:jt,formatter:(k,F)=>{const Q=typeof k=="number"?k.toLocaleString():String(k??0),Z=String(F??"");return Z==="_totalSessions"?[Q,"Total Sessions"]:Z==="_organicSessions"?[Q,"Organic Sessions"]:[Q,Z]}}),e.jsx(ja,{wrapperStyle:{fontSize:11,color:qe.text},formatter:k=>k==="_totalSessions"?"Total Sessions":k==="_organicSessions"?"Organic Sessions":k}),e.jsx(qt,{type:"monotone",dataKey:"_totalSessions",stroke:qe.textFaint,fill:qe.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),Fe.map((k,F)=>e.jsx(qt,{type:"monotone",dataKey:k,stackId:"ai",stroke:pt[F%pt.length],fill:pt[F%pt.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(Ze,{label:"Organic",value:Rt,hint:`${wt.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(Ze,{label:"Social",value:Le,hint:`${se.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(Ze,{label:"Direct",value:us,hint:`${Jt.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(Ze,{label:"Known AI referrers (lower bound)",value:Yt,hint:`${$e.toLocaleString()} sessions`,tone:"positive",tooltip:"Sessions whose current sessionSource matched a known AI engine (e.g. chatgpt.com, claude.ai, gemini.google.com). These sessions are removed from their native GA4 channel in this card grid so the five buckets stay disjoint. This is a strict lower bound: most AI traffic strips the referrer and falls into Direct, so the true AI share is typically higher than what's shown here. The detail table below also surfaces firstUserSource and UTM-tagged AI signals."}),e.jsx(Ze,{label:"Other channels",value:Ie,hint:`${it.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."})]}),Ee&&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:Ee.source})," via ",Ee.medium,", accounting for ",Ee.sessions.toLocaleString()," sessions."]})]}),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?`${Ue} 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(Me,{label:"Source",sortKey:"source",current:N,dir:x,onSort:ye,align:"left"}),e.jsx(Me,{label:"Medium",sortKey:"medium",current:N,dir:x,onSort:ye,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(Me,{label:"Sessions",sortKey:"sessions",current:N,dir:x,onSort:ye,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(Me,{label:"Users",sortKey:"users",current:N,dir:x,onSort:ye,align:"right"})]})}),e.jsx("tbody",{children:ie.map(k=>e.jsx(Yl,{referral:k,totalSessions:Vt},`${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:oe.length>vs?`${Ae+1}–${Ae+Oe.length} of ${oe.length} rows`:oe.length>0?`${oe.length} rows`:"No landing-page rows"})]}),oe.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(Me,{label:"Landing Page",sortKey:"landingPage",current:M,dir:G,onSort:O,align:"left"}),e.jsx(Me,{label:"Source",sortKey:"source",current:M,dir:G,onSort:O,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(Me,{label:"Sessions",sortKey:"sessions",current:M,dir:G,onSort:O,align:"right"}),e.jsx(Me,{label:"Users",sortKey:"users",current:M,dir:G,onSort:O,align:"right"})]})}),e.jsx("tbody",{children:Oe.map(k=>e.jsx(Xl,{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:()=>ue(D-1),disabled:D<=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 ",D," of ",y]}),e.jsx("button",{type:"button",onClick:()=>ue(D+1),disabled:D>=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(ke,{text:"Tracks sessions classified as social traffic by GA4's default channel grouping (Organic Social and Paid Social). Google maintains the source-to-channel mapping."})]})]}),vt.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"})]}),Ke>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",dt.length-1," sources · ",Ke," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(Lt,{width:"100%",height:"100%",children:e.jsxs(zt,{data:vt,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Dt,{dataKey:"date",tick:_e,tickLine:!1,axisLine:{stroke:et},tickFormatter:Pt}),e.jsx(Tt,{tick:_e,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(It,{...ct,labelFormatter:jt,formatter:(k,F)=>{const Q=typeof k=="number"?k.toLocaleString():String(k??0),Z=String(F??"");if(Z===Qt)return[Q,"Total Social"];if(Z===Wt){const nt=`Other (${Ke} source${Ke===1?"":"s"})`;return[Q,nt]}return[Q,Kt(Z)]}}),e.jsx(qt,{type:"monotone",dataKey:Qt,stroke:$a,fill:qe.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),dt.map((k,F)=>{const Z=k===Wt?dn:pt[F%pt.length];return e.jsx(qt,{type:"monotone",dataKey:k,stackId:"social",stroke:Z,fill:Z,fillOpacity:.4,strokeWidth:1.5},k)})]})})}),e.jsx(Zl,{sources:dt,otherCount:Ke})]}),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(Ze,{label:"Social Sessions",value:Ns(h),hint:`${h.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(Ze,{label:"Share of Traffic",value:Y,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(Ze,{label:"Platforms",value:String(ve),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."})]}),He&&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:`${He.source} via ${He.medium}`,children:Aa(Kt(He.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:He.medium,children:["via ",Kt(He.medium)," · ",He.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(Ze,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(Ze,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(Ze,{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?Ne.length>ns&&!te?`Top ${ns} of ${Ne.length}`:`${Ne.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(Me,{label:"Source",sortKey:"source",current:_,dir:T,onSort:X,align:"left"}),e.jsx(Me,{label:"Medium",sortKey:"medium",current:_,dir:T,onSort:X,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(Me,{label:"Sessions",sortKey:"sessions",current:_,dir:T,onSort:X,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(Me,{label:"Users",sortKey:"users",current:_,dir:T,onSort:X,align:"right"})]})}),e.jsx("tbody",{children:(te?Ne:Ne.slice(0,ns)).map(k=>e.jsx(Jl,{referral:k,totalSessions:h},`${k.source}:${k.medium}:${k.channelGroup}`))})]})}),Ne.length>ns&&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:te?`Show top ${ns}`:`Show all ${Ne.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(ke,{text:"Landing pages ranked by session volume. Click column headers to sort. Organic % shows the share of sessions coming from Google organic search."})]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(Me,{label:"Landing Page",sortKey:"landingPage",current:C,dir:R,onSort:be,align:"left"}),e.jsx(Me,{label:"Sessions",sortKey:"sessions",current:C,dir:R,onSort:be,align:"right"}),e.jsx(Me,{label:"Organic",sortKey:"organicSessions",current:C,dir:R,onSort:be,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"}),e.jsx(Me,{label:"Users",sortKey:"users",current:C,dir:R,onSort:be,align:"right"})]})}),e.jsx("tbody",{children:q.map(k=>e.jsx(Vl,{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 ${Pa(i.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:i?`${i.topPages.length} pages · ${i.aiReferrals.length} AI rows · ${i.socialReferrals.length} social rows`:""})]})]})}function Wl({projectName:t,onConnected:s}){const[n,a]=r.useState(""),[i,l]=r.useState(null),[o,p]=r.useState(null),[g,u]=r.useState(!1),[m,d]=r.useState(null),P=r.useRef(null),b=r.useCallback(v=>{const C=v.target.files?.[0];if(!C)return;d(null),l(C.name);const z=new FileReader;z.onload=()=>{const R=z.result;try{const I=JSON.parse(R);if(!I.client_email||!I.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(R)}catch{d("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),p(null)}},z.onerror=()=>{d("Failed to read file."),p(null)},z.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}u(!0);try{await mi(t,{propertyId:n.trim(),keyJson:o});try{await oa(t)}catch{}s()}catch(v){d(v instanceof Error?v.message:"Failed to connect GA4")}finally{u(!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."}),m&&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:m}),e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{htmlFor:"ga4-property-id",className:"block text-xs font-medium text-secondary mb-1.5",children:"GA4 Property ID"}),e.jsx("input",{id:"ga4-property-id",type:"text",placeholder:"e.g. 123456789",value:n,onChange:v=>a(v.target.value),className:"w-full rounded-lg bg-bg-elevated/60 border border-default px-3 py-2 text-sm text-strong placeholder-mono-600 focus:outline-none focus:ring-1 focus:ring-mono-600"}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:"Find this in GA4 → Admin → Property Settings. It's a numeric ID, not the Measurement ID (G-XXXXXX)."})]}),e.jsxs("div",{className:"mb-5",children:[e.jsx("label",{className:"block text-xs font-medium text-secondary mb-1.5",children:"Service Account Key File"}),e.jsx("input",{ref:P,type:"file",accept:".json,application/json",onChange:b,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>P.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(kl,{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(L,{variant:"default",size:"sm",disabled:g||!n.trim()||!o,onClick:ee(A),children:g?"Connecting & syncing…":"Connect GA4"})]})}function Me({label:t,sortKey:s,current:n,dir:a,onSort:i,align:l}){const o=n===s;return e.jsx("th",{className:`py-1 ${l==="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 La={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function Ws({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 ${La[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Ze({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(ke,{text:i})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${La[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Vl({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 za={session:"Session",first_user:"First Visit",manual_utm:"UTM"},Da={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 Yl({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=za[t.sourceDimension]??t.sourceDimension,i=Da[t.sourceDimension]??"";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 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 Xl({row:t}){const s=za[t.sourceDimension]??t.sourceDimension,n=Da[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 Jl({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),l=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:l}),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 Zl({sources:t,otherCount:s}){const n=[{key:Qt,color:$a,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const i=t[a];if(i===Wt)n.push({key:Wt,color:dn,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const l=Kt(i);n.push({key:i,color:pt[a%pt.length]??dn,label:Aa(l,32),tooltip:l})}}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 eo(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 to=["7d","30d","90d","all"],ws=500,xt=25;function so({projectName:t,refreshNonce:s}){const n=yt(),[a,i]=r.useState(!1),[l,o]=r.useState([]),[p,g]=r.useState([]),[u,m]=r.useState([]),[d,P]=r.useState(null),[b,A]=r.useState([]),[v,C]=r.useState([]),[z,R]=r.useState(null),[I,N]=r.useState(""),[j,x]=r.useState(""),[E,_]=r.useState("30"),[H,T]=r.useState(!1),[S,M]=r.useState("30d"),[U,G]=r.useState({startDate:"",endDate:"",query:"",page:"",limit:"20"}),[ne,fe]=r.useState(0),[ue,pe]=r.useState(!1),[me,he]=r.useState(0),[je,f]=r.useState(!1),[B,te]=r.useState(""),[le,de]=r.useState(!0),[Ce,$]=r.useState(!1),[V,Te]=r.useState(!1),[be,ye]=r.useState(!1),[X,O]=r.useState(!1),[q,ie]=r.useState(!1),[oe,y]=r.useState(!1),[D,Ae]=r.useState(null),[Oe,Ne]=r.useState(!1),[vt,dt]=r.useState(!1),[Ke,Nt]=r.useState(null),[Fe,tt]=r.useState(""),[st,Rt]=r.useState(!1),[wt,Vt]=r.useState(!1),[$e,Yt]=r.useState("indexed"),[Ue,Ee]=r.useState(null),St=!!(U.query.trim()||U.page.trim()||Ue),Xt=Ue!==null,Jt=r.useMemo(()=>{if(!Ue)return u;const{key:c,dir:w}=Ue;return[...u].sort((J,ce)=>{const ze=c===$t.CTR?Number.isFinite(J.ctr)?J.ctr:0:J[c],Ge=c===$t.CTR?Number.isFinite(ce.ctr)?ce.ctr:0:ce[c];return w==="asc"?ze-Ge:Ge-ze})},[u,Ue]),[us,it]=r.useState([]),[Ie,h]=r.useState(null),[Y,se]=r.useState(1);r.useEffect(()=>{se(1)},[D,$e,Ie]);const Le=r.useMemo(()=>Ie?(D?.reasonGroups??[]).find(c=>c.reason===Ie):void 0,[D,Ie]),ve=r.useMemo(()=>D?$e==="indexed"?D.indexed:$e==="deindexed"?D.deindexed:$e==="notIndexed"?Ie?Le?.urls??[]:(D.reasonGroups??[]).length===0?D.notIndexed:[]:[]:[],[D,$e,Ie,Le]),He=Math.max(1,Math.ceil(ve.length/xt)),k=Math.min(Math.max(1,Y),He),F=(k-1)*xt,Q=ve.length>xt,Z=ve.length===0?0:F+1,nt=Math.min(F+xt,ve.length),Zt=r.useMemo(()=>D?.indexed.slice(F,F+xt)??[],[D,F]),we=r.useMemo(()=>D?.notIndexed.slice(F,F+xt)??[],[D,F]),We=r.useMemo(()=>D?.deindexed.slice(F,F+xt)??[],[D,F]),Et=r.useMemo(()=>(Le?.urls??[]).slice(F,F+xt),[Le,F]),[ut,at]=r.useState(!1),[jn,xe]=r.useState(null),[rt,ms]=r.useState(null),[yn,lt]=r.useState(null);function Fa(c,w){const J=hl(c),ce=eo(J);ce?(ms(ce),xe(null)):(ms(null),xe(J.message||w))}const Se=l.find(c=>c.connectionType==="gsc"),Ba=u.length>0||b.length>0||v.length>0,qs=xi(),es=hi(),Gs=pi();async function vn(c){if(!c){g([]),N("");return}Te(!0);try{const{sites:w}=await n.fetchQuery({...Ai({client:K,path:{name:t}}),staleTime:Re});g(w),N(c.propertyId??w[0]?.siteUrl??""),ms(null)}catch(w){g([]),Fa(w,"Failed to load Search Console properties")}finally{Te(!1)}}async function Mt(c){O(!0);const w=c??ne;try{const J=parseInt(U.limit,10)||20,ce=St?ws:J+1,ze=St?0:w,Ge={limit:String(ce)};U.startDate&&(Ge.startDate=U.startDate),U.endDate&&(Ge.endDate=U.endDate),U.query&&(Ge.query=U.query),U.page&&(Ge.page=U.page),ze>0&&(Ge.offset=String(ze)),S&&S!=="all"&&!U.startDate&&(Ge.window=S);const Ve=await n.fetchQuery({...bi({client:K,path:{name:t},query:Ge}),staleTime:Re});St?(pe(!1),m(Ve),he(Ve.length),f(!0)):(pe(Ve.length>J),m(Ve.slice(0,J)),he(0),f(!1))}catch(J){m([]),pe(!1),he(0),xe(J instanceof Error?J.message:"Failed to load GSC performance data")}finally{O(!1)}}async function _s(){try{const c={};U.startDate&&(c.startDate=U.startDate),U.endDate&&(c.endDate=U.endDate),S&&S!=="all"&&!U.startDate&&(c.window=S);const w=await n.fetchQuery({...ji({client:K,path:{name:t},query:c}),staleTime:Re});P(w)}catch{P(null)}}async function xs(){ie(!0);try{const c=B.trim()||void 0,w={limit:"20"};c&&(w.url=c);const[J,ce]=await Promise.all([n.fetchQuery({...ki({client:K,path:{name:t},query:w}),staleTime:Re}),n.fetchQuery({...Ci({client:K,path:{name:t}}),staleTime:Re})]);A(J),C(ce)}catch(c){A([]),C([]),xe(c instanceof Error?c.message:"Failed to load GSC inspection history")}finally{ie(!1)}}async function Nn(){Ne(!0);try{const[c,w]=await Promise.all([n.fetchQuery({...ca({client:K,path:{name:t}}),staleTime:Re}),n.fetchQuery({...wi({client:K,path:{name:t}}),staleTime:Re}).catch(()=>[])]);Ae(c),it(w)}catch(c){Ae(null),it([]),xe(c instanceof Error?c.message:"Failed to load coverage data")}finally{Ne(!1)}}async function wn(c){at(!0),xe(null);try{const w=await Ln(t,{urls:c}),{succeeded:J,failed:ce,total:ze}=w.summary;re({title:"Indexing requested",detail:ce===0?`${J} URL${J!==1?"s":""} submitted for indexing.`:`${J}/${ze} submitted successfully, ${ce} failed.`,tone:ce===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(w){xe(w instanceof Error?w.message:"Failed to request indexing")}finally{at(!1)}}async function qa(){at(!0),xe(null);try{const c=await Ln(t,{urls:[],allUnindexed:!0}),{succeeded:w,failed:J,total:ce}=c.summary;re({title:"Indexing requested",detail:J===0?`${w} unindexed URL${w!==1?"s":""} submitted for indexing.`:`${w}/${ce} submitted successfully, ${J} failed.`,tone:J===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(c){xe(c instanceof Error?c.message:"Failed to request indexing")}finally{at(!1)}}async function hs(){if(Fe.trim()){Rt(!0),xe(null);try{await Ni(t,"gsc",Fe.trim()),await n.invalidateQueries({predicate:c=>{const w=c.queryKey[0];return typeof w?._id=="string"&&w._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),o(c=>c.map(w=>w.connectionType==="gsc"?{...w,sitemapUrl:Fe.trim()}:w)),re({title:"Sitemap URL saved",detail:`${t} will use the updated sitemap URL.`,tone:"positive",dedupeKey:`gsc:sitemap:${t}`,dedupeMode:"drop"}),tt("")}catch(c){xe(c instanceof Error?c.message:"Failed to save sitemap URL")}finally{Rt(!1)}}}async function Sn(){xe(null);try{const c=await es.mutateAsync({projectName:t,projectLabel:t});Nt(c.sitemaps),o(w=>w.map(J=>J.connectionType==="gsc"?{...J,sitemapUrl:c.primarySitemapUrl}:J))}catch{}}async function Ga(){dt(!0),xe(null);try{const c=await Pi(t);n.setQueryData(Li({client:K,path:{name:t}}),c),Nt(c.sitemaps),c.sitemaps.length===0&<("No sitemaps found in this GSC property. Submit a sitemap in Google Search Console first.")}catch(c){xe(c instanceof Error?c.message:"Failed to list sitemaps")}finally{dt(!1)}}async function kn(){de(!0),xe(null);try{const[c,w]=await Promise.all([fi().catch(()=>null),n.fetchQuery({...xn({client:K,path:{name:t}}),staleTime:Re}).catch(()=>[])]);i(!!c?.google?.configured),o(w);const J=w.find(ce=>ce.connectionType==="gsc");await Promise.all([vn(J),Mt(),_s(),xs(),Nn()])}finally{de(!1)}}r.useEffect(()=>{kn()},[t,s]),r.useEffect(()=>{fe(0),Mt(0),_s()},[S]);const Cn=r.useRef(!1);r.useEffect(()=>{if(!Cn.current){Cn.current=!0;return}fe(0),Mt(0)},[Xt]);async function _a(){if(!a){xe("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}$(!0),xe(null),lt(null);try{const{authUrl:c}=await vi(t,"gsc");if(!c.startsWith("https://accounts.google.com/")){xe("Unexpected OAuth redirect URL. Please try again.");return}const w=window.open(c,"_blank","width=600,height=700");if(!w){window.location.assign(c);return}lt("Finish the Google consent flow in the popup, then close it to refresh this project.");const J=window.setInterval(()=>{w.closed&&(window.clearInterval(J),lt(null),n.invalidateQueries({predicate:ce=>{const ze=ce.queryKey[0];return typeof ze?._id=="string"&&ze._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),kn())},1e3)}catch(c){xe(c instanceof Error?c.message:"Failed to start OAuth flow")}finally{$(!1)}}async function Ua(){xe(null),lt(null);try{await yi(t,"gsc"),await n.invalidateQueries({predicate:c=>{const w=c.queryKey[0];return typeof w?._id=="string"&&w._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),o(c=>c.filter(w=>w.connectionType!=="gsc")),g([]),N("")}catch(c){xe(c instanceof Error?c.message:"Failed to disconnect")}}async function Qa(){if(I){ye(!0),xe(null);try{await $i(t,"gsc",I),await n.invalidateQueries({predicate:c=>{const w=c.queryKey[0];return typeof w?._id=="string"&&w._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),o(c=>c.map(w=>w.connectionType==="gsc"?{...w,propertyId:I}:w)),re({title:"GSC property updated",detail:`${t} is now linked to ${I}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(c){xe(c instanceof Error?c.message:"Failed to save GSC property")}finally{ye(!1)}}}async function Ka(){xe(null),lt(null);try{await qs.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(E,10)||void 0,full:H||void 0}}),await n.invalidateQueries({predicate:c=>{const w=c.queryKey[0];return typeof w?._id=="string"&&w._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}})}catch{}}async function An(){if(j.trim()){y(!0),xe(null),lt(null);try{const c=await Si(t,j.trim());await n.invalidateQueries({predicate:w=>{const J=w.queryKey[0];return typeof J?._id=="string"&&J._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),R(c),x(""),await xs()}catch(c){xe(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"})]})}),rt&&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:rt.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:rt.message}),(Bt(rt.enableUrl)||Bt(rt.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[Bt(rt.enableUrl)&&e.jsx("a",{href:Bt(rt.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 ↗"}),Bt(rt.indexingApiUrl)&&e.jsx("a",{href:Bt(rt.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:()=>ms(null),children:"×"})]})}),jn&&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:[jn,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>xe(null),children:"×"})]}),yn&&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:[yn,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:[Se?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:Se.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Last updated ",Je(Se.updatedAt)]}),e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:ee(Ua),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(ae,{tone:a?"caution":"negative",children:a?"Ready to connect":"App credentials missing"})]}),e.jsxs("div",{className:"mt-3 rounded-lg border border-default bg-surface px-4 py-5",children:[e.jsx("p",{className:"text-sm text-neutral",children:a?"Generate a Google OAuth link for this project and have the client sign in with a Google account that already has access to the correct Search Console property.":"Set Google OAuth client credentials first. Once configured, you can generate a consent link for this project domain."}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[a?e.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:Ce,onClick:ee(_a),children:Ce?"Opening…":"Connect Google Search Console"}):e.jsx(L,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(ft,{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."})]})]})]}),Se&&!Se.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."}),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(L,{type:"button",size:"sm",disabled:es.isPending||!Se.propertyId,onClick:ee(Sn),children:es.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:Fe,onChange:c=>tt(c.target.value),onKeyDown:c=>c.key==="Enter"&&void hs()}),e.jsx(L,{type:"button",size:"sm",variant:"outline",disabled:st||!Fe.trim(),onClick:ee(hs),children:st?"Saving…":"Save sitemap URL"})]})]})]})]})}),(Se||Ba)&&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:[D&&D.notIndexed.length>0&&e.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:ut,onClick:()=>{qa()},children:ut?"Requesting…":`Request indexing (${D.notIndexed.length})`}),e.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:Oe,onClick:()=>{Nn()},children:Oe?"Loading…":"Refresh coverage"})]})]}),D&&D.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const c=D.summary.indexed+D.summary.notIndexed,w=c>0?D.summary.indexed/c:0,J=c>0?D.summary.notIndexed/c:0,ce=54,ze=2*Math.PI*ce,Ge=ze*(1-w),Ve=ze*J,Ot=ze*w;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:ce,fill:"none",stroke:qe.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:ce,fill:"none",stroke:bt.positiveDeep,strokeWidth:"14",strokeDasharray:ze,strokeDashoffset:Ge,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),D.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:ce,fill:"none",stroke:qe.textFaint,strokeWidth:"14",strokeDasharray:`${Ve} ${ze-Ve}`,strokeDashoffset:-Ot,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:[(w*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:D.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:D.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:["Not indexed",(D.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-faint",children:["· ",(D.reasonGroups??[]).length," ",(D.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),D.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:D.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 w=c==="indexed"?D.indexed.length:c==="notIndexed"?D.notIndexed.length:D.deindexed.length,J=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 ${$e===c?"bg-mono-700 text-heading":"text-secondary hover:bg-mono-800 hover:text-strong"}`,onClick:()=>{Yt(c),h(null)},children:[J," (",w,")"]},c)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[$e==="indexed"&&D.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:Zt.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))})]}),$e==="notIndexed"&&!Ie&&(D.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:(D.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:()=>h(c.reason),onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),h(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))})]}),$e==="notIndexed"&&!Ie&&(D.reasonGroups??[]).length===0&&D.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:we.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))})]}),$e==="notIndexed"&&Ie&&(()=>{const c=(D.reasonGroups??[]).find(w=>w.reason===Ie);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:()=>h(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":""]})]}),e.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:ut,onClick:()=>{wn(c.urls.map(w=>w.url))},children:ut?"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"}),e.jsx("th",{className:"w-8"})]})}),e.jsx("tbody",{children:Et.map(w=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:w.url}),e.jsx("td",{className:"text-secondary",children:w.crawlTime?w.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-strong transition-colors",disabled:ut,onClick:()=>{wn([w.url])},title:"Request indexing",children:"Index"})})]},w.id))})]})]}):null})(),$e==="deindexed"&&D.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:We.map((c,w)=>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}-${w}`))})]}),($e==="indexed"&&D.indexed.length===0||$e==="notIndexed"&&!Ie&&D.notIndexed.length===0||$e==="deindexed"&&D.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),Q&&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:Z.toLocaleString("en-US")}),"–",e.jsx("span",{className:"text-neutral",children:nt.toLocaleString("en-US")})," of"," ",e.jsx("span",{className:"text-neutral",children:ve.length.toLocaleString("en-US")})," URLs"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>se(c=>Math.max(1,c-1)),disabled:k<=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(dl,{className:"size-3.5"}),"Prev"]}),e.jsxs("span",{className:"tabular-nums",children:["Page ",e.jsx("span",{className:"text-strong",children:k})," of"," ",e.jsx("span",{className:"text-strong",children:He})]}),e.jsxs("button",{type:"button",onClick:()=>se(c=>Math.min(He,c+1)),disabled:k>=He,"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(Is,{className:"size-3.5"})]})]})]})]})]}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:Oe?"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:to.map(c=>e.jsx("button",{type:"button",role:"tab","aria-selected":S===c,className:`px-2.5 py-1 text-xs rounded-full border transition-colors ${S===c?"bg-mono-700 border-mono-600 text-primary":"border-base text-secondary hover:border-strong hover:text-neutral"}`,onClick:()=>M(c),children:c==="all"?"All":c},c))}),e.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:X,onClick:()=>{fe(0),Mt(0),_s()},children:X?"Loading…":"Apply filters"})]})]}),d&&d.daily.length>0&&(()=>{const c=d.daily,w=Math.max(...c.map(ge=>ge.impressions),1),{clicks:J,impressions:ce,ctr:ze}=d.totals,Ge=(ze*100).toFixed(1),Ve=700,Ot=220,Ye={top:12,bottom:36,left:48,right:12},Ha=Ve-Ye.left-Ye.right,Ft=Ot-Ye.top-Ye.bottom,ts=Ha/c.length,ps=Math.max(Math.min(ts*.35,24),4),$n=Math.max(ps*.15,1),Wa=ge=>{if(ge<=0)return 1;const ot=Math.pow(10,Math.floor(Math.log10(ge))),Xe=ge/ot,mt=Xe<=1.5?1.5:Xe<=3?3:Xe<=5?5:10;return Math.ceil(mt*ot)},gs=4,fs=Math.ceil(Wa(w)/gs)*gs,Va=Array.from({length:gs+1},(ge,ot)=>fs/gs*ot),Ya=ge=>ge>=1e3?`${(ge/1e3).toFixed(ge>=1e4?0:1)}k`:String(ge);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:J.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:ce.toLocaleString()})]})]}),e.jsxs("span",{className:"text-xs text-muted",children:["CTR ",e.jsxs("span",{className:"text-caution-400 tabular-nums font-medium",children:[Ge,"%"]})]})]}),e.jsx("div",{className:"relative w-full",style:{aspectRatio:`${Ve} / ${Ot}`},children:e.jsxs("svg",{viewBox:`0 0 ${Ve} ${Ot}`,className:"h-full w-full",children:[Va.map((ge,ot)=>{const Xe=Ye.top+Ft-ge/fs*Ft;return e.jsxs("g",{children:[e.jsx("line",{x1:Ye.left,y1:Xe,x2:Ve-Ye.right,y2:Xe,stroke:qe.gridLine,strokeWidth:"1"}),e.jsx("text",{x:Ye.left-6,y:Xe+3.5,textAnchor:"end",fill:qe.text,fontSize:"10",fontFamily:"inherit",children:Ya(ge)})]},`t-${ot}`)}),c.map((ge,ot)=>{const Xe=Ye.left+ts*ot+ts/2,mt=ge.impressions/fs*Ft,bs=ge.clicks/fs*Ft;return e.jsxs("g",{children:[e.jsx("title",{children:`${ge.date}
|
|
2
2
|
Clicks: ${ge.clicks}
|
|
3
3
|
Impressions: ${ge.impressions}
|
|
4
4
|
CTR: ${(ge.ctr*100).toFixed(1)}%`}),e.jsx("rect",{x:Xe-ps-$n/2,y:Ye.top+Ft-mt,width:ps,height:Math.max(mt,1),rx:2,fill:Qe[1],opacity:.85}),e.jsx("rect",{x:Xe+$n/2,y:Ye.top+Ft-bs,width:ps,height:Math.max(bs,1),rx:2,fill:bt.positiveDeep,opacity:.85})]},ge.date)}),(()=>{const ge=Math.min(c.length,7);return Array.from({length:ge},(ot,Xe)=>{const mt=c.length===1?0:Math.round(Xe/(ge-1)*(c.length-1)),bs=Ye.left+ts*mt+ts/2;return e.jsx("text",{x:bs,y:Ot-8,textAnchor:"middle",fill:qe.textDim,fontSize:"10",fontFamily:"inherit",children:c[mt].date.slice(5)},`xl-${mt}`)})})()]})})]})})(),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:U.startDate,onChange:c=>G(w=>({...w,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:U.endDate,onChange:c=>G(w=>({...w,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:U.query,onChange:c=>G(w=>({...w,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:U.page,onChange:c=>G(w=>({...w,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:U.limit,onChange:c=>G(w=>({...w,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 ",ws.toLocaleString()," matching rows load so sorting covers the full set."]}),u.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($t).map(c=>e.jsx("th",{className:"text-right","aria-sort":Ue?.key===c?Ue.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:()=>Ee(w=>w?.key===c?w.dir==="desc"?{key:c,dir:"asc"}:null:{key:c,dir:"desc"}),children:[gi[c],Ue?.key===c?Ue.dir==="desc"?" ↓":" ↑":""]})},c))]})}),e.jsx("tbody",{children:Jt.map((c,w)=>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}:${w}`))})]})}),je?e.jsx("div",{className:"mt-3 text-xs text-muted",children:e.jsxs("span",{className:"tabular-nums",children:["Showing ",me.toLocaleString()," matching row",me===1?"":"s",me>=ws?` (capped at ${ws.toLocaleString()} — narrow the filter to see more)`:""]})}):(ne>0||ue)&&(()=>{const c=parseInt(U.limit,10)||20,w=ne+1,J=ne+u.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 ",w.toLocaleString()," – ",J.toLocaleString(),ue?"+":""]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:X||ne===0,onClick:()=>{const ce=Math.max(0,ne-c);fe(ce),Mt(ce)},children:"Previous"}),e.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:X||!ue,onClick:()=>{const ce=ne+c;fe(ce),Mt(ce)},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"})]})}),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:j,onChange:c=>x(c.target.value),onKeyDown:c=>c.key==="Enter"&&void An()}),e.jsx(L,{type:"button",size:"sm",disabled:oe||!Se?.propertyId||!j.trim(),onClick:ee(An),children:oe?"Inspecting…":"Inspect URL"})]}),z&&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:z.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:z.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:Pn(z.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(z.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.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:q,onClick:()=>{xs()},children:q?"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:B,onChange:c=>te(c.target.value)}),e.jsx(L,{type:"button",size:"sm",variant:"outline",disabled:q,onClick:()=>{xs()},children:"Apply filter"})]}),b.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:b.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:Pn(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"})]})}),v.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Previous"}),e.jsx("th",{className:"text-left",children:"Current"}),e.jsx("th",{className:"text-left",children:"Changed at"})]})}),e.jsx("tbody",{children:v.map(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."})]})]}),Se&&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:()=>Vt(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 ${wt?"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"})]})}),wt&&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:I,disabled:V||p.length===0,onChange:c=>N(c.target.value),children:p.length===0?e.jsx("option",{value:"",children:V?"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.jsx(L,{type:"button",size:"sm",variant:"outline",disabled:V,onClick:()=>{vn(Se)},children:V?"Refreshing…":"Refresh properties"}),e.jsx(L,{type:"button",size:"sm",disabled:!I||be,onClick:ee(Qa),children:be?"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:E,onChange:c=>_(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:H,onChange:c=>T(c.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(L,{type:"button",size:"sm",disabled:qs.isPending||!Se.propertyId,onClick:ee(Ka),children:qs.isPending?"Queueing…":"Queue sync"}),!Se.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:[Se.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:Se.sitemapUrl})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(L,{type:"button",size:"sm",variant:"outline",disabled:vt||!Se.propertyId,onClick:()=>{Ga()},children:vt?"Loading…":"Browse sitemaps from GSC"}),e.jsx(L,{type:"button",size:"sm",variant:"outline",disabled:es.isPending||!Se.propertyId,onClick:ee(Sn),children:es.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."}),Ke&&Ke.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 (",Ke.length,")"]}),Ke.map(c=>{const w=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:[w&&e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-neutral",children:[w.indexed," / ",w.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:()=>tt(c.path),children:"Use"})]})]},c.path)})]}),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:Se.sitemapUrl?"Update sitemap URL…":"https://example.com/sitemap.xml",value:Fe,onChange:c=>tt(c.target.value),onKeyDown:c=>c.key==="Enter"&&Fe.trim()&&void hs()}),e.jsx(L,{type:"button",size:"sm",disabled:st||!Fe.trim(),onClick:ee(hs),children:st?"Saving…":Se.sitemapUrl?"Update":"Save"})]}),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(L,{type:"button",size:"sm",variant:"outline",disabled:Gs.isPending||!Se.propertyId,onClick:ee(async()=>{const w=document.getElementById(`gsc-sitemap-inspect-${t}`)?.value?.trim()||Se.sitemapUrl||void 0;xe(null),lt(null);try{await Gs.mutateAsync({projectName:t,projectLabel:t,opts:{sitemapUrl:w}})}catch{}}),children:Gs.isPending?"Queueing…":"Inspect sitemap"})]}),!Se.propertyId&&e.jsx("p",{className:"text-xs text-caution-400",children:"Select a Search Console property first."})]})]})]})]})]})]})}const no=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function ao({projectName:t,projectId:s}){const n=yt(),[a,i]=r.useState(null),[l,o]=r.useState(null),[p,g]=r.useState(!1),u=Pe(xn({client:K,path:{name:t}})),m=u.data?.find($=>$.connectionType==="gbp"),d=!!m,P=a?{locationName:a}:void 0,b=Pe({...zi({client:K,path:{name:t}}),enabled:d}),A=Pe({...Di({client:K,path:{name:t},query:P}),enabled:d}),v=Pe({...Ti({client:K,path:{name:t},query:P}),enabled:d}),C=Pe({...Ii({client:K,path:{name:t},query:P}),enabled:d}),z=Pe({...Ri({client:K,path:{name:t},query:P}),enabled:d}),R=Pe({...Ei({client:K,path:{name:t},query:P}),enabled:d}),I=Pe({queryKey:["gbp-section-insights",t],queryFn:()=>Mi(t),enabled:d});function N(){n.invalidateQueries({predicate:$=>{const V=$.queryKey[0];return typeof V?._id=="string"&&V._id.startsWith("getApiV1ProjectsByNameGbp")}})}const j=os({...Fi(),onSuccess:$=>{Oi({id:$.runId,projectId:s,kind:cs["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),re({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),x=r.useSyncExternalStore(Bi,zn,zn),E=Object.values(x.runs).some($=>$.kind===cs["gbp-sync"]&&$.projectId===s),_=j.isPending||E,H=os({...qi(),onSuccess:()=>N()});if(r.useEffect(()=>{if(!a||!b.data)return;const $=b.data.locations.filter(V=>V.selected);($.length<=1||!$.some(V=>V.locationName===a))&&i(null)},[a,b.data]),r.useEffect(()=>{if(!l||!b.data)return;(a?[a]:b.data.locations.filter(V=>V.selected).map(V=>V.locationName)).includes(l)||o(null)},[l,b.data,a]),u.isLoading)return null;if(!m){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((V,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:V.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:V.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:V.note})]})]},V.title))})]})})}const T=A.data,S=b.data?.locations??[],M=S.filter($=>$.selected),U=v.data?.keywords??[],G=C.data?.lodging??[],ne=z.data?.placeActions??[],fe=R.data?.places??[],ue=S.length>0?S[0].accountName:m.domain,pe=a?S.find($=>$.locationName===a)?.displayName??null:null,me=a?S.filter($=>$.locationName===a):M,he=new Set(me.map($=>$.locationName)),je=G.filter($=>he.has($.locationName)),f=ne.filter($=>he.has($.locationName)),B=fe.filter($=>he.has($.locationName)),te=new Set(M.map($=>$.locationName)),le=a?U:U.filter($=>te.has($.locationName)),de=!a&&M.length>1,Ce=(I.data??[]).filter($=>!$.dismissed&&no.has($.type)&&(!pe||$.query===pe||$.query===a||$.title.startsWith(pe)));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(ke,{text:"How AI answer engines and Maps surface this business: performance, search terms, and how your public listing compares to the profile you control."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ae,{tone:"positive",children:"Connected"}),e.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:_,onClick:()=>j.mutate({client:K,path:{name:t},body:{}}),children:_?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-muted",children:[ue?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-secondary",children:ue})," · "]}):null,b.data?`${b.data.totalSelected} of ${b.data.totalDiscovered} locations tracked`:"Loading locations…"]}),M.length>1&&e.jsxs("div",{className:"mb-5 flex flex-wrap gap-1.5",role:"tablist","aria-label":"Location",children:[e.jsx(Qn,{label:"All locations",active:a===null,onClick:()=>i(null)}),M.map($=>e.jsx(Qn,{label:$.displayName,active:a===$.locationName,onClick:()=>i($.locationName)},$.id))]}),M.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:[Ce.length>0&&e.jsxs("div",{className:"mb-6 grid gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Needs attention"}),Ce.map($=>e.jsx("div",{className:["insight-card",bo($.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(ke,{text:$.recommendation.reason})]})},$.id))]}),T&&e.jsx(No,{performance:T.performance,freshness:T.freshness,timeseries:T.timeseries}),T?.profileCompleteness&&e.jsx(io,{summary:T.profileCompleteness}),me.length>0&&e.jsx(ro,{locations:me,lodging:je,places:B,placeActions:f,expandedLocation:l,onToggleExpanded:$=>{o(V=>V===$?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"}),v.data&&v.data.total>0&&e.jsxs("span",{className:"text-[11px] text-faint",children:[v.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"}),de&&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}),de&&e.jsx("td",{className:"text-muted",children:S.find(V=>V.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:()=>g($=>!$),"aria-expanded":p,children:[e.jsx("span",{"aria-hidden":"true",children:p?"▾":"▸"})," Manage locations (",S.length,")"]}),p&&e.jsx("div",{className:"mt-3",children:S.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"}),e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:S.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(ae,{tone:$.selected?"positive":"neutral",children:$.selected?"Tracked":"Not tracked"})}),e.jsx("td",{className:"text-right",children:e.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:H.isPending,onClick:()=>H.mutate({client:K,path:{name:t,locationName:$.locationName},body:{selected:!$.selected}}),children:$.selected?"Untrack":"Track"})})]},$.id))})]})})]})]})})}function Qn({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 io({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:as(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:as(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:as(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:as(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:as(t.withSecondaryCategories,s,"caution")},{label:"Closed",value:String(t.permanentlyClosed+t.temporarilyClosed),detail:t.permanentlyClosed||t.temporarilyClosed?`${t.permanentlyClosed} permanent, ${t.temporarilyClosed} temporary`:"reported open",tone:t.permanentlyClosed>0?"negative":t.temporarilyClosed>0?"caution":"positive"}];return e.jsxs("div",{className:"mb-6 border-y border-default py-3",children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Owner profile · Business Information"}),e.jsx(ke,{text:"Counts selected locations where Google Business Information returned the owner-authored field. A missing value means it was not returned by this API response, not that every Google surface is empty."})]}),e.jsx("div",{className:"grid gap-x-5 gap-y-3 sm:grid-cols-2 lg:grid-cols-3",children:n.map(a=>e.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_auto] items-baseline gap-3",children:[e.jsx("span",{className:"text-xs text-muted",children:a.label}),e.jsx("span",{className:`font-mono text-sm tabular-nums ${fo(a.tone)}`,children:a.value}),a.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-faint",children:a.detail})]},a.label))})]})}function ro({locations:t,lodging:s,places:n,placeActions:a,expandedLocation:i,onToggleExpanded:l}){const o=new Map(s.map(u=>[u.locationName,u])),p=new Map(n.map(u=>[u.locationName,u])),g=new Map;for(const u of a){const m=g.get(u.locationName)??[];m.push(u),g.set(u.locationName,m)}return e.jsxs("div",{className:"mb-6",children:[e.jsxs("div",{className:"section-head section-head-inline mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Source evidence"}),e.jsx(ke,{text:"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(u=>{const m=o.get(u.locationName)??null,d=p.get(u.locationName)??null,P=g.get(u.locationName)??[],b=i===u.locationName;return e.jsxs(r.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:u.displayName}),e.jsx("p",{className:"mt-1 text-xs text-faint",children:u.primaryCategoryDisplayName??"Primary category not returned"}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[e.jsx(ae,{tone:u.selected?"positive":"neutral",children:u.selected?"Tracked":"Not tracked"}),u.openStatus&&u.openStatus!=="OPEN"&&e.jsx(ae,{tone:u.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:Ta(u.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(oo,{location:u})}),e.jsx("td",{children:e.jsx(co,{lodging:m})}),e.jsx("td",{children:e.jsx(mo,{place:d,mapsUri:u.mapsUri})}),e.jsx("td",{children:e.jsx(ho,{actions:P})}),e.jsx("td",{className:"text-right",children:e.jsx(L,{type:"button",variant:"outline",size:"sm",onClick:()=>l(u.locationName),children:b?"Hide":"Details"})})]}),b&&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(go,{location:u,lodging:m,place:d,placeActions:P})})})]},u.id)})})]})})]})}function lo(t){return[{label:"Description",tone:At(t.description)?"positive":"neutral",value:At(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:At(t.primaryPhone)?"positive":"neutral",value:At(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:At(t.websiteUri)?"positive":"neutral",value:At(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 oo({location:t}){const s=lo(t);return e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>e.jsxs(ae,{tone:n.tone,children:[n.label," ",n.value]},n.label))})}function co({lodging:t}){return e.jsx(pn,{...uo(t)})}function uo(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 mo({place:t,mapsUri:s}){return e.jsx(pn,{...xo(t,s)})}function xo(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 ho({actions:t}){return e.jsx(pn,{...po(t)})}function po(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 pn({tone:t,label:s,detail:n}){return e.jsxs("div",{children:[e.jsx(ae,{tone:t,children:s}),e.jsx("p",{className:"mt-1.5 text-xs leading-5 text-faint",children:n})]})}function go({location:t,lodging:s,place:n,placeActions:a}){const i=s?yo(s.attributes):[];return e.jsxs("div",{className:"grid gap-5 text-xs lg:grid-cols-3",children:[e.jsxs(Vs,{title:"Owner profile · Business Information",children:[e.jsx(Be,{label:"Primary category",value:t.primaryCategoryDisplayName??"Not returned"}),e.jsx(Be,{label:"Secondary categories",value:t.additionalCategories.length>0?t.additionalCategories.join(", "):"Not returned"}),e.jsx(Be,{label:"Description",value:At(t.description)?t.description:"Not returned"}),e.jsx(Be,{label:"Hours",value:t.regularHours?"Returned by Google":"Not returned"}),e.jsx(Be,{label:"Service area",value:t.serviceArea?"Returned by Google":"Not returned"}),e.jsx(Be,{label:"Phone",value:t.primaryPhone??"Not returned"}),e.jsx(Be,{label:"Website",value:t.websiteUri??"Not returned"}),e.jsx(Be,{label:"Open status",value:Ta(t.openStatus)}),e.jsx(Be,{label:"Opening date",value:t.openingDate??"Not returned"})]}),e.jsx(Vs,{title:"Hotel data · Lodging API",children:s?e.jsxs(e.Fragment,{children:[e.jsx(Be,{label:"Last checked",value:Kn(s.syncedAt)}),e.jsx(Be,{label:"Groups returned",value:String(s.populatedGroupCount)}),e.jsx(Be,{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(Vs,{title:"Public listing + CTAs",children:[n?e.jsxs(e.Fragment,{children:[e.jsx(Be,{label:"Places tier",value:n.tier}),e.jsx(Be,{label:"Last checked",value:Kn(n.syncedAt)}),e.jsx(Be,{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(l=>e.jsxs("div",{className:"grid gap-0.5",children:[e.jsxs("span",{className:"font-medium text-neutral",children:[zs(l.placeActionType),l.isPreferred?" · preferred":""]}),e.jsxs("span",{className:"text-faint",children:[zs(l.providerType),l.uri?` · ${jo(l.uri)}`:""]})]},l.placeActionLinkName))})})]})]})}function Vs({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 Be({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 as(t,s,n){return t===s?"positive":t===0?n:"caution"}function fo(t){switch(t){case"positive":return"text-positive";case"caution":return"text-caution";case"negative":return"text-negative";case"neutral":return"text-neutral"}}function bo(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function At(t){return typeof t=="string"&&t.trim().length>0}function Ta(t){return t?zs(t):"Not returned"}function zs(t){return t?t.toLowerCase().split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"Unknown"}function jo(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function Kn(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function yo(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&vo(n)).map(([s])=>zs(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function vo(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function No({performance:t,freshness:s,timeseries:n}){const a=t.totals,i=Gi.filter(A=>(a[A]??0)>0),l=_i.filter(A=>(a[A]??0)>0),o=Object.keys(a).filter(A=>(a[A]??0)>0&&Ui(A)==="other").sort((A,v)=>(a[v]??0)-(a[A]??0)),p=Object.keys(a).filter(A=>(a[A]??0)===0).sort(),g=n.map(A=>{const v={date:A.date};for(const[C,z]of Object.entries(A.metrics))v[C]=z;return v}),u=n.find(A=>A.pending)?.date,m=n.length>0?n[n.length-1].date:void 0,d=g.length>0,P=s.dataThroughDate?`Data through ${jt(s.dataThroughDate)}${s.pendingDays>0?` · ${s.pendingDays}d pending`:""}`:null,b=[...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"}),P&&e.jsx("span",{className:"text-[11px] text-muted",children:P})]}),!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(Hn,{data:g,metrics:i,kind:"line",firstPending:u,lastDate:m}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-x-5 gap-y-1",children:b.map(A=>e.jsxs("span",{className:"text-sm text-secondary",children:[Ps(A)," ",e.jsx("span",{className:"font-mono text-heading",children:(a[A]??0).toLocaleString()})]},A))})]})]}),d&&l.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(Hn,{data:g,metrics:l,kind:"area",firstPending:u,lastDate:m})]}),p.length>0&&e.jsxs("p",{className:"text-xs text-faint",children:["Not active: ",p.map(A=>Ps(A)).join(", ")]})]})}function Hn({data:t,metrics:s,kind:n,firstPending:a,lastDate:i}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(Lt,{width:"100%",height:"100%",children:e.jsxs(zt,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Ms,{stroke:Es,vertical:!1}),e.jsx(Dt,{dataKey:"date",tick:_e,tickLine:!1,axisLine:{stroke:et},tickFormatter:Pt,minTickGap:24}),e.jsx(Tt,{tick:_e,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(It,{...ct,labelFormatter:jt,formatter:(l,o)=>[typeof l=="number"?l.toLocaleString():String(l??0),Ps(String(o??""))]}),e.jsx(ja,{wrapperStyle:{fontSize:11,color:qe.text},formatter:l=>Ps(l)}),a&&i&&e.jsx(pl,{x1:a,x2:i,fill:qe.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:qe.textDim,fontSize:10}}),s.map((l,o)=>n==="line"?e.jsx(Os,{type:"monotone",dataKey:l,stroke:Qe[o%Qe.length],strokeWidth:2,dot:!1,isAnimationActive:!1},l):e.jsx(qt,{type:"monotone",dataKey:l,stackId:"reach",stroke:Qe[o%Qe.length],fill:Qe[o%Qe.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},l))]})})})}function Ys({children:t,label:s="More info",placement:n="top",className:a}){const i=r.useId(),[l,o]=r.useState(!1);return e.jsxs("span",{className:`relative inline-flex ${a??""}`,children:[e.jsx("button",{type:"button","aria-label":s,"aria-describedby":l?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(gl,{className:"h-3.5 w-3.5","aria-hidden":!0})}),l&&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 kt=50,Wn={commoncrawl:"Common Crawl","bing-webmaster":"Bing Webmaster"},wo={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 Ct(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function is(t){return t.toLocaleString()}function So(t){const s=Number(t);return Number.isFinite(s)?`${(s*100).toFixed(1)}%`:"—"}function ko(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 Co(t){const s=t.filter(n=>n.kind===cs["backlink-extract"]&&!da(n.status));return s.length===0?null:s.reduce((n,a)=>n.createdAt>a.createdAt?n:a)}function Ao(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),l=a%60;return l===0?`${i}m`:`${i}m ${l}s`}function $o({projectName:t}){const[s,n]=r.useState(null),[a,i]=r.useState("commoncrawl"),[l,o]=r.useState(null),[p,g]=r.useState(null),[u,m]=r.useState([]),[d,P]=r.useState(null),[b,A]=r.useState(null),[v,C]=r.useState("commoncrawl"),[z,R]=r.useState(null),[I,N]=r.useState(Date.now()),[j,x]=r.useState(0),[E,_]=r.useState(!0),[H,T]=r.useState(!1),[S,M]=r.useState(!1),[U,G]=r.useState(null),ne=r.useRef(null),fe=r.useRef(!1),ue=r.useCallback(async()=>{_(!0),G(null);try{const[O,q,ie,oe,y,D]=await Promise.all([Qi(t,{excludeCrawlers:!0}).catch(()=>null),Ki().catch(()=>null),Hi(t,{excludeCrawlers:!0,source:a}).catch(()=>null),Wi(t,{limit:kt,offset:j,excludeCrawlers:!0,source:a}).catch(Oe=>{if(Oe instanceof ln&&Oe.code==="NOT_FOUND")return null;throw Oe}),Vi(t,{source:a}).catch(()=>[]),Yi(t).catch(()=>[])]);n(O),P(q),o(ie),g(oe),m(y);const Ae=Co(D);A(Ae),ne.current=Ae?.id??null}catch(O){G(O instanceof Error?O.message:"Failed to load backlinks")}finally{_(!1)}},[t,j,a]);r.useEffect(()=>{ue()},[ue]),r.useEffect(()=>{if(!s||fe.current)return;const O=s.sources.find(oe=>oe.hasData),q=s.sources.find(oe=>oe.connected),ie=O?.source??q?.source;ie&&ie!==a&&i(ie)},[s,a]);function pe(O){fe.current=!0,x(0),i(O)}r.useEffect(()=>{if(!b)return;const O=b.id;let q=!1;const ie=async()=>{try{const y=await ua(O);if(q)return;da(y.status)?(A(null),R(y),await ue()):A(D=>D?.id===y.id?{...D,...y}:D)}catch{}},oe=window.setInterval(()=>{ie()},3e3);return()=>{q=!0,window.clearInterval(oe)}},[b,ue]),r.useEffect(()=>{if(!b)return;const O=window.setInterval(()=>N(Date.now()),1e3);return()=>window.clearInterval(O)},[b]),r.useEffect(()=>{if(!z||z.status==="failed")return;const O=window.setTimeout(()=>R(null),1e4);return()=>window.clearTimeout(O)},[z]);async function me(){T(!0),G(null);try{const O=await er(t);C("commoncrawl"),A(O),ne.current=O.id}catch(O){O instanceof ln&&O.code==="MISSING_DEPENDENCY"?G("DuckDB is not installed. Visit the Backlinks admin page to install it."):G(O instanceof Error?O.message:"Failed to trigger extract")}finally{T(!1)}}async function he(){M(!0),G(null);try{const O=await Zi(t);C("bing-webmaster"),A(O),ne.current=O.id}catch(O){G(O instanceof Error?O.message:"Failed to trigger Bing sync")}finally{M(!1)}}const je=r.useMemo(()=>u.slice().sort((O,q)=>O.queriedAt.localeCompare(q.queriedAt)).map(O=>({date:O.queriedAt,linkingDomains:O.totalLinkingDomains})),[u]),f=p?.rows??[],B=p?.total??0,te=l?.excludedLinkingDomains??0,le=B>kt,de=Math.floor(j/kt)+1,Ce=Math.max(1,Math.ceil(B/kt));return r.useEffect(()=>{j>0&&j>=B&&x(0)},[j,B]),e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Backlinks"}),e.jsx("h2",{children:"Referring domains"}),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)."]})]})}),U&&e.jsx(W,{className:"surface-card p-4 mb-4 border-negative-800/60",children:e.jsx("p",{className:"text-sm text-negative",children:U})}),b&&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(Xi,{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:v==="bing-webmaster"?"Bing sync running":"Extract running"}),e.jsx(ae,{tone:"neutral",children:b.status}),e.jsxs("span",{className:"text-xs text-muted tabular-nums",children:[Ao(b.startedAt??null,b.createdAt)," elapsed · refreshing every 3s"]}),e.jsxs("span",{className:"sr-only",children:["now=",I]})]}),v==="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."]})]})]})}),z&&!b&&e.jsx(W,{className:`surface-card p-4 mb-4 ${z.status==="failed"?"border-negative-800/60":"border-positive-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[z.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(ya,{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 ${z.status==="failed"?"text-negative":"text-positive"}`,children:v==="bing-webmaster"?z.status==="failed"?"Bing sync failed":"Bing sync complete":z.status==="failed"?"Extract failed":"Extract complete"}),z.error?e.jsx("p",{className:"text-xs text-muted mt-1",children:Ji(z.error)}):z.status!=="failed"?e.jsx("p",{className:"text-xs text-muted mt-1",children:v==="bing-webmaster"?"Inbound links refreshed live from Bing Webmaster.":"Backlinks refreshed from the cached release."}):null]})]})}),$()]});function $(){return E||!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:[V(s),a==="bing-webmaster"?be():ye()]})}function V(O){return e.jsx("div",{className:"flex items-center gap-2 mb-4 flex-wrap",role:"tablist","aria-label":"Backlink source",children:O.sources.map(q=>{const ie=q.source===a,oe=q.hasData?"bg-positive-500":q.connected?"bg-caution-500":"bg-mono-600";return e.jsxs("button",{type:"button",role:"tab","aria-selected":ie,onClick:()=>pe(q.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 ${ie?"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 ${oe}`,"aria-hidden":!0}),Wn[q.source],q.hasData&&e.jsx("span",{className:"text-muted tabular-nums",children:is(q.totalLinkingDomains)})]},q.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(Us,{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."]})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(L,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Ct("/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 be(){const O=s?.sources.find(y=>y.source==="bing-webmaster"),q=O?.connected??!1,ie=O?.hasData??!1;return l!==null&&l.totalLinkingDomains>0?X(e.jsxs(L,{type:"button",variant:"outline",size:"sm",disabled:S||b!==null,onClick:ee(he),children:[e.jsx(rs,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),b?"Sync running…":S?"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(Us,{className:"h-5 w-5","aria-hidden":!0})}),e.jsx("div",{className:"flex-1",children:q&&ie?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 every inbound link in the latest window is a crawler/proxy host (hidden by default). Re-sync to check for new links."]}),e.jsx("div",{className:"mt-4",children:e.jsxs(L,{type:"button",variant:"outline",size:"sm",disabled:S||b!==null,onClick:ee(he),children:[e.jsx(rs,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),b?"Sync running…":S?"Queuing…":"Re-sync Bing inbound links"]})})]}):q?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."]}),e.jsx("div",{className:"mt-4",children:e.jsxs(L,{type:"button",size:"sm",disabled:S||b!==null,onClick:ee(he),children:[e.jsx(Ut,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),b?"Sync running…":S?"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 ye(){const O=l!==null&&l.totalLinkingDomains>0,q=z?.status==="failed",ie=l!==null&&l.totalLinkingDomains===0&&!q,oe=d?.status==="ready",y=d?.status==="failed",D=d&&(d.status==="downloading"||d.status==="querying"||d.status==="queued");return O?X(e.jsxs(e.Fragment,{children:[e.jsxs(L,{type:"button",variant:"outline",size:"sm",disabled:H||b!==null,onClick:ee(me),children:[e.jsx(rs,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),b?"Extract running…":H?"Queuing…":"Re-run extract"]}),e.jsxs(Ys,{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"}),"."]})]}),e.jsx(L,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Ct("/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(Us,{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."}),e.jsx("div",{className:"mt-4",children:e.jsx(L,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Ct("/backlinks"),children:"Set up backlinks"})})})]}),D&&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."]}),e.jsx("div",{className:"mt-4",children:e.jsx(L,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Ct("/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."}),e.jsx("div",{className:"mt-4",children:e.jsx(L,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Ct("/backlinks"),children:"Go to Backlinks admin"})})})]}),oe&&!D&&!ie&&!q&&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."]}),e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(L,{type:"button",size:"sm",disabled:H||b!==null,onClick:ee(me),children:[e.jsx(Ut,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),b?"Extract running…":H?"Queuing…":"Run extract"]}),e.jsxs(Ys,{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"}),"."]})]})]})]}),q&&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."]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(L,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Ct("/backlinks"),children:"Go to Backlinks admin"})})})]}),ie&&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:l.release})," found"," ",e.jsx("span",{className:"text-neutral",children:"0 referring domains"})," for"," ",e.jsx("code",{className:"text-neutral",children:l.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."}),e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(L,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Ct("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(L,{type:"button",variant:"outline",size:"sm",disabled:H||b!==null,onClick:ee(me),children:[e.jsx(Ut,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),b?"Extract running…":H?"Queuing…":"Re-run extract"]}),e.jsxs(Ys,{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:l.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 X(O){if(!l)return null;const q=a==="bing-webmaster",ie=q?"Inbound links":"Linking hosts",oe=q?"inbound links":"linking hosts",y=q?"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:is(l.totalLinkingDomains)})}),e.jsxs("p",{className:"metric-card-sub",children:["unique domains linking to ",l.targetDomain]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("p",{className:"metric-card-eyebrow",children:["Total ",oe]}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:is(l.totalHosts)})}),e.jsxs("p",{className:"metric-card-sub",children:["aggregate ",oe," 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:So(l.top10HostsShare)})}),e.jsxs("p",{className:"metric-card-sub",children:["share of ",oe," from the 10 largest linking domains"]})]})]}),e.jsxs("p",{className:"text-xs text-faint mt-2",children:[e.jsx("span",{className:"text-secondary",children:Wn[a]})," · ",y," ",e.jsx("code",{className:"text-secondary",children:l.release})," · queried ",ko(l.queriedAt),te>0&&e.jsxs(e.Fragment,{children:[" · ",e.jsxs("span",{className:"text-muted",children:[te," crawler/proxy domain",te===1?"":"s"," hidden"]})]})]}),e.jsx("p",{className:"text-[11px] text-faint mt-0.5",children:wo[a]}),je.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(Lt,{width:"100%",height:"100%",children:e.jsxs(zt,{data:je,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(Dt,{dataKey:"date",tick:_e,stroke:et,tickFormatter:Pt}),e.jsx(Tt,{tick:_e,stroke:et,allowDecimals:!1}),e.jsx(It,{contentStyle:ct.contentStyle,labelStyle:ct.labelStyle,itemStyle:ct.itemStyle,labelFormatter:jt}),e.jsx(qt,{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 ",de," of ",Ce," · ",is(B)," 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:ie})]})}),e.jsxs("tbody",{children:[f.map(D=>e.jsxs("tr",{className:"border-b border-mono-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-strong",children:D.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-secondary tabular-nums",children:is(D.numHosts)})]},D.linkingDomain)),f.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-muted",colSpan:2,children:te>0&&B===0?`Every referring domain in this ${y} was a crawler/proxy host (${te} hidden).`:`No referring domains in this ${y}.`})})]})]})}),le&&e.jsxs("div",{className:"flex items-center justify-end gap-2 mt-2",children:[e.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:j===0,onClick:()=>x(D=>Math.max(0,D-kt)),children:"Previous"}),e.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:j+kt>=B,onClick:()=>x(D=>D+kt),children:"Next"})]})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:O})]})}}function Po({projectName:t}){const s=Pe({...tr({client:K,path:{name:t}}),staleTime:hn}),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:l,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(ke,{text:"An engine is ‘citing’ when our domain appears in its grounding source list (the structured citation/search-result attribution it returns alongside the answer). Counts each configured engine that cites the project on at least one tracked query in the latest snapshot per (query × provider)."})]}),e.jsxs("p",{className:"text-base text-neutral flex items-center gap-2",children:["Mentioned in ",l," of ",o," engine answers",e.jsx(ke,{text:"An engine is ‘mentioning’ when our brand or domain appears inside the prose of the answer text — independent of whether it’s in the citation list. Models often name-drop from training without citing a fresh page."})]})]}),n.summary.latestRunAt&&e.jsxs("p",{className:"supporting-copy",children:["Latest run ",new Date(n.summary.latestRunAt).toLocaleString()]})]}),e.jsx(Lo,{data:n}),e.jsx(zo,{data:n}),n.competitorGaps.length>0&&e.jsx(Ro,{data:n})]})}function Lo({data:t}){const{totalQueries:s,queriesCitedAndMentioned:n,queriesCitedOnly:a,queriesMentionedOnly:i,queriesInvisible:l}=t.summary;return e.jsxs("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4 mb-4",children:[e.jsx(Ss,{label:"Cited + mentioned",value:`${n} / ${s}`,helper:"In sources AND named in answer",tone:n>0?"positive":"neutral"}),e.jsx(Ss,{label:"Cited only",value:`${a} / ${s}`,helper:"In sources, not named in answer",tone:a>0?"positive-dim":"neutral"}),e.jsx(Ss,{label:"Mentioned only",value:`${i} / ${s}`,helper:"Named in answer, no source link",tone:i>0?"caution":"neutral"}),e.jsx(Ss,{label:"Invisible",value:`${l} / ${s}`,helper:"No engine cites or mentions",tone:l>0?"negative":"neutral"})]})}function Ss({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 zo({data:t}){const s=r.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(Do,{}),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(Ht,{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(l=>l.provider===a);return e.jsx("td",{className:"text-center",children:i==null?e.jsx(jl,{className:"inline h-3.5 w-3.5 text-mono-700","aria-label":"no data"}):e.jsx(To,{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 Do(){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(Gt,{active:!0,tone:"cited"}),e.jsx("span",{children:"cited (in sources)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Gt,{active:!0,tone:"mentioned"}),e.jsx("span",{children:"mentioned (in answer)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Gt,{active:!1,tone:"cited"}),e.jsx(Gt,{active:!1,tone:"mentioned"}),e.jsx("span",{children:"neither"})]})]})}function To({provider:t}){const s=Io(t);return e.jsxs("span",{className:"inline-flex items-center justify-center gap-1",title:s,children:[e.jsx(Gt,{active:t.cited,tone:"cited"}),e.jsx(Gt,{active:t.mentioned,tone:"mentioned"})]})}function Io(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 Gt({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 Ro({data:t}){return e.jsxs("div",{className:"mt-4",children:[e.jsxs("h3",{className:"text-sm font-semibold text-strong mb-2 flex items-center gap-2",children:["Competitor gaps",e.jsx(ke,{text:"Queries where the project is not cited but a configured competitor is. Each row maps to one (query, engine) pair — the same query may surface for multiple engines."}),e.jsxs("span",{className:"text-[10px] font-normal uppercase tracking-wide text-muted",children:[t.competitorGaps.length," ",t.competitorGaps.length===1?"gap":"gaps"]})]}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Engine"}),e.jsx("th",{children:"Competitors cited"})]})}),e.jsx("tbody",{children:t.competitorGaps.map(s=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:s.query}),e.jsx("td",{children:e.jsx(Ht,{provider:s.provider})}),e.jsx("td",{className:"text-neutral",children:s.citingCompetitors.join(", ")})]},`${s.queryId}::${s.provider}`))})]})})]})}const Fs="__cited__",Bs="__mentioned__",gt="__mentionShare__";function un(t){return Math.round(t*1e3)/10}function Eo(t,s,n){const a=t.buckets.length>0,i=t.buckets.length===1;if(n==="overall"){const g=s==="cited"?Fs:Bs,u=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(d=>({date:d.startDate,[g]:un(d[u])})),series:[g],hasData:a,singleBucket:i}}const l=s==="mentioned"?"mentionRate":"citationRate",o=[...new Set(t.buckets.flatMap(g=>Object.keys(g.byProvider??{})))].sort();return{rows:t.buckets.map(g=>{const u={date:g.startDate};for(const m of o){const d=g.byProvider?.[m];u[m]=d?un(d[l]):null}return u}),series:o,hasData:a,singleBucket:i}}function Mo(t){const s=t.buckets.map(a=>{const i=a.mentionShare;return{date:a.startDate,[gt]:i?.rate==null?null:un(i.rate)}}),n=s.map(a=>a[gt]).filter(a=>typeof a=="number"&&Number.isFinite(a));return{rows:s,series:[gt],hasData:n.length>0,singleBucket:n.length===1}}function Ia(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 Vn(t){const[,s,n]=t.slice(0,10).split("-");return!s||!n?t:`${s}/${n}`}function Yn(t){return t>0?`+${t}`:`${t}`}function Ra(t){if(t.length===0)return null;if(t.length<=2)return`Query set changed: ${t.map(n=>`${Yn(n.delta)} on ${Vn(n.date)}`).join(", ")}`;const s=[...t].sort((n,a)=>a.date.localeCompare(n.date))[0];return`Query set changed ${t.length} times (latest ${Yn(s.delta)} on ${Vn(s.date)})`}const Ea=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],Oo=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],Fo=[{value:"mentioned",label:"Mentioned"},{value:"cited",label:"Cited"}],Ma="var(--chart-tooltip-bg)",Bo={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",local:"Local"};function qo(t){return Bo[t]??t.charAt(0).toUpperCase()+t.slice(1)}function As(t){return Math.round(t*10)/10}function Go(t){return t===Fs||t===Bs}function Xn(t){return t===Fs?"Cited":t===Bs?"Mentioned":qo(t)}function Xs(t,s){return t===Fs?bt.positive:t===Bs?Qe[1]:t===gt?bt.positive:ul(t,s)}function _o(t,s){for(const n of t){const a=n[s];if(typeof a=="number"&&Number.isFinite(a))return a}return null}function Oa(t){return t.map(s=>s.trim().toLowerCase()).filter(Boolean).sort().join(`
|