@canonry/canonry 4.141.0 → 4.142.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/agent-workspace/skills/canonry/references/canonry-cli.md +12 -5
- package/assets/assets/{AuditHistoryPanel-DlyLhzqq.js → AuditHistoryPanel-CfaF5B_e.js} +1 -1
- package/assets/assets/{BacklinksPage-DNxtwQBF.js → BacklinksPage-BIytWBpL.js} +1 -1
- package/assets/assets/{ChartPrimitives-BStLR_NC.js → ChartPrimitives-0tQT6GE7.js} +1 -1
- package/assets/assets/{HistoryPage-CIcCgoWK.js → HistoryPage-Bn6IH8WV.js} +1 -1
- package/assets/assets/{ProjectPage-BSI3Qum9.js → ProjectPage-DsQic9wX.js} +1 -1
- package/assets/assets/{RunRow-C0mFtLlc.js → RunRow-RHd8Bd52.js} +1 -1
- package/assets/assets/{RunsPage-C-yo0yoj.js → RunsPage-BsDqqQFX.js} +1 -1
- package/assets/assets/{SettingsPage-jg4MXOuo.js → SettingsPage-CX2LkFDB.js} +1 -1
- package/assets/assets/{TrafficPage-CnYHIg8t.js → TrafficPage-I19b7i9m.js} +1 -1
- package/assets/assets/{TrafficSourceDetailPage-CEdyQT2P.js → TrafficSourceDetailPage-DOLEAPsc.js} +1 -1
- package/assets/assets/{arrow-left-DUv0imIl.js → arrow-left-BG9o86__.js} +1 -1
- package/assets/assets/{extract-error-message-CCOGDwlm.js → extract-error-message-D0cgM2XG.js} +1 -1
- package/assets/assets/{index-D6EP4dQs.js → index-CYGBt2f0.js} +73 -73
- package/assets/assets/{trash-2-1Yg9W-vs.js → trash-2-C_THWxO_.js} +1 -1
- package/assets/index.html +1 -1
- package/dist/{chunk-ZCFQGF3V.js → chunk-D7NJUGNQ.js} +10 -7
- package/dist/{chunk-OJOA425V.js → chunk-LS6SEZVF.js} +78 -3
- package/dist/{chunk-2LUSZFB6.js → chunk-NR6OGEV3.js} +207 -49
- package/dist/{chunk-HXXO2AF5.js → chunk-UFPP5CSN.js} +4 -4
- package/dist/cli.js +62 -50
- package/dist/index.js +4 -4
- package/dist/{intelligence-service-4HQIUC7U.js → intelligence-service-EOUP37XN.js} +2 -2
- package/dist/mcp.js +2 -2
- package/package.json +7 -7
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{j as e,r as o,L as xt,n as kt,u as ve,o as fs,A as Zi,B as er,h as tr}from"./vendor-tanstack-Be8JdV5M.js";import{c as Ns,T as te,t as sr,a as nr,S as ar,X as ir,C as qn,u as Wa,b as rr,P as Kt,B as I,h as or,d as lr,e as cr,f as Y,i as Q,g as De,j as he,I as $e,k as cs,l as dr,m as V,n as ur,o as mr,p as xr,q as hr,r as Ya,s as pr,v as gr,w as Rt,x as fr,y as br,z as Pt,A as st,D as jr,E as pa,F as Ja,G as Te,H as Gn,J as yr,K as vr,L as Nr,M as wr,N as ga,O as se,Q as Xa,R as Sr,U as un,V as Cr,W as kr,Y as Ar,Z as $r,_ as Pr,$ as Lr,a0 as Rr,a1 as Dr,a2 as Ir,a3 as Tr,a4 as Mr,a5 as Er,a6 as Or,a7 as Fr,a8 as _r,a9 as qr,aa as Mt,ab as Gr,ac as Za,ad as Ks,ae as Br,af as Ur,ag as Qr,ah as zr,ai as Vs,aj as Hr,ak as Kr,al as Vr,am as Ln,an as Wr,ao as Yr,ap as Rn,aq as Jr,ar as Xr,as as Vt,at as ei,au as ti,av as Zr,aw as si,ax as eo,ay as to,az as so,aA as no,aB as ni,aC as ao,aD as io,aE as ro,aF as hs,aG as Dt,aH as oo,aI as lo,aJ as co,aK as uo,aL as ai,aM as mo,aN as xo,aO as ho,aP as po,aQ as go,aR as ii,aS as fo,aT as Bn,aU as bo,aV as jo,aW as yo,aX as vo,aY as No,aZ as wo,a_ as So,a$ as Co,b0 as ko,b1 as Ao,b2 as $o,b3 as Po,b4 as Lo,b5 as Ro,b6 as Do,b7 as Io,b8 as To,b9 as Mo,ba as Eo,bb as mn,bc as Oo,bd as Fo,be as fa,bf as _o,bg as qo,bh as Go,bi as Bo,bj as Uo,bk as Qo,bl as zo,bm as Ho,bn as Ko,bo as Vo,bp as Wo,bq as Yo,br as ba,bs as Jo,bt as xn,bu as Xo,bv as Zo,bw as el,bx as tl,by as sl,bz as nl,bA as al,bB as il,bC as rl,bD as ri,bE as oi,bF as ol,bG as li,bH as ll,bI as ci,bJ as cl,bK as dl,bL as Fs,bM as ul,bN as ml,bO as xl,bP as ja}from"./index-D6EP4dQs.js";import{R as hl}from"./RunRow-C0mFtLlc.js";import{C as pl,R as bs,f as Dn,a as pt,b as Ve,c as Ws,d as It,e as _e,g as Fe,h as ht,i as Un,j as Qn,k as Ct,o as nt,p as gl}from"./ChartPrimitives-BStLR_NC.js";import{u as fl,t as bl,e as jl}from"./extract-error-message-CCOGDwlm.js";import{R as Wt,C as Yt,X as Jt,Y as Xt,T as Zt,L as di,A as Bt,a as zn,b as yl,d as Hn,e as vl}from"./vendor-recharts-DSxTZhaH.js";import{D as ui,C as Nl,E as wl,T as Sl}from"./trash-2-1Yg9W-vs.js";import{A as Cl}from"./AuditHistoryPanel-DlyLhzqq.js";import"./vendor-radix-CQ77EO2y.js";import"./vendor-markdown-6dwjPOKK.js";const kl=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],mi=Ns("circle-check",kl);const Al=[["path",{d:"M5 12h14",key:"1ays0h"}]],$l=Ns("minus",Al);const Pl=[["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"}]],Ll=Ns("scan-search",Pl);const Rl=[["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"}]],Dl=Ns("unplug",Rl);const Il=[["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"}]],Tl=Ns("upload",Il);function zs(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 Ml(t,s){return s<=0?null:Math.round((t-s)/s*100)}function hn(t,s,n="vs prior 7 days"){return t.deltaPct===null?t.prior===0?"First baseline week":"":t.deltaPct>0?`Up ${t.deltaPct}% ${n} (${zs(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${zs(t.prior)} ${s})`:`Flat ${n} (${zs(t.prior)} ${s})`}const xi=30;function ya(t){return Math.round(t*10)/10}function El(t){return t.prior>=xi&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% vs prior`:`${t.deltaAbs>0?"+":""}${ya(t.deltaAbs)} vs ${ya(t.prior)}`}function Ol(t,s,n){return t.prior>=xi&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% ${n}`:`${t.deltaAbs>0?"+":""}${zs(Math.round(t.deltaAbs))} ${s} ${n}`}const Fl=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function hi(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function pi(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 gi(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(hi).map(pi).filter(Boolean)):new Set}function fi(t,s){const n=hi(t).map(pi).filter(Boolean).filter(a=>!Fl.has(a)).filter(a=>!s.has(a));return[...new Set(n)].sort().join(" ")}function _l(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function ql(t,s){const n=gi(t);if(s.length<=1||n.size===0)return[...s];const a=new Set,i=[];for(const r of s){if(r.category!=="content"){i.push(r);continue}const l=fi(_l(r),n);!l||a.has(l)||(a.add(l),i.push(r))}return i}function Gl(t){const s=gi(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const a=new Set;return n.filter(i=>{const r=fi(i.query,s);return!r||a.has(r)?!1:(a.add(r),!0)})}function In({state:t,label:s}){return e.jsx(te,{tone:nr(t),children:s??sr(t)})}const et=25;function Bl(t){return t.trim().toLocaleLowerCase().split(/\s+/).filter(Boolean)}function bi(t){let s=t;try{s=decodeURIComponent(t.replace(/\+/g," "))}catch{}let n="";const a=t.indexOf("?");return a>=0&&new URLSearchParams(t.slice(a+1)).forEach((r,l)=>{n+=` ${l} ${r}`}),`${t} ${s}${n}`}function Ul(t,s=36,n=18){const a=[...t];return a.length<=s+n+1?t:`${a.slice(0,s).join("")}…${a.slice(-n).join("")}`}function ps({value:t,headLength:s,tailLength:n,className:a,title:i}){const r=Ul(t,s,n);return e.jsx("span",{className:a,title:i??t,children:r===t?t:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"sr-only",children:t}),e.jsx("span",{"aria-hidden":"true",children:r})]})})}function js({rows:t,getSearchText:s,pageSize:n=et}){const[a,i]=o.useState(""),[r,l]=o.useState(1),u=o.useMemo(()=>Bl(a),[a]),x=o.useMemo(()=>u.length===0||!s?t:t.filter(w=>{const g=s(w).toLocaleLowerCase();return u.every(D=>g.includes(D))}),[s,t,u]),m=Math.max(1,Math.ceil(x.length/n)),f=Math.min(Math.max(1,r),m),d=(f-1)*n,b=o.useMemo(()=>x.slice(d,d+n),[x,n,d]),A=o.useCallback(w=>{i(w),l(1)},[]),$=o.useCallback(w=>{l(Math.max(1,w))},[]);return{query:a,setQuery:A,page:f,setPage:$,rows:b,filteredRows:x,totalRows:x.length,totalPages:m,pageSize:n,rangeStart:x.length===0?0:d+1,rangeEnd:d+b.length,hasQuery:a.trim().length>0}}function Qt({value:t,onChange:s,label:n,placeholder:a="Filter rows",className:i}){return e.jsxs("div",{className:`relative ${i??""}`,children:[e.jsx(ar,{"aria-hidden":"true",className:"pointer-events-none absolute left-3 top-1/2 size-3.5 -translate-y-1/2 text-muted"}),e.jsx("input",{type:"search",value:t,onChange:r=>s(r.target.value),"aria-label":n,placeholder:a,autoComplete:"off",spellCheck:!1,className:"h-9 w-full rounded-md border border-default bg-surface/50 pl-9 pr-9 text-sm text-strong placeholder:text-muted outline-none transition focus:border-mono-500 focus:ring-1 focus:ring-mono-500 [&::-webkit-search-cancel-button]:appearance-none"}),t.trim().length>0?e.jsx("button",{type:"button",onClick:()=>s(""),"aria-label":`Clear ${n.toLocaleLowerCase()}`,className:"absolute right-2 top-1/2 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded text-muted transition-colors hover:bg-surface-hover hover:text-strong focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",children:e.jsx(ir,{"aria-hidden":"true",className:"size-3.5"})}):null]})}function Tt({page:t,pageSize:s=et,visibleRows:n,totalRows:a,hasNextPage:i,onPageChange:r,itemLabel:l="rows",className:u,disabled:x=!1}){if(n===0)return null;const m=(t-1)*s+1,f=m+n-1,d=a===void 0?void 0:Math.max(1,Math.ceil(a/s)),b=i??(d!==void 0&&t<d),A=t>1||b;return e.jsxs("div",{className:`mt-3 flex flex-wrap items-center justify-between gap-x-4 gap-y-2 text-xs text-secondary ${u??""}`,children:[e.jsxs("p",{className:"tabular-nums",children:[m.toLocaleString("en-US"),"–",f.toLocaleString("en-US"),a===void 0?`${b?"+":""} ${l}`:` of ${a.toLocaleString("en-US")} ${l}`]}),A?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>r(t-1),disabled:x||t<=1,className:"inline-flex items-center gap-1 rounded-md border border-base bg-bg px-2.5 py-1.5 text-strong transition hover:border-strong hover:text-primary disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-base disabled:hover:text-strong",children:[e.jsx(pl,{"aria-hidden":"true",className:"size-3.5"}),"Previous"]}),e.jsx("span",{className:"tabular-nums",children:d===void 0?`Page ${t}`:`Page ${t} of ${d}`}),e.jsxs("button",{type:"button",onClick:()=>r(t+1),disabled:x||!b,className:"inline-flex items-center gap-1 rounded-md border border-base bg-bg px-2.5 py-1.5 text-strong transition hover:border-strong hover:text-primary disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-base disabled:hover:text-strong",children:["Next",e.jsx(qn,{"aria-hidden":"true",className:"size-3.5"})]})]}):null]})}function va({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={cited:"rounded-full","not-cited":"rounded-sm",lost:"rotate-45 rounded-[1px]",emerging:"rounded-full"},r=n.length-1,l=new Date(n[0].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),u=new Date(n[r].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),x=n.map((m,f)=>{const d=new Date(m.createdAt).toLocaleDateString();return`${f===r?"Latest run, ":""}${d}: ${m.citationState}${m.model?`, model ${m.model}`:""}`}).join("; ");return e.jsxs("div",{className:"flex items-center gap-1",role:"img","aria-label":`Citation history across ${n.length} runs. ${x}`,children:[e.jsx("span",{className:"text-[9px] text-faint shrink-0","aria-hidden":"true",children:l}),e.jsx("div",{className:"flex items-center gap-[3px]",title:`${n.length} runs`,"aria-hidden":"true",children:n.map((m,f)=>{const d=!!(m.model&&f>0&&n[f-1]?.model&&n[f-1].model!==m.model),b=f===r;return e.jsx("span",{className:`h-2.5 w-2.5 ${i[m.citationState]??"rounded-sm"} ${a[m.citationState]??"bg-mono-700"} ${d?"ring-1 ring-caution-300/80 ring-offset-1 ring-offset-bg":""} ${b?"outline outline-1 outline-offset-2 outline-mono-400":""}`,title:[m.citationState,new Date(m.createdAt).toLocaleDateString(),m.model?`model ${m.model}`:null,d?"model changed":null,b?"latest run":null].filter(Boolean).join(" · ")},`${m.runId}:${m.createdAt}`)})}),e.jsxs("span",{className:"text-[9px] shrink-0 text-secondary","aria-hidden":"true",children:[u," ",e.jsx("span",{className:"text-faint",children:"latest"})]})]})}function Tn(t){const s=new Map;for(const a of t)for(const i of a.runHistory){const r=s.get(i.createdAt);r?r.states.push(i.citationState):s.set(i.createdAt,{states:[i.citationState],runId:i.runId})}return[...s.entries()].sort(([a],[i])=>a.localeCompare(i)).map(([a,{states:i,runId:r}])=>({runId:r,createdAt:a,citationState:i.includes("cited")?"cited":i.includes("emerging")?"emerging":"not-cited"}))}const Ql=320;function zl(t){return[t.phrase,t.location??"",...t.rawItems.map(s=>s.provider)].join(" ")}function Na(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 wa(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 Sa(t,s){const n=s==="mentions"?"mentioned":"cited",a=s==="mentions"?"Mentioned":"Cited";if(t.length===0)return"Awaiting first run";if(t.length===1)return"First observation";const i=t[t.length-1].citationState,r=t[t.length-2].citationState;if(r!=="cited"&&i==="cited")return`Newly ${n}`;if(r==="cited"&&i!=="cited")return"Lost since last run";let l=0;for(let u=t.length-1;u>=0&&t[u].citationState===i;u--)l++;return i==="cited"?l<=1?`${a} in latest run`:`${a} for ${l} runs`:l<=1?`Not ${n} in latest run`:`Not ${n} across ${l} runs`}function Hl(t,s){return t.map(n=>ji(n,s))}function ji(t,s){return s==="citations"?t:{...t,citationState:Na(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:Na(n,s)}))}}function Ca(t,s){const n=s==="mentions"?"mention":"citation",a=s==="mentions"?"Mention":"Citation";if(t.length===0)return{key:s,label:`${a} pending`,tone:"pending"};const i=t[t.length-1].citationState,r=t.length>=2?t[t.length-2].citationState:null,l=i==="cited"||i==="emerging",u=r==="cited"||r==="emerging";return i==="lost"||r!==null&&u&&!l?{key:s,label:`Lost ${n}`,tone:"negative"}:i==="emerging"||r!==null&&!u&&l?{key:s,label:`New ${n}`,tone:"positive"}:r===null&&l?{key:s,label:`First ${n}`,tone:"positive"}:l?{key:s,label:s==="mentions"?"Still mentioned":"Still cited",tone:"neutral"}:{key:s,label:`No ${n}`,tone:"neutral"}}function Kl(t){const s=Tn(Hl(t,"mentions")),n=Tn(t);return[Ca(s,"mentions"),Ca(n,"citations")]}function Vl({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 ka({items:t}){return e.jsx("div",{className:"mt-1 flex flex-wrap gap-1","aria-label":"Latest run mention and citation signals",children:Kl(t).map(s=>e.jsx(Vl,{signal:s},s.key))})}function Wl({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:a}=Wa(),[i,r]=o.useState(new Set),[l,u]=o.useState("mentions"),[x,m]=o.useState(n),f=o.useMemo(()=>{const F=new Map;for(const T of t){const q=T.query,h=s?T.location??null:null,k=s?JSON.stringify([q,h]):q,E=F.get(k)??{key:k,phrase:q,location:h,items:[],rawItems:[]};E.items.push(ji(T,l)),E.rawItems.push(T),F.set(k,E)}return[...F.values()]},[t,l,s]),d=js({rows:f,getSearchText:zl}),b=d.rows.map(F=>F.key),A=b.length>0&&b.every(F=>i.has(F)),$=F=>{r(T=>{const q=new Set(T);return q.has(F)?q.delete(F):q.add(F),q})},w=l==="mentions"?"mentioned":"cited",g=l==="mentions"?"Mention History":"Citation History",D=l==="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":l==="mentions",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${l==="mentions"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>u("mentions"),children:"Mentions"}),e.jsx("button",{type:"button",role:"tab","aria-selected":l==="citations",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${l==="citations"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>u("citations"),children:"Citations"})]}),e.jsx("span",{className:"text-[11px] text-muted",children:l==="mentions"?"Brand or domain in answer text":"Brand or domain in source links"}),e.jsxs("div",{className:"ml-auto flex items-center gap-3",children:[e.jsx("button",{type:"button",className:"text-[11px] text-secondary hover:text-strong",onClick:()=>{r(F=>{const T=new Set(F);for(const q of b)A?T.delete(q):T.add(q);return T})},children:A?"Collapse page":"Expand page"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Density"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-bg-elevated/60 border border-subtle",role:"tablist","aria-label":"Evidence row density",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":x==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${x==="compact"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>m("compact"),children:"Compact"}),e.jsx("button",{type:"button",role:"tab","aria-selected":x==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${x==="detailed"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>m("detailed"),children:"Detailed"})]})]})]})]}),f.length>0?e.jsx(Qt,{value:d.query,onChange:d.setQuery,label:"Filter tracked queries",placeholder:"Filter query, location, or provider",className:"mb-3 max-w-md"}):null,e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{style:{width:"2rem"}}),e.jsx("th",{scope:"col",children:"Query"}),e.jsx("th",{scope:"col",children:"Status"}),e.jsx("th",{scope:"col",children:g}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:d.rows.map(({key:F,phrase:T,location:q,items:h,rawItems:k})=>{const E=i.has(F),X=h.map(y=>y.citationState),le=X.includes("cited")?"cited":X.includes("emerging")?"emerging":X.includes("lost")?"lost":X.every(y=>y==="pending")?"pending":"not-cited",S=Tn(h),p=h.filter(y=>y.citationState===rr.cited||y.citationState==="emerging").length,_=Sa(S,l);return e.jsxs(o.Fragment,{children:[e.jsxs("tr",{className:"cursor-pointer hover:bg-mono-800/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>$(F),onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),$(F))},tabIndex:0,role:"button","aria-expanded":E,children:[e.jsx("td",{children:e.jsx(qn,{size:14,className:`transition-transform duration-150 text-muted ${E?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-heading",children:T}),s&&e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-muted",children:q??"No location"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:h.map(y=>e.jsx(Kt,{provider:y.provider},y.id))})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(In,{state:le,label:wa(le,l)}),e.jsxs("span",{className:"text-[11px] text-muted",title:`${p} of ${h.length} engines ${D}`,children:[p,"/",h.length]})]})}),e.jsx("td",{children:e.jsx(va,{history:S})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:_}),e.jsx(ka,{items:k})]}),e.jsx("td",{})]}),E&&h.map((y,G)=>e.jsxs(o.Fragment,{children:[e.jsxs("tr",{className:"bg-surface",children:[e.jsx("td",{}),e.jsx("td",{className:"evidence-query-cell pl-5",children:e.jsx(Kt,{provider:y.provider})}),e.jsx("td",{children:e.jsx(In,{state:y.citationState,label:wa(y.citationState,l)})}),e.jsx("td",{children:e.jsx(va,{history:y.runHistory})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:Sa(y.runHistory,l)}),e.jsx(ka,{items:[k[G]??y]})]}),e.jsx("td",{children:e.jsx(I,{variant:"ghost",size:"sm",type:"button",onClick:re=>{re.stopPropagation(),a(y.id)},children:"View"})})]}),x==="detailed"&&e.jsxs("tr",{className:"bg-surface-subtle",children:[e.jsx("td",{}),e.jsx("td",{colSpan:5,className:"px-5 pb-4",children:e.jsx(Xl,{item:y,onViewFull:()=>a(y.id)})})]})]},y.id))]},F)})})]})}),d.totalRows===0&&d.hasQuery?e.jsx("p",{className:"supporting-copy mt-3",children:"No tracked queries match this filter."}):null,e.jsx(Tt,{page:d.page,pageSize:d.pageSize,visibleRows:d.rows.length,totalRows:d.totalRows,onPageChange:d.setPage,itemLabel:d.hasQuery?"matches":"queries"}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",w==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function Yl(t){const s=(t.matchedTerms??[]).filter(i=>i.trim().length>2),n=[...t.competitorDomains.flatMap(i=>{const r=lr(i);return r.length>=4?[r]:[]}),...t.recommendedCompetitors??[]].filter(i=>i.trim().length>2),a=[];return s.length>0&&a.push({terms:s,className:"answer-highlight-brand"}),n.length>0&&a.push({terms:n,className:"answer-highlight-competitor"}),a}function Jl(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 Xl({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}=Jl(t.answerSnippet,Ql),r=Yl(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:or(a,r)}),(t.citedDomains.length>0||t.competitorDomains.length>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[t.citedDomains.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Cited:"}),t.citedDomains.slice(0,6).map(l=>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:l},`c-${l}`)),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(l=>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:l},`co-${l}`)),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:l=>{l.stopPropagation(),s()},children:"View full answer →"})]})}function Zl({competitors:t,onSelectCompetitor:s,onRemoveCompetitor:n,activeFilter:a}){if(t.length===0)return e.jsx("p",{className:"text-sm text-muted",children:"No competitors configured. Add competitors to track overlap."});const i=s!=null,r=n!=null;return e.jsx("div",{className:"competitor-table-wrap",children:e.jsxs("table",{className:"competitor-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Domain"}),e.jsx("th",{children:"Pressure"}),e.jsx("th",{children:"Citations"}),e.jsx("th",{children:"Queries"}),r&&e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{children:t.map(l=>{const u=a!=null&&a.toLowerCase()===l.domain.toLowerCase(),x=[i?"cursor-pointer hover:bg-mono-800/30 transition-colors":"",u?"bg-negative-950/20":""].filter(Boolean).join(" ");return e.jsxs("tr",{className:x,onClick:i?()=>s(l.domain):void 0,title:i?`Filter answers to queries where ${l.domain} surfaced`:void 0,children:[e.jsx("td",{className:"font-medium text-heading",children:l.domain}),e.jsx("td",{children:e.jsx(te,{tone:cr(l.pressureLabel),children:l.pressureLabel})}),e.jsx("td",{className:"text-neutral tabular-nums",children:l.totalQueries>0?`${l.citationCount} / ${l.totalQueries}`:"—"}),e.jsx("td",{className:"text-muted text-xs",children:l.citedQueries.length>0?l.citedQueries.join(", "):"Not cited"}),r&&e.jsx("td",{className:"text-right",children:e.jsx("button",{type:"button",className:"rounded px-1.5 py-0.5 text-xs text-muted transition-colors hover:text-negative-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-negative-500","aria-label":`Remove competitor ${l.domain}`,title:`Remove ${l.domain}`,onClick:m=>{m.stopPropagation(),n(l.domain)},children:"Remove"})})]},l.id)})})]})})}function _s({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 ec=6,es="__other__",zt="_socialTotal";function tc(t,s=ec){const n=new Map;for(const f of t)n.set(f.source,(n.get(f.source)??0)+f.sessions);const a=[...n.entries()].sort((f,d)=>d[1]!==f[1]?d[1]-f[1]:f[0].localeCompare(d[0])),i=a.slice(0,s),r=new Set(i.map(([f])=>f)),l=Math.max(0,a.length-s),u=new Map;for(const f of t){let d=u.get(f.date);d||(d={date:f.date,[zt]:0},u.set(f.date,d));const b=r.has(f.source)?f.source:es;d[b]=(d[b]??0)+f.sessions,d[zt]=(d[zt]??0)+f.sessions}const x=[...u.values()].sort((f,d)=>String(f.date).localeCompare(String(d.date))),m=i.map(([f])=>f);return l>0&&m.push(es),{data:x,sources:m,otherCount:l}}function Ht(t){return t.replace(/\+/g," ")}function yi(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const Aa="_totalSessions",$a="_organicSessions";function sc(t,s){const n=new Map;for(const l of s)n.set(l.date,{[Aa]:l.sessions,[$a]:l.organicSessions});for(const l of t.days){let u=n.get(l.date);u||(u={[Aa]:0,[$a]:0},n.set(l.date,u));for(const x of l.bySource)u[x.source]=(u[x.source]??0)+x.sessions}const a=[...n.entries()].sort(([l],[u])=>l.localeCompare(u)).map(([l,u])=>({date:l,...u})),i=a.map(l=>l.date),r=i.length>0?{start:i[0],end:i[i.length-1]}:null;return{data:a,sources:t.sources,dateRange:r}}const nc=["7d","30d","90d","all"],wt=Fe,Mn=_e.textDim,vi=_e.textFaint,ds=25;function ac(t){return bi(t.landingPage)}const ic=25,pn={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0};function qs(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function Ni(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 rc({projectName:t}){const{data:s,isLoading:n,isError:a}=fl(t);if(n)return e.jsx(Y,{className:"p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading server activity…"})});if(a)return e.jsx(Y,{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:"Server activity"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["Crawler, AI fetch, and referral activity from connected sources."," ",!Q()&&e.jsx(xt,{to:"/traffic",className:"text-link hover:underline",children:"Manage sources →"})]})]})}),i.length===0?e.jsx(Y,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-secondary",children:["No server traffic source connected yet."," ",!Q()&&e.jsxs(e.Fragment,{children:[e.jsx(xt,{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(Y,{className:"overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-bg-elevated/50 text-[10px] uppercase tracking-wide text-muted",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Source"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Status"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Crawler hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI sessions 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Last sync"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium","aria-label":"open"})]})}),e.jsx("tbody",{children:i.map(r=>e.jsxs("tr",{className:"border-t border-default",children:[e.jsx("td",{className:"px-4 py-3 text-heading",children:r.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(te,{tone:bl(r.status),children:r.status})}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:r.totals24h.crawlerHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:r.totals24h.aiUserFetchHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:r.totals24h.aiReferralHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right text-secondary text-xs",children:r.lastSyncedAt?Ni(r.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:Q()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(xt,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:r.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},r.id))})]})})]})}function oc({projectName:t}){return e.jsxs("div",{className:"space-y-10",children:[e.jsx(rc,{projectName:t}),e.jsx(lc,{projectName:t})]})}function lc({projectName:t}){const s=kt(),[n,a]=o.useState(null),[i,r]=o.useState(null),[l,u]=o.useState(!0),[x,m]=o.useState(!1),[f,d]=o.useState(!1),[b,A]=o.useState(null),[$,w]=o.useState(null),[g,D]=o.useState("sessions"),[F,T]=o.useState("desc"),[q,h]=o.useState("sessions"),[k,E]=o.useState("desc"),[X,le]=o.useState("sessions"),[S,p]=o.useState("desc"),[_,y]=o.useState("sessions"),[G,re]=o.useState("desc"),[J,U]=o.useState(pn),[oe,ae]=o.useState([]),[O,M]=o.useState([]),[j,Z]=o.useState(!1),[ie,v]=o.useState("30d");async function z(L){u(!0),A(null);try{const pe=await s.fetchQuery({...dr({client:V,path:{name:t}}),staleTime:cs});if(L.current)return;if(a(pe),!pe.connected){r(null),U(pn),ae([]),M([]),u(!1);return}const ne=ie==="all"?void 0:ie,[ue,Pe,tn,Ye]=await Promise.all([s.fetchQuery({...ur({client:V,path:{name:t},query:ne?{window:ne}:void 0}),staleTime:cs}).then(sn=>sn),s.fetchQuery({...mr({client:V,path:{name:t},query:ne?{window:ne}:void 0}),staleTime:cs}).catch(()=>pn),s.fetchQuery({...xr({client:V,path:{name:t},query:ne?{window:ne}:void 0}),staleTime:cs}).catch(()=>[]),s.fetchQuery({...hr({client:V,path:{name:t},query:ne?{window:ne}:void 0}),staleTime:cs}).catch(()=>[])]);if(L.current)return;r(ue),U(Pe),ae(tn),M(Ye),u(!1)}catch(pe){if(L.current)return;A(pe instanceof Error?pe.message:"Failed to load GA4 data"),u(!1)}}o.useEffect(()=>{const L={current:!1};return z(L),()=>{L.current=!0}},[t,ie,s]);async function K(){m(!0),A(null),w(null);try{const L=await Ya(t);w(`Synced ${L.rowCount.toLocaleString()} page rows, ${L.aiReferralCount.toLocaleString()} AI and ${L.socialReferralCount.toLocaleString()} social referral rows (${L.days} days)`),await De(s,"ga"),await z({current:!1})}catch(L){A(L instanceof Error?L.message:"Sync failed")}finally{m(!1)}}async function P(){d(!0),A(null),w(null);try{await pr(t),await De(s,"ga"),a({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),r(null),w("GA4 disconnected")}catch(L){A(L instanceof Error?L.message:"Disconnect failed")}finally{d(!1)}}function ee(L){g===L?T(pe=>pe==="desc"?"asc":"desc"):(D(L),T("desc"))}function fe(L){q===L?E(pe=>pe==="desc"?"asc":"desc"):(h(L),E("desc"))}function Ce(L){X===L?p(pe=>pe==="desc"?"asc":"desc"):(le(L),p("desc"))}const qe=o.useMemo(()=>i?.topPages?[...i.topPages].sort((L,pe)=>{const ne=L[g],ue=pe[g];return typeof ne=="string"&&typeof ue=="string"?F==="asc"?ne.localeCompare(ue):ue.localeCompare(ne):F==="asc"?ne-ue:ue-ne}):[],[i?.topPages,g,F]),Ge=o.useMemo(()=>i?.aiReferrals?[...i.aiReferrals].sort((L,pe)=>{const ne=L[q],ue=pe[q];return typeof ne=="string"&&typeof ue=="string"?k==="asc"?ne.localeCompare(ue):ue.localeCompare(ne):k==="asc"?ne-ue:ue-ne}):[],[i?.aiReferrals,q,k]),gt=o.useMemo(()=>i?.aiReferralLandingPages?[...i.aiReferralLandingPages].sort((L,pe)=>{const ne=L[_],ue=pe[_];return typeof ne=="string"&&typeof ue=="string"?G==="asc"?ne.localeCompare(ue):ue.localeCompare(ne):G==="asc"?ne-ue:ue-ne}):[],[i?.aiReferralLandingPages,_,G]),Ne=js({rows:gt,getSearchText:ac,pageSize:ic}),ft=Ne.totalRows>0?`${Ne.totalRows.toLocaleString()} ${Ne.hasQuery?Ne.totalRows===1?"match":"matches":Ne.totalRows===1?"row":"rows"}`:Ne.hasQuery&&(i?.aiReferralLandingPages.length??0)>0?"0 matches":"No landing-page rows";function We(L){Ne.setPage(1),_===L?re(pe=>pe==="desc"?"asc":"desc"):(y(L),re("desc"))}const Me=o.useMemo(()=>i?.socialReferrals?[...i.socialReferrals].sort((L,pe)=>{const ne=L[X],ue=pe[X];return typeof ne=="string"&&typeof ue=="string"?S==="asc"?ne.localeCompare(ue):ue.localeCompare(ne):S==="asc"?ne-ue:ue-ne}):[],[i?.socialReferrals,X,S]),{socialChartData:W,socialChartSources:be,socialOtherCount:Le}=o.useMemo(()=>{const L=tc(O);return{socialChartData:L.data,socialChartSources:L.sources,socialOtherCount:L.otherCount}},[O]),{chartData:at,chartSources:R,dateRange:we}=o.useMemo(()=>{const L=sc(J,oe);return{chartData:L.data,chartSources:L.sources,dateRange:L.dateRange}},[J,oe]);if(l&&!n)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!n?.connected)return Q()?e.jsx(Y,{className:"p-5",children:e.jsx("div",{className:"text-sm text-secondary",children:"No Google Analytics 4 property connected yet."})}):e.jsx(cc,{projectName:t,onConnected:()=>{(async()=>(await De(s,"ga"),await z({current:!1})))()}});const ke=i?.organicSharePctDisplay??"0%",bt=i?.channelBreakdown?.organic.sharePctDisplay??ke,N=i?.channelBreakdown?.organic.sessions??i?.totalOrganicSessions??0,ce=i?.aiSessionsDeduped??0,de=i?.channelBreakdown?.ai.sessions??i?.aiSessionsBySession??0,it=i?.channelBreakdown?.ai.sharePctDisplay??i?.aiSharePctBySessionDisplay??"0%",Ie=i?.paidAiSessionsBySession??0,Cs=i?.paidAiSharePctBySessionDisplay??"0%",Et=i?new Set(i.aiReferrals.map(L=>L.source.toLowerCase())).size:0,jt=Ge[0]??null,Zs=i?.totalDirectSessions??0,ks=i?.directSharePctDisplay??"0%",As=i?.channelBreakdown?.direct.sessions??Zs,en=i?.channelBreakdown?.direct.sharePctDisplay??ks,ss=i?.channelBreakdown?.other.sessions??i?.otherSessions??0,ns=i?.channelBreakdown?.other.sharePctDisplay??i?.otherSharePctDisplay??"0%",rt=i?.socialSessions??0,as=i?.socialSharePctDisplay??"0%",$s=i?.channelBreakdown?.social.sessions??rt,Ps=i?.channelBreakdown?.social.sharePctDisplay??as,ot=i?new Set(i.socialReferrals.map(L=>L.source.toLowerCase())).size:0,ze=Me[0]??null;return e.jsxs(e.Fragment,{children:[b&&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:b}),$&&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:$}),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})]})]})]}),!Q()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(I,{variant:"outline",size:"sm",disabled:x,onClick:he(K),children:[e.jsx(bs,{className:`w-3.5 h-3.5 mr-1.5 ${x?"animate-spin":""}`}),x?"Syncing…":"Sync"]}),e.jsxs(I,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:f,onClick:he(P),children:[e.jsx(Dl,{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($e,{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:"segmented",role:"group","aria-label":"Traffic time period",children:nc.map(L=>e.jsx("button",{type:"button","aria-pressed":ie===L,className:`segmented-option ${ie===L?"segmented-option-active":""}`,onClick:()=>v(L),children:L==="all"?"All":L},L))})]}),i?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(gn,{value:qs(i.totalSessions),label:"Total Sessions",subtitle:i.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(gn,{value:qs(i.totalOrganicSessions),label:"Organic Sessions",subtitle:`${ke} of total`,tone:"positive"}),e.jsx(gn,{value:qs(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."}),!Q()&&e.jsxs(I,{variant:"outline",size:"sm",disabled:x,onClick:he(K),children:[e.jsx(bs,{className:`w-3.5 h-3.5 mr-1.5 ${x?"animate-spin":""}`}),"Sync from GA4"]})]})]}),i&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Traffic Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Traffic by channel",e.jsx($e,{text:"Decomposes GA4 sessions into five disjoint channels — known AI referrers first, then organic search, social, direct, and other channels. Known AI includes paid and organic AI referrals; paid rows are labeled in the source table below. Known AI referrers are removed from their native GA4 channel before the residual Other bucket is computed."})]})]}),we&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(we.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(we.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),at.length>0&&e.jsxs(Y,{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:R.length>0?"AI vs. total sessions":"All sessions (baseline)"}),R.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),R.length===0&&e.jsx("p",{className:"text-xs text-muted",children:"No AI referrals detected yet"})]}),e.jsx("div",{className:"h-64",children:e.jsx(Wt,{width:"100%",height:"100%",children:e.jsxs(Yt,{data:at,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Jt,{dataKey:"date",tick:Ve,tickLine:!1,axisLine:{stroke:pt},tickFormatter:Dn}),e.jsx(Xt,{tick:Ve,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Zt,{...It,labelFormatter:Ws,formatter:(L,pe)=>{const ne=typeof L=="number"?L.toLocaleString():String(L??0),ue=String(pe??"");return ue==="_totalSessions"?[ne,"Total Sessions"]:ue==="_organicSessions"?[ne,"Organic Sessions"]:[ne,ue]}}),e.jsx(di,{wrapperStyle:{fontSize:11,color:_e.text},formatter:L=>L==="_totalSessions"?"Total Sessions":L==="_organicSessions"?"Organic Sessions":L}),e.jsx(Bt,{type:"monotone",dataKey:"_totalSessions",stroke:_e.textFaint,fill:_e.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),R.map((L,pe)=>e.jsx(Bt,{type:"monotone",dataKey:L,stackId:"ai",stroke:wt[pe%wt.length],fill:wt[pe%wt.length],fillOpacity:.4,strokeWidth:1.5},L))]})})})]}),e.jsxs(Y,{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:bt,hint:`${N.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:Ps,hint:`${$s.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:en,hint:`${As.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:it,hint:Ie>0?`${de.toLocaleString()} sessions · ${Ie.toLocaleString()} paid`:`${de.toLocaleString()} sessions`,tone:"positive",tooltip:"Sessions whose current sessionSource matched a known AI engine (e.g. chatgpt.com, claude.ai, gemini.google.com). Paid AI is inferred from paid/cpc/sponsored UTM values or GA4 paid channel groups. Untagged ad clicks with no referrer still fall under Direct because GA4 has no paid evidence for them."}),e.jsx(Ze,{label:"Other channels",value:ns,hint:`${ss.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."})]}),jt&&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:jt.source})," via ",jt.medium,", accounting for ",jt.sessions.toLocaleString()," sessions.",Ie>0&&e.jsxs("span",{children:[" Paid AI: ",Ie.toLocaleString()," sessions (",Cs,")."]})]})]}),e.jsxs(Y,{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?`${Et} unique sources, ${i.aiReferrals.length} rows`:"No source rows"})]}),i.aiReferrals.length>0?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(Qe,{label:"Source",sortKey:"source",current:q,dir:k,onSort:fe,align:"left"}),e.jsx(Qe,{label:"Medium",sortKey:"medium",current:q,dir:k,onSort:fe,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Class"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(Qe,{label:"Sessions",sortKey:"sessions",current:q,dir:k,onSort:fe,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:Ge.map(L=>e.jsx(uc,{referral:L,totalSessions:ce},`${L.source}:${L.medium}:${L.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(Y,{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:ft})]}),i.aiReferralLandingPages.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Qt,{value:Ne.query,onChange:Ne.setQuery,label:"Filter landing page URLs or query parameters",placeholder:"Filter URL or query parameters",className:"mb-4 max-w-md"}),Ne.totalRows>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(Qe,{label:"Landing Page",sortKey:"landingPage",current:_,dir:G,onSort:We,align:"left"}),e.jsx(Qe,{label:"Source",sortKey:"source",current:_,dir:G,onSort:We,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(Qe,{label:"Sessions",sortKey:"sessions",current:_,dir:G,onSort:We,align:"right"})]})}),e.jsx("tbody",{children:Ne.rows.map(L=>e.jsx(mc,{row:L},`${L.landingPage}:${L.source}:${L.medium}:${L.sourceDimension}`))})]})}),e.jsx(Tt,{page:Ne.page,pageSize:Ne.pageSize,visibleRows:Ne.rows.length,totalRows:Ne.totalRows,onPageChange:Ne.setPage,itemLabel:Ne.hasQuery?"matches":"rows"})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary",children:"No landing pages match this filter"}),e.jsx("button",{type:"button",onClick:()=>Ne.setQuery(""),className:"mt-2 text-xs text-link hover:underline focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",children:"Clear filter"})]})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No AI landing pages detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"Known-AI landing pages appear after a GA4 sync records visits from AI referrers."})]})]})]})]}),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($e,{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."})]})]}),W.length>0&&e.jsxs(Y,{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"})]}),Le>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",be.length-1," sources · ",Le," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(Wt,{width:"100%",height:"100%",children:e.jsxs(Yt,{data:W,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Jt,{dataKey:"date",tick:Ve,tickLine:!1,axisLine:{stroke:pt},tickFormatter:Dn}),e.jsx(Xt,{tick:Ve,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Zt,{...It,labelFormatter:Ws,formatter:(L,pe)=>{const ne=typeof L=="number"?L.toLocaleString():String(L??0),ue=String(pe??"");if(ue===zt)return[ne,"Total Social"];if(ue===es){const Pe=`Other (${Le} source${Le===1?"":"s"})`;return[ne,Pe]}return[ne,Ht(ue)]}}),e.jsx(Bt,{type:"monotone",dataKey:zt,stroke:vi,fill:_e.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),be.map((L,pe)=>{const ue=L===es?Mn:wt[pe%wt.length];return e.jsx(Bt,{type:"monotone",dataKey:L,stackId:"social",stroke:ue,fill:ue,fillOpacity:.4,strokeWidth:1.5},L)})]})})}),e.jsx(hc,{sources:be,otherCount:Le})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.5fr)]",children:[e.jsxs(Y,{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:qs(rt),hint:`${rt.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:as,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(ot),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."})]}),ze&&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:`${ze.source} via ${ze.medium}`,children:yi(Ht(ze.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:ze.medium,children:["via ",Ht(ze.medium)," · ",ze.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(Y,{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?Me.length>ds&&!j?`Top ${ds} of ${Me.length}`:`${Me.length} rows`:"No source rows"})]}),i.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm table-fixed",children:[e.jsxs("colgroup",{children:[e.jsx("col",{className:"w-[32%]"}),e.jsx("col",{className:"w-[22%]"}),e.jsx("col",{className:"w-[12%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[12%]"})]}),e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(Qe,{label:"Source",sortKey:"source",current:X,dir:S,onSort:Ce,align:"left"}),e.jsx(Qe,{label:"Medium",sortKey:"medium",current:X,dir:S,onSort:Ce,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(Qe,{label:"Sessions",sortKey:"sessions",current:X,dir:S,onSort:Ce,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(Qe,{label:"Users",sortKey:"users",current:X,dir:S,onSort:Ce,align:"right"})]})}),e.jsx("tbody",{children:(j?Me:Me.slice(0,ds)).map(L=>e.jsx(xc,{referral:L,totalSessions:rt},`${L.source}:${L.medium}:${L.channelGroup}`))})]})}),Me.length>ds&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>Z(L=>!L),className:"rounded-md border border-base px-3 py-1.5 text-xs text-secondary transition-colors hover:border-strong hover:text-strong",children:j?`Show top ${ds}`:`Show all ${Me.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($e,{text:"Landing pages ranked by session volume. Click column headers to sort. Organic % shows the share of sessions coming from Google organic search."})]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(Qe,{label:"Landing Page",sortKey:"landingPage",current:g,dir:F,onSort:ee,align:"left"}),e.jsx(Qe,{label:"Sessions",sortKey:"sessions",current:g,dir:F,onSort:ee,align:"right"}),e.jsx(Qe,{label:"Organic",sortKey:"organicSessions",current:g,dir:F,onSort:ee,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"})]})}),e.jsx("tbody",{children:qe.map(L=>e.jsx(dc,{page:L},L.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 ${Ni(i.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:i?`${i.topPages.length} pages · ${i.aiReferrals.length} AI rows · ${i.socialReferrals.length} social rows`:""})]})]})}function cc({projectName:t,onConnected:s}){const[n,a]=o.useState(""),[i,r]=o.useState(null),[l,u]=o.useState(null),[x,m]=o.useState(!1),[f,d]=o.useState(null),b=o.useRef(null),A=o.useCallback(w=>{const g=w.target.files?.[0];if(!g)return;d(null),r(g.name);const D=new FileReader;D.onload=()=>{const F=D.result;try{const T=JSON.parse(F);if(!T.client_email||!T.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)."),u(null);return}u(F)}catch{d("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),u(null)}},D.onerror=()=>{d("Failed to read file."),u(null)},D.readAsText(g)},[]);async function $(){if(d(null),!n.trim()){d("Property ID is required.");return}if(!l){d("Please upload a service account key file.");return}m(!0);try{await gr(t,{propertyId:n.trim(),keyJson:l});try{await Ya(t)}catch{}s()}catch(w){d(w instanceof Error?w.message:"Failed to connect GA4")}finally{m(!1)}}return e.jsxs(Y,{className:"surface-card p-6",children:[e.jsx("h3",{className:"text-base font-semibold text-primary mb-1",children:"Connect Google Analytics 4"}),e.jsx("p",{className:"text-sm text-secondary mb-5",children:"Connect a GA4 property to see traffic data for this project. You'll need a service account key file from Google Cloud Console."}),f&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative",children:f}),e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{htmlFor:"ga4-property-id",className:"block text-xs font-medium text-secondary mb-1.5",children:"GA4 Property ID"}),e.jsx("input",{id:"ga4-property-id",type:"text",placeholder:"e.g. 123456789",value:n,onChange:w=>a(w.target.value),className:"w-full rounded-lg bg-bg-elevated/60 border border-default px-3 py-2 text-sm text-strong placeholder-mono-600 focus:outline-none focus:ring-1 focus:ring-mono-600"}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:"Find this in GA4 → Admin → Property Settings. It's a numeric ID, not the Measurement ID (G-XXXXXX)."})]}),e.jsxs("div",{className:"mb-5",children:[e.jsx("label",{className:"block text-xs font-medium text-secondary mb-1.5",children:"Service Account Key File"}),e.jsx("input",{ref:b,type:"file",accept:".json,application/json",onChange:A,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>b.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(Tl,{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(I,{variant:"default",size:"sm",disabled:x||!n.trim()||!l,onClick:he($),children:x?"Connecting & syncing…":"Connect GA4"})]})}function Qe({label:t,sortKey:s,current:n,dir:a,onSort:i,align:r}){const l=n===s;return e.jsx("th",{className:`py-1 ${r==="right"?"text-right":"text-left"}`,children:e.jsxs("button",{type:"button",className:"font-medium cursor-pointer select-none hover:text-neutral transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-400 rounded",onClick:()=>i(s),"aria-label":`Sort by ${t}${l?` (currently ${a==="asc"?"ascending":"descending"})`:""}`,children:[t,l&&e.jsx("span",{className:"ml-0.5",children:a==="asc"?"↑":"↓"})]})})}const wi={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function gn({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 ${wi[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($e,{text:i})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${wi[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function dc({page:t}){const s=t.sessions>0?(t.organicSessions/t.sessions*100).toFixed(1):"0.0";return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 text-neutral max-w-[400px] truncate",title:t.landingPage,children:t.landingPage}),e.jsx("td",{className:"py-1.5 text-right text-strong tabular-nums",children:t.sessions.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.organicSessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[s,"%"]})]})}const Si={session:"Session",first_user:"First Visit",manual_utm:"UTM"},Ci={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 uc({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=Si[t.sourceDimension]??t.sourceDimension,i=Ci[t.sourceDimension]??"",r=t.trafficClass==="paid"?"Paid":"Organic",l=t.trafficClass==="paid"?"Paid AI traffic inferred from paid/cpc/sponsored UTM values or a GA4 paid channel group":"AI traffic without a paid attribution signal";return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 text-strong max-w-[220px] truncate",title:t.source,children:t.source}),e.jsx("td",{className:"py-1.5 text-muted max-w-[180px] truncate",title:t.medium,children:t.medium}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:`inline-block text-[10px] px-1.5 py-0.5 rounded-full border ${t.trafficClass==="paid"?"border-caution-700 text-caution-300":"border-strong text-secondary"}`,title:l,children:r})}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:i,children:a})}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[n,"%"]})]})}function mc({row:t}){const s=Si[t.sourceDimension]??t.sourceDimension,n=Ci[t.sourceDimension]??"";return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"max-w-[400px] py-1.5 text-neutral",children:e.jsx(ps,{value:t.landingPage,className:"whitespace-nowrap"})}),e.jsx("td",{className:"py-1.5 text-strong max-w-[220px] truncate",title:t.source,children:t.source}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:n,children:s})}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.sessions.toLocaleString()})]})}function xc({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=t.channelGroup==="Paid Social"?"Paid":"Organic",i=Ht(t.source),r=Ht(t.medium);return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 pr-3 text-strong truncate",title:t.source,children:i}),e.jsx("td",{className:"py-1.5 pr-3 text-muted truncate",title:t.medium,children:r}),e.jsx("td",{className:"py-1.5 pr-3",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:`GA4 channel group: ${t.channelGroup}`,children:a})}),e.jsx("td",{className:"py-1.5 text-right text-info-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[n,"%"]}),e.jsx("td",{className:"py-1.5 text-right text-strong tabular-nums",children:t.users.toLocaleString()})]})}function hc({sources:t,otherCount:s}){const n=[{key:zt,color:vi,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const i=t[a];if(i===es)n.push({key:es,color:Mn,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const r=Ht(i);n.push({key:i,color:wt[a%wt.length]??Mn,label:yi(r,32),tooltip:r})}}return e.jsx("div",{className:"mt-3 flex flex-wrap gap-x-4 gap-y-1.5 text-[11px] text-secondary",children:n.map(a=>e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 max-w-[260px]",title:a.tooltip,children:[e.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-sm shrink-0",style:{backgroundColor:a.color},"aria-hidden":"true"}),e.jsx("span",{className:"truncate",children:a.label})]},a.key))})}function pc(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 gc=["7d","30d","90d","all"],Gs=500,vt=25,fc="canonry:google-oauth-complete";function Pa(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function La(t){const s=Number(t.errors??0),n=Number(t.warnings??0);return[s>0?`${s} error${s===1?"":"s"}`:"",n>0?`${n} warning${n===1?"":"s"}`:""].filter(Boolean).join(" · ")}function Ra(t){return t.isPending?"Processing":Number(t.errors??0)>0?"Errors":Number(t.warnings??0)>0?"Warnings":"Success"}function bc({projectName:t,refreshNonce:s}){const n=kt(),[a,i]=o.useState(!1),[r,l]=o.useState([]),[u,x]=o.useState([]),[m,f]=o.useState([]),[d,b]=o.useState(null),[A,$]=o.useState([]),[w,g]=o.useState([]),[D,F]=o.useState(null),[T,q]=o.useState(""),[h,k]=o.useState(""),[E,X]=o.useState("30"),[le,S]=o.useState(!1),[p,_]=o.useState("30d"),[y,G]=o.useState({startDate:"",endDate:"",query:"",page:""}),[re,J]=o.useState(0),[U,oe]=o.useState(!1),[ae,O]=o.useState(0),[M,j]=o.useState(!1),[Z,ie]=o.useState(""),[v,z]=o.useState(!0),[K,P]=o.useState(!1),[ee,fe]=o.useState(!1),[Ce,qe]=o.useState(!1),[Ge,gt]=o.useState(!1),[Ne,ft]=o.useState(!1),[We,Me]=o.useState(!1),[W,be]=o.useState(null),[Le,at]=o.useState(!1),[R,we]=o.useState(!1),[ke,bt]=o.useState(null),[N,ce]=o.useState(null),[de,it]=o.useState([]),[Ie,Cs]=o.useState(new Set),[Et,jt]=o.useState({}),[Zs,ks]=o.useState(new Set),[As,en]=o.useState(""),[ss,ns]=o.useState(null),[rt,as]=o.useState(""),[$s,Ps]=o.useState(!1),[ot,ze]=o.useState(!1),[L,pe]=o.useState(!1),[ne,ue]=o.useState(!1),[Pe,tn]=o.useState("indexed"),[Ye,sn]=o.useState(null),nn=!!(y.query.trim()||y.page.trim()||Ye),Ti=Ye!==null,Xn=o.useMemo(()=>{if(!Ye)return m;const{key:c,dir:C}=Ye;return[...m].sort((B,H)=>{const xe=c===Rt.CTR?Number.isFinite(B.ctr)?B.ctr:0:B[c],je=c===Rt.CTR?Number.isFinite(H.ctr)?H.ctr:0:H[c];return C==="asc"?xe-je:je-xe})},[m,Ye]),Ot=js({rows:Xn,pageSize:et}),Zn=M?Ot.rows:Xn,Ft=js({rows:(ke??[]).filter(c=>c.path.toLowerCase().includes(As.trim().toLowerCase())),pageSize:et}),[tt,ea]=o.useState([]),[Je,Ls]=o.useState(null),[Mi,ta]=o.useState(1),is=o.useMemo(()=>{if(tt.length<2)return null;const c=tt[tt.length-1],C=tt[tt.length-2];return{indexed:c.indexed-C.indexed,notIndexed:c.notIndexed-C.notIndexed}},[tt]);o.useEffect(()=>{ta(1)},[W,Pe,Je]);const Rs=o.useMemo(()=>Je?(W?.reasonGroups??[]).find(c=>c.reason===Je):void 0,[W,Je]),an=o.useMemo(()=>W?Pe==="indexed"?W.indexed:Pe==="deindexed"?W.deindexed:Pe==="notIndexed"?Je?Rs?.urls??[]:(W.reasonGroups??[]).length===0?W.notIndexed:[]:[]:[],[W,Pe,Je,Rs]),Ei=Math.max(1,Math.ceil(an.length/vt)),sa=Math.min(Math.max(1,Mi),Ei),Ue=(sa-1)*vt,Oi=o.useMemo(()=>W?.indexed.slice(Ue,Ue+vt)??[],[W,Ue]),Fi=o.useMemo(()=>W?.notIndexed.slice(Ue,Ue+vt)??[],[W,Ue]),_i=o.useMemo(()=>W?.deindexed.slice(Ue,Ue+vt)??[],[W,Ue]),qi=o.useMemo(()=>(Rs?.urls??[]).slice(Ue,Ue+vt),[Rs,Ue]),[rs,Ds]=o.useState(!1),[na,ge]=o.useState(null),[lt,Is]=o.useState(null),[aa,ct]=o.useState(null);function Gi(c,C){const B=jl(c),H=pc(B);H?(Is(H),ge(null)):(Is(null),ge(B.message||C))}const Be=r.find(c=>c.connectionType==="gsc"),At=(Be?.scopes??[]).includes("https://www.googleapis.com/auth/webmasters"),rn=de.length>0?de:(ke??[]).map(c=>c.path),ia=rn.filter(c=>ke?.some(C=>C.path===c&&C.isSitemapsIndex)).length,Bi=ia===1?"Resubmit sitemap index":ia>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",Ui=m.length>0||A.length>0||w.length>0,on=fr(),ln=br();async function ra(c,C=!1){if(!c){x([]),q("");return}fe(!0);try{const{sites:B}=await n.fetchQuery({...Rr({client:V,path:{name:t}}),staleTime:C?0:Te});x(B),q(c.propertyId??B[0]?.siteUrl??""),Is(null)}catch(B){x([]),Gi(B,"Failed to load Search Console properties")}finally{fe(!1)}}async function os(c){gt(!0);const C=c??re;try{const B=nn?Gs:et,H=nn?0:C,xe={limit:String(B)};y.startDate&&(xe.startDate=y.startDate),y.endDate&&(xe.endDate=y.endDate),y.query&&(xe.query=y.query),y.page&&(xe.page=y.page),H>0&&(xe.offset=String(H)),p&&p!=="all"&&!y.startDate&&(xe.window=p);const je=await n.fetchQuery({...yr({client:V,path:{name:t},query:xe}),staleTime:Te}),ye=je.rows;nn?(oe(!1),f(ye),O(ye.length),j(!0)):(oe(H+ye.length<je.totalMatching),f(ye),O(0),j(!1))}catch(B){f([]),oe(!1),O(0),ge(B instanceof Error?B.message:"Failed to load GSC performance data")}finally{gt(!1)}}async function cn(){try{const c={};y.startDate&&(c.startDate=y.startDate),y.endDate&&(c.endDate=y.endDate),p&&p!=="all"&&!y.startDate&&(c.window=p);const C=await n.fetchQuery({...vr({client:V,path:{name:t},query:c}),staleTime:Te});b(C)}catch{b(null)}}async function Ts(c=!1){ft(!0);try{const C=Z.trim()||void 0,B={limit:"20"};C&&(B.url=C);const[H,xe]=await Promise.all([n.fetchQuery({...Pr({client:V,path:{name:t},query:B}),staleTime:c?0:Te}),n.fetchQuery({...Lr({client:V,path:{name:t}}),staleTime:c?0:Te})]);$(H),g(xe)}catch(C){$([]),g([]),ge(C instanceof Error?C.message:"Failed to load GSC inspection history")}finally{ft(!1)}}async function oa(c=!1){at(!0);try{const[C,B]=await Promise.all([n.fetchQuery({...Xa({client:V,path:{name:t}}),staleTime:c?0:Te}),n.fetchQuery({...Sr({client:V,path:{name:t}}),staleTime:c?0:Te}).catch(()=>[])]);be(C),ea(B)}catch(C){be(null),ea([]),ge(C instanceof Error?C.message:"Failed to load coverage data")}finally{at(!1)}}async function la(c){Ds(!0),ge(null);try{const C=await ga(t,{urls:c}),{succeeded:B,failed:H,total:xe}=C.summary;se({title:"Indexing requested",detail:H===0?`${B} URL${B!==1?"s":""} submitted for indexing.`:`${B}/${xe} submitted successfully, ${H} failed.`,tone:H===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(C){ge(C instanceof Error?C.message:"Failed to request indexing")}finally{Ds(!1)}}async function Qi(){Ds(!0),ge(null);try{const c=await ga(t,{urls:[],allUnindexed:!0}),{succeeded:C,failed:B,total:H}=c.summary;se({title:"Indexing requested",detail:B===0?`${C} unindexed URL${C!==1?"s":""} submitted for indexing.`:`${C}/${H} submitted successfully, ${B} failed.`,tone:B===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(c){ge(c instanceof Error?c.message:"Failed to request indexing")}finally{Ds(!1)}}async function dn(){we(!0),ge(null);try{const c=await un(t);n.setQueryData(Cr({client:V,path:{name:t}}),c),bt(c.sitemaps),ce(c.summary),it(c.preferredSubmissionUrls),Cs(new Set),jt({}),c.sitemaps.length===0&&ct("No sitemaps found in this GSC property. Submit one here to start Google processing it.")}catch(c){ge(c instanceof Error?c.message:"Failed to list sitemaps")}finally{we(!1)}}async function zi(c){const C=Ie.has(c);if(Cs(B=>{const H=new Set(B);return C?H.delete(c):H.add(c),H}),!(C||Et[c])){ks(B=>new Set(B).add(c));try{const B=await un(t,c);jt(H=>({...H,[c]:B.sitemaps}))}catch(B){ge(B instanceof Error?B.message:"Failed to load sitemap files")}finally{ks(B=>{const H=new Set(B);return H.delete(c),H})}}}async function _t(c){if(!At||c.length===0)return;const C=[...new Set(c)];ze(!0),ge(null),ns({completed:0,total:C.length});let B=0,H=0,xe=0,je=null;try{for(let Ae=0;Ae<C.length;Ae+=50){const me=C.slice(Ae,Ae+50);try{const Ee=await kr(t,me);B+=Ee.summary.accepted,H+=Ee.summary.failed,xe+=me.length,ns({completed:xe,total:C.length})}catch(Ee){xe+=me.length;const Xe=me.length,$t=C.length-xe,qt=Ee instanceof Error?Ee.message:"The batch request failed",ls=`${B} accepted, ${H} failed, ${Xe} unconfirmed, ${$t} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;je=`Sitemap submission stopped after a batch request failed. ${ls} ${qt}`,ge(je),se({title:"Sitemap resubmission partially completed",detail:ls,tone:"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"});return}}const ye=C.length;se({title:H===0?"Sitemap submitted to Google":"Some sitemap submissions need attention",detail:H===0?"Google accepted the sitemap submission/refetch request; indexing is not guaranteed.":`Google accepted ${B}/${ye} sitemap submissions; ${H} failed. Indexing is not guaranteed.`,tone:H===0?"positive":"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"}),as("")}catch(ye){ge(ye instanceof Error?ye.message:"Failed to submit sitemap to Google")}finally{ze(!1),ns(null),await dn(),je&&ge(je)}}async function Hi(){ze(!0);const c=ke??[];try{const C=c.filter(H=>H.isSitemapsIndex),B=[];for(let H=0;H<C.length;H+=4)(await Promise.all(C.slice(H,H+4).map(async je=>{const ye=Et[je.path];if(ye)return ye;const Ae=await un(t,je.path);return jt(me=>({...me,[je.path]:Ae.sitemaps})),Ae.sitemaps}))).forEach((je,ye)=>{B.push(...je.length>0?je.map(Ae=>Ae.path):[C[H+ye].path])});await _t([...c.filter(H=>!H.isSitemapsIndex).map(H=>H.path),...B])}catch(C){ge(C instanceof Error?C.message:"Failed to load sitemap files"),ze(!1)}}async function ca(c){Ps(!0),ge(null);try{await Ar(t,"gsc",c),await De(n,"google"),l(C=>C.map(B=>B.connectionType==="gsc"?{...B,sitemapUrl:c}:B)),se({title:"Default sitemap updated",detail:c,tone:"positive",dedupeKey:`gsc:sitemap-default:${t}`,dedupeMode:"replace"})}catch(C){ge(C instanceof Error?C.message:"Failed to set the default sitemap")}finally{Ps(!1)}}async function da(c){try{await ln.mutateAsync({projectName:t,projectLabel:t,opts:c?{sitemapUrl:c}:void 0})}catch{}}async function ua(){z(!0),ge(null);try{const[c,C]=await Promise.all([Ja().catch(()=>null),n.fetchQuery({...Gn({client:V,path:{name:t}}),staleTime:Te}).catch(()=>[])]);i(!!c?.google?.configured),l(C);const B=C.find(H=>H.connectionType==="gsc");await Promise.all([ra(B),os(),cn(),Ts(),oa(),B?.propertyId?dn():Promise.resolve()])}finally{z(!1)}}o.useEffect(()=>{ua()},[t,s]),o.useEffect(()=>{J(0),os(0),cn()},[p]);const ma=o.useRef(!1);o.useEffect(()=>{if(!ma.current){ma.current=!0;return}J(0),os(0)},[Ti]);async function xa(){if(!a){ge("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}P(!0),ge(null),ct(null);try{let c=function(Ee){if(Ee.source!==H||Ee.origin!==xe||!Ee.data||typeof Ee.data!="object")return;const Xe=Ee.data;Xe.type!==fc||Xe.connectionType!=="gsc"||me(!0)};const{authUrl:C,redirectUri:B}=await wr(t,"gsc");if(!C.startsWith("https://accounts.google.com/")){ge("Unexpected OAuth redirect URL. Please try again.");return}const H=window.open(C,"_blank","width=600,height=700");if(!H){window.location.assign(C);return}const xe=B?new URL(B).origin:window.location.origin;let je=!1,ye=null;const Ae=()=>{ye!==null&&window.clearInterval(ye),window.removeEventListener("message",c)},me=async Ee=>{if(!je){je=!0,Ae(),ct(Ee?"Google connected. Refreshing access…":"Refreshing Google connection…");try{await De(n,"google"),await ua()}finally{ct(null)}}};window.addEventListener("message",c),ct("Finish the Google consent flow in the popup. This page will refresh automatically."),ye=window.setInterval(()=>{H.closed&&me(!1)},1e3)}catch(c){ge(c instanceof Error?c.message:"Failed to start OAuth flow")}finally{P(!1)}}async function Ki(){ge(null),ct(null);try{await Nr(t,"gsc"),await De(n,"google"),l(c=>c.filter(C=>C.connectionType!=="gsc")),x([]),q("")}catch(c){ge(c instanceof Error?c.message:"Failed to disconnect")}}async function Vi(){if(T){qe(!0),ge(null);try{await Dr(t,"gsc",T),await De(n,"google"),l(c=>c.map(C=>C.connectionType==="gsc"?{...C,propertyId:T}:C)),se({title:"GSC property updated",detail:`${t} is now linked to ${T}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(c){ge(c instanceof Error?c.message:"Failed to save GSC property")}finally{qe(!1)}}}async function Wi(){ge(null),ct(null);try{await on.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(E,10)||void 0,full:le||void 0}}),await De(n,"gsc")}catch{}}async function ha(){if(h.trim()){Me(!0),ge(null),ct(null);try{const c=await $r(t,h.trim());await De(n,"gsc"),F(c),k(""),await Ts()}catch(c){ge(c instanceof Error?c.message:"Failed to inspect URL")}finally{Me(!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"})]})}),lt&&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:lt.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:lt.message}),(Pt(lt.enableUrl)||Pt(lt.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[Pt(lt.enableUrl)&&e.jsx("a",{href:Pt(lt.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 ↗"}),Pt(lt.indexingApiUrl)&&e.jsx("a",{href:Pt(lt.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:()=>Is(null),children:"×"})]})}),na&&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:[na,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>ge(null),children:"×"})]}),aa&&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:[aa,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>ct(null),children:"×"})]}),v?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[Be?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:Be.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Last updated ",st(Be.updatedAt)]}),e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:he(Ki),children:"Disconnect"})]}):e.jsxs(Y,{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(te,{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(I,{type:"button",variant:"outline",size:"sm",disabled:K,onClick:he(xa),children:K?"Opening…":"Connect Google Search Console"}):e.jsx(I,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(xt,{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."})]})]})]}),(Be||Ui)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs(Y,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Performance"}),e.jsx("h3",{children:"Search performance"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"segmented",role:"group","aria-label":"Performance time period",children:gc.map(c=>e.jsx("button",{type:"button","aria-pressed":p===c,className:`segmented-option ${p===c?"segmented-option-active":""}`,onClick:()=>{_(c),J(0),Ot.setPage(1)},children:c==="all"?"All":c},c))}),e.jsx(I,{type:"button",variant:"outline",size:"sm",disabled:Ge,onClick:()=>{J(0),Ot.setPage(1),os(0),cn()},children:Ge?"Loading…":"Apply filters"})]})]}),d&&d.daily.length>0&&(()=>{const c=d.daily,C=Math.max(...c.map(Se=>Se.impressions),1),{clicks:B,impressions:H,ctr:xe}=d.totals,je=(xe*100).toFixed(1),ye=700,Ae=220,me={top:12,bottom:36,left:48,right:12},Ee=ye-me.left-me.right,Xe=Ae-me.top-me.bottom,$t=Ee/c.length,qt=Math.max(Math.min($t*.35,24),4),ls=Math.max(qt*.15,1),Yi=Se=>{if(Se<=0)return 1;const dt=Math.pow(10,Math.floor(Math.log10(Se))),He=Se/dt,yt=He<=1.5?1.5:He<=3?3:He<=5?5:10;return Math.ceil(yt*dt)},Ms=4,Es=Math.ceil(Yi(C)/Ms)*Ms,Ji=Array.from({length:Ms+1},(Se,dt)=>Es/Ms*dt),Xi=Se=>Se>=1e3?`${(Se/1e3).toFixed(Se>=1e4?0:1)}k`:String(Se);return e.jsxs("div",{className:"mt-3",children:[e.jsxs("div",{className:"flex items-center gap-5 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-sm bg-positive-500"}),e.jsxs("span",{className:"text-xs text-secondary",children:["Clicks ",e.jsx("span",{className:"text-strong tabular-nums font-medium",children:B.toLocaleString()})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-sm bg-chart-series-2"}),e.jsxs("span",{className:"text-xs text-secondary",children:["Impressions ",e.jsx("span",{className:"text-strong tabular-nums font-medium",children:H.toLocaleString()})]})]}),e.jsxs("span",{className:"text-xs text-muted",children:["CTR ",e.jsxs("span",{className:"text-caution-400 tabular-nums font-medium",children:[je,"%"]})]})]}),e.jsx("div",{className:"relative w-full",style:{aspectRatio:`${ye} / ${Ae}`},children:e.jsxs("svg",{viewBox:`0 0 ${ye} ${Ae}`,className:"h-full w-full",children:[Ji.map((Se,dt)=>{const He=me.top+Xe-Se/Es*Xe;return e.jsxs("g",{children:[e.jsx("line",{x1:me.left,y1:He,x2:ye-me.right,y2:He,stroke:_e.gridLine,strokeWidth:"1"}),e.jsx("text",{x:me.left-6,y:He+3.5,textAnchor:"end",fill:_e.text,fontSize:"10",fontFamily:"inherit",children:Xi(Se)})]},`t-${dt}`)}),c.map((Se,dt)=>{const He=me.left+$t*dt+$t/2,yt=Se.impressions/Es*Xe,Os=Se.clicks/Es*Xe;return e.jsxs("g",{children:[e.jsx("title",{children:`${Se.date}
|
|
1
|
+
import{j as e,r as o,L as xt,n as kt,u as ve,o as fs,A as Zi,B as er,h as tr}from"./vendor-tanstack-Be8JdV5M.js";import{c as Ns,T as te,t as sr,a as nr,S as ar,X as ir,C as qn,u as Wa,b as rr,P as Kt,B as I,h as or,d as lr,e as cr,f as Y,i as Q,g as De,j as he,I as $e,k as cs,l as dr,m as V,n as ur,o as mr,p as xr,q as hr,r as Ya,s as pr,v as gr,w as Rt,x as fr,y as br,z as Pt,A as st,D as jr,E as pa,F as Ja,G as Te,H as Gn,J as yr,K as vr,L as Nr,M as wr,N as ga,O as se,Q as Xa,R as Sr,U as un,V as Cr,W as kr,Y as Ar,Z as $r,_ as Pr,$ as Lr,a0 as Rr,a1 as Dr,a2 as Ir,a3 as Tr,a4 as Mr,a5 as Er,a6 as Or,a7 as Fr,a8 as _r,a9 as qr,aa as Mt,ab as Gr,ac as Za,ad as Ks,ae as Br,af as Ur,ag as Qr,ah as zr,ai as Vs,aj as Hr,ak as Kr,al as Vr,am as Ln,an as Wr,ao as Yr,ap as Rn,aq as Jr,ar as Xr,as as Vt,at as ei,au as ti,av as Zr,aw as si,ax as eo,ay as to,az as so,aA as no,aB as ni,aC as ao,aD as io,aE as ro,aF as hs,aG as Dt,aH as oo,aI as lo,aJ as co,aK as uo,aL as ai,aM as mo,aN as xo,aO as ho,aP as po,aQ as go,aR as ii,aS as fo,aT as Bn,aU as bo,aV as jo,aW as yo,aX as vo,aY as No,aZ as wo,a_ as So,a$ as Co,b0 as ko,b1 as Ao,b2 as $o,b3 as Po,b4 as Lo,b5 as Ro,b6 as Do,b7 as Io,b8 as To,b9 as Mo,ba as Eo,bb as mn,bc as Oo,bd as Fo,be as fa,bf as _o,bg as qo,bh as Go,bi as Bo,bj as Uo,bk as Qo,bl as zo,bm as Ho,bn as Ko,bo as Vo,bp as Wo,bq as Yo,br as ba,bs as Jo,bt as xn,bu as Xo,bv as Zo,bw as el,bx as tl,by as sl,bz as nl,bA as al,bB as il,bC as rl,bD as ri,bE as oi,bF as ol,bG as li,bH as ll,bI as ci,bJ as cl,bK as dl,bL as Fs,bM as ul,bN as ml,bO as xl,bP as ja}from"./index-CYGBt2f0.js";import{R as hl}from"./RunRow-RHd8Bd52.js";import{C as pl,R as bs,f as Dn,a as pt,b as Ve,c as Ws,d as It,e as _e,g as Fe,h as ht,i as Un,j as Qn,k as Ct,o as nt,p as gl}from"./ChartPrimitives-0tQT6GE7.js";import{u as fl,t as bl,e as jl}from"./extract-error-message-D0cgM2XG.js";import{R as Wt,C as Yt,X as Jt,Y as Xt,T as Zt,L as di,A as Bt,a as zn,b as yl,d as Hn,e as vl}from"./vendor-recharts-DSxTZhaH.js";import{D as ui,C as Nl,E as wl,T as Sl}from"./trash-2-C_THWxO_.js";import{A as Cl}from"./AuditHistoryPanel-CfaF5B_e.js";import"./vendor-radix-CQ77EO2y.js";import"./vendor-markdown-6dwjPOKK.js";const kl=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],mi=Ns("circle-check",kl);const Al=[["path",{d:"M5 12h14",key:"1ays0h"}]],$l=Ns("minus",Al);const Pl=[["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"}]],Ll=Ns("scan-search",Pl);const Rl=[["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"}]],Dl=Ns("unplug",Rl);const Il=[["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"}]],Tl=Ns("upload",Il);function zs(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 Ml(t,s){return s<=0?null:Math.round((t-s)/s*100)}function hn(t,s,n="vs prior 7 days"){return t.deltaPct===null?t.prior===0?"First baseline week":"":t.deltaPct>0?`Up ${t.deltaPct}% ${n} (${zs(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${zs(t.prior)} ${s})`:`Flat ${n} (${zs(t.prior)} ${s})`}const xi=30;function ya(t){return Math.round(t*10)/10}function El(t){return t.prior>=xi&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% vs prior`:`${t.deltaAbs>0?"+":""}${ya(t.deltaAbs)} vs ${ya(t.prior)}`}function Ol(t,s,n){return t.prior>=xi&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% ${n}`:`${t.deltaAbs>0?"+":""}${zs(Math.round(t.deltaAbs))} ${s} ${n}`}const Fl=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function hi(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function pi(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 gi(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(hi).map(pi).filter(Boolean)):new Set}function fi(t,s){const n=hi(t).map(pi).filter(Boolean).filter(a=>!Fl.has(a)).filter(a=>!s.has(a));return[...new Set(n)].sort().join(" ")}function _l(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function ql(t,s){const n=gi(t);if(s.length<=1||n.size===0)return[...s];const a=new Set,i=[];for(const r of s){if(r.category!=="content"){i.push(r);continue}const l=fi(_l(r),n);!l||a.has(l)||(a.add(l),i.push(r))}return i}function Gl(t){const s=gi(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const a=new Set;return n.filter(i=>{const r=fi(i.query,s);return!r||a.has(r)?!1:(a.add(r),!0)})}function In({state:t,label:s}){return e.jsx(te,{tone:nr(t),children:s??sr(t)})}const et=25;function Bl(t){return t.trim().toLocaleLowerCase().split(/\s+/).filter(Boolean)}function bi(t){let s=t;try{s=decodeURIComponent(t.replace(/\+/g," "))}catch{}let n="";const a=t.indexOf("?");return a>=0&&new URLSearchParams(t.slice(a+1)).forEach((r,l)=>{n+=` ${l} ${r}`}),`${t} ${s}${n}`}function Ul(t,s=36,n=18){const a=[...t];return a.length<=s+n+1?t:`${a.slice(0,s).join("")}…${a.slice(-n).join("")}`}function ps({value:t,headLength:s,tailLength:n,className:a,title:i}){const r=Ul(t,s,n);return e.jsx("span",{className:a,title:i??t,children:r===t?t:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"sr-only",children:t}),e.jsx("span",{"aria-hidden":"true",children:r})]})})}function js({rows:t,getSearchText:s,pageSize:n=et}){const[a,i]=o.useState(""),[r,l]=o.useState(1),u=o.useMemo(()=>Bl(a),[a]),x=o.useMemo(()=>u.length===0||!s?t:t.filter(w=>{const g=s(w).toLocaleLowerCase();return u.every(D=>g.includes(D))}),[s,t,u]),m=Math.max(1,Math.ceil(x.length/n)),f=Math.min(Math.max(1,r),m),d=(f-1)*n,b=o.useMemo(()=>x.slice(d,d+n),[x,n,d]),A=o.useCallback(w=>{i(w),l(1)},[]),$=o.useCallback(w=>{l(Math.max(1,w))},[]);return{query:a,setQuery:A,page:f,setPage:$,rows:b,filteredRows:x,totalRows:x.length,totalPages:m,pageSize:n,rangeStart:x.length===0?0:d+1,rangeEnd:d+b.length,hasQuery:a.trim().length>0}}function Qt({value:t,onChange:s,label:n,placeholder:a="Filter rows",className:i}){return e.jsxs("div",{className:`relative ${i??""}`,children:[e.jsx(ar,{"aria-hidden":"true",className:"pointer-events-none absolute left-3 top-1/2 size-3.5 -translate-y-1/2 text-muted"}),e.jsx("input",{type:"search",value:t,onChange:r=>s(r.target.value),"aria-label":n,placeholder:a,autoComplete:"off",spellCheck:!1,className:"h-9 w-full rounded-md border border-default bg-surface/50 pl-9 pr-9 text-sm text-strong placeholder:text-muted outline-none transition focus:border-mono-500 focus:ring-1 focus:ring-mono-500 [&::-webkit-search-cancel-button]:appearance-none"}),t.trim().length>0?e.jsx("button",{type:"button",onClick:()=>s(""),"aria-label":`Clear ${n.toLocaleLowerCase()}`,className:"absolute right-2 top-1/2 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded text-muted transition-colors hover:bg-surface-hover hover:text-strong focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",children:e.jsx(ir,{"aria-hidden":"true",className:"size-3.5"})}):null]})}function Tt({page:t,pageSize:s=et,visibleRows:n,totalRows:a,hasNextPage:i,onPageChange:r,itemLabel:l="rows",className:u,disabled:x=!1}){if(n===0)return null;const m=(t-1)*s+1,f=m+n-1,d=a===void 0?void 0:Math.max(1,Math.ceil(a/s)),b=i??(d!==void 0&&t<d),A=t>1||b;return e.jsxs("div",{className:`mt-3 flex flex-wrap items-center justify-between gap-x-4 gap-y-2 text-xs text-secondary ${u??""}`,children:[e.jsxs("p",{className:"tabular-nums",children:[m.toLocaleString("en-US"),"–",f.toLocaleString("en-US"),a===void 0?`${b?"+":""} ${l}`:` of ${a.toLocaleString("en-US")} ${l}`]}),A?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>r(t-1),disabled:x||t<=1,className:"inline-flex items-center gap-1 rounded-md border border-base bg-bg px-2.5 py-1.5 text-strong transition hover:border-strong hover:text-primary disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-base disabled:hover:text-strong",children:[e.jsx(pl,{"aria-hidden":"true",className:"size-3.5"}),"Previous"]}),e.jsx("span",{className:"tabular-nums",children:d===void 0?`Page ${t}`:`Page ${t} of ${d}`}),e.jsxs("button",{type:"button",onClick:()=>r(t+1),disabled:x||!b,className:"inline-flex items-center gap-1 rounded-md border border-base bg-bg px-2.5 py-1.5 text-strong transition hover:border-strong hover:text-primary disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-base disabled:hover:text-strong",children:["Next",e.jsx(qn,{"aria-hidden":"true",className:"size-3.5"})]})]}):null]})}function va({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={cited:"rounded-full","not-cited":"rounded-sm",lost:"rotate-45 rounded-[1px]",emerging:"rounded-full"},r=n.length-1,l=new Date(n[0].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),u=new Date(n[r].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),x=n.map((m,f)=>{const d=new Date(m.createdAt).toLocaleDateString();return`${f===r?"Latest run, ":""}${d}: ${m.citationState}${m.model?`, model ${m.model}`:""}`}).join("; ");return e.jsxs("div",{className:"flex items-center gap-1",role:"img","aria-label":`Citation history across ${n.length} runs. ${x}`,children:[e.jsx("span",{className:"text-[9px] text-faint shrink-0","aria-hidden":"true",children:l}),e.jsx("div",{className:"flex items-center gap-[3px]",title:`${n.length} runs`,"aria-hidden":"true",children:n.map((m,f)=>{const d=!!(m.model&&f>0&&n[f-1]?.model&&n[f-1].model!==m.model),b=f===r;return e.jsx("span",{className:`h-2.5 w-2.5 ${i[m.citationState]??"rounded-sm"} ${a[m.citationState]??"bg-mono-700"} ${d?"ring-1 ring-caution-300/80 ring-offset-1 ring-offset-bg":""} ${b?"outline outline-1 outline-offset-2 outline-mono-400":""}`,title:[m.citationState,new Date(m.createdAt).toLocaleDateString(),m.model?`model ${m.model}`:null,d?"model changed":null,b?"latest run":null].filter(Boolean).join(" · ")},`${m.runId}:${m.createdAt}`)})}),e.jsxs("span",{className:"text-[9px] shrink-0 text-secondary","aria-hidden":"true",children:[u," ",e.jsx("span",{className:"text-faint",children:"latest"})]})]})}function Tn(t){const s=new Map;for(const a of t)for(const i of a.runHistory){const r=s.get(i.createdAt);r?r.states.push(i.citationState):s.set(i.createdAt,{states:[i.citationState],runId:i.runId})}return[...s.entries()].sort(([a],[i])=>a.localeCompare(i)).map(([a,{states:i,runId:r}])=>({runId:r,createdAt:a,citationState:i.includes("cited")?"cited":i.includes("emerging")?"emerging":"not-cited"}))}const Ql=320;function zl(t){return[t.phrase,t.location??"",...t.rawItems.map(s=>s.provider)].join(" ")}function Na(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 wa(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 Sa(t,s){const n=s==="mentions"?"mentioned":"cited",a=s==="mentions"?"Mentioned":"Cited";if(t.length===0)return"Awaiting first run";if(t.length===1)return"First observation";const i=t[t.length-1].citationState,r=t[t.length-2].citationState;if(r!=="cited"&&i==="cited")return`Newly ${n}`;if(r==="cited"&&i!=="cited")return"Lost since last run";let l=0;for(let u=t.length-1;u>=0&&t[u].citationState===i;u--)l++;return i==="cited"?l<=1?`${a} in latest run`:`${a} for ${l} runs`:l<=1?`Not ${n} in latest run`:`Not ${n} across ${l} runs`}function Hl(t,s){return t.map(n=>ji(n,s))}function ji(t,s){return s==="citations"?t:{...t,citationState:Na(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:Na(n,s)}))}}function Ca(t,s){const n=s==="mentions"?"mention":"citation",a=s==="mentions"?"Mention":"Citation";if(t.length===0)return{key:s,label:`${a} pending`,tone:"pending"};const i=t[t.length-1].citationState,r=t.length>=2?t[t.length-2].citationState:null,l=i==="cited"||i==="emerging",u=r==="cited"||r==="emerging";return i==="lost"||r!==null&&u&&!l?{key:s,label:`Lost ${n}`,tone:"negative"}:i==="emerging"||r!==null&&!u&&l?{key:s,label:`New ${n}`,tone:"positive"}:r===null&&l?{key:s,label:`First ${n}`,tone:"positive"}:l?{key:s,label:s==="mentions"?"Still mentioned":"Still cited",tone:"neutral"}:{key:s,label:`No ${n}`,tone:"neutral"}}function Kl(t){const s=Tn(Hl(t,"mentions")),n=Tn(t);return[Ca(s,"mentions"),Ca(n,"citations")]}function Vl({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 ka({items:t}){return e.jsx("div",{className:"mt-1 flex flex-wrap gap-1","aria-label":"Latest run mention and citation signals",children:Kl(t).map(s=>e.jsx(Vl,{signal:s},s.key))})}function Wl({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:a}=Wa(),[i,r]=o.useState(new Set),[l,u]=o.useState("mentions"),[x,m]=o.useState(n),f=o.useMemo(()=>{const F=new Map;for(const T of t){const q=T.query,h=s?T.location??null:null,k=s?JSON.stringify([q,h]):q,E=F.get(k)??{key:k,phrase:q,location:h,items:[],rawItems:[]};E.items.push(ji(T,l)),E.rawItems.push(T),F.set(k,E)}return[...F.values()]},[t,l,s]),d=js({rows:f,getSearchText:zl}),b=d.rows.map(F=>F.key),A=b.length>0&&b.every(F=>i.has(F)),$=F=>{r(T=>{const q=new Set(T);return q.has(F)?q.delete(F):q.add(F),q})},w=l==="mentions"?"mentioned":"cited",g=l==="mentions"?"Mention History":"Citation History",D=l==="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":l==="mentions",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${l==="mentions"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>u("mentions"),children:"Mentions"}),e.jsx("button",{type:"button",role:"tab","aria-selected":l==="citations",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${l==="citations"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>u("citations"),children:"Citations"})]}),e.jsx("span",{className:"text-[11px] text-muted",children:l==="mentions"?"Brand or domain in answer text":"Brand or domain in source links"}),e.jsxs("div",{className:"ml-auto flex items-center gap-3",children:[e.jsx("button",{type:"button",className:"text-[11px] text-secondary hover:text-strong",onClick:()=>{r(F=>{const T=new Set(F);for(const q of b)A?T.delete(q):T.add(q);return T})},children:A?"Collapse page":"Expand page"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Density"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-bg-elevated/60 border border-subtle",role:"tablist","aria-label":"Evidence row density",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":x==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${x==="compact"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>m("compact"),children:"Compact"}),e.jsx("button",{type:"button",role:"tab","aria-selected":x==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${x==="detailed"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>m("detailed"),children:"Detailed"})]})]})]})]}),f.length>0?e.jsx(Qt,{value:d.query,onChange:d.setQuery,label:"Filter tracked queries",placeholder:"Filter query, location, or provider",className:"mb-3 max-w-md"}):null,e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{style:{width:"2rem"}}),e.jsx("th",{scope:"col",children:"Query"}),e.jsx("th",{scope:"col",children:"Status"}),e.jsx("th",{scope:"col",children:g}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:d.rows.map(({key:F,phrase:T,location:q,items:h,rawItems:k})=>{const E=i.has(F),X=h.map(y=>y.citationState),le=X.includes("cited")?"cited":X.includes("emerging")?"emerging":X.includes("lost")?"lost":X.every(y=>y==="pending")?"pending":"not-cited",S=Tn(h),p=h.filter(y=>y.citationState===rr.cited||y.citationState==="emerging").length,_=Sa(S,l);return e.jsxs(o.Fragment,{children:[e.jsxs("tr",{className:"cursor-pointer hover:bg-mono-800/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>$(F),onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),$(F))},tabIndex:0,role:"button","aria-expanded":E,children:[e.jsx("td",{children:e.jsx(qn,{size:14,className:`transition-transform duration-150 text-muted ${E?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-heading",children:T}),s&&e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-muted",children:q??"No location"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:h.map(y=>e.jsx(Kt,{provider:y.provider},y.id))})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(In,{state:le,label:wa(le,l)}),e.jsxs("span",{className:"text-[11px] text-muted",title:`${p} of ${h.length} engines ${D}`,children:[p,"/",h.length]})]})}),e.jsx("td",{children:e.jsx(va,{history:S})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:_}),e.jsx(ka,{items:k})]}),e.jsx("td",{})]}),E&&h.map((y,G)=>e.jsxs(o.Fragment,{children:[e.jsxs("tr",{className:"bg-surface",children:[e.jsx("td",{}),e.jsx("td",{className:"evidence-query-cell pl-5",children:e.jsx(Kt,{provider:y.provider})}),e.jsx("td",{children:e.jsx(In,{state:y.citationState,label:wa(y.citationState,l)})}),e.jsx("td",{children:e.jsx(va,{history:y.runHistory})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:Sa(y.runHistory,l)}),e.jsx(ka,{items:[k[G]??y]})]}),e.jsx("td",{children:e.jsx(I,{variant:"ghost",size:"sm",type:"button",onClick:re=>{re.stopPropagation(),a(y.id)},children:"View"})})]}),x==="detailed"&&e.jsxs("tr",{className:"bg-surface-subtle",children:[e.jsx("td",{}),e.jsx("td",{colSpan:5,className:"px-5 pb-4",children:e.jsx(Xl,{item:y,onViewFull:()=>a(y.id)})})]})]},y.id))]},F)})})]})}),d.totalRows===0&&d.hasQuery?e.jsx("p",{className:"supporting-copy mt-3",children:"No tracked queries match this filter."}):null,e.jsx(Tt,{page:d.page,pageSize:d.pageSize,visibleRows:d.rows.length,totalRows:d.totalRows,onPageChange:d.setPage,itemLabel:d.hasQuery?"matches":"queries"}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",w==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function Yl(t){const s=(t.matchedTerms??[]).filter(i=>i.trim().length>2),n=[...t.competitorDomains.flatMap(i=>{const r=lr(i);return r.length>=4?[r]:[]}),...t.recommendedCompetitors??[]].filter(i=>i.trim().length>2),a=[];return s.length>0&&a.push({terms:s,className:"answer-highlight-brand"}),n.length>0&&a.push({terms:n,className:"answer-highlight-competitor"}),a}function Jl(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 Xl({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}=Jl(t.answerSnippet,Ql),r=Yl(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:or(a,r)}),(t.citedDomains.length>0||t.competitorDomains.length>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[t.citedDomains.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Cited:"}),t.citedDomains.slice(0,6).map(l=>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:l},`c-${l}`)),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(l=>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:l},`co-${l}`)),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:l=>{l.stopPropagation(),s()},children:"View full answer →"})]})}function Zl({competitors:t,onSelectCompetitor:s,onRemoveCompetitor:n,activeFilter:a}){if(t.length===0)return e.jsx("p",{className:"text-sm text-muted",children:"No competitors configured. Add competitors to track overlap."});const i=s!=null,r=n!=null;return e.jsx("div",{className:"competitor-table-wrap",children:e.jsxs("table",{className:"competitor-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Domain"}),e.jsx("th",{children:"Pressure"}),e.jsx("th",{children:"Citations"}),e.jsx("th",{children:"Queries"}),r&&e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{children:t.map(l=>{const u=a!=null&&a.toLowerCase()===l.domain.toLowerCase(),x=[i?"cursor-pointer hover:bg-mono-800/30 transition-colors":"",u?"bg-negative-950/20":""].filter(Boolean).join(" ");return e.jsxs("tr",{className:x,onClick:i?()=>s(l.domain):void 0,title:i?`Filter answers to queries where ${l.domain} surfaced`:void 0,children:[e.jsx("td",{className:"font-medium text-heading",children:l.domain}),e.jsx("td",{children:e.jsx(te,{tone:cr(l.pressureLabel),children:l.pressureLabel})}),e.jsx("td",{className:"text-neutral tabular-nums",children:l.totalQueries>0?`${l.citationCount} / ${l.totalQueries}`:"—"}),e.jsx("td",{className:"text-muted text-xs",children:l.citedQueries.length>0?l.citedQueries.join(", "):"Not cited"}),r&&e.jsx("td",{className:"text-right",children:e.jsx("button",{type:"button",className:"rounded px-1.5 py-0.5 text-xs text-muted transition-colors hover:text-negative-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-negative-500","aria-label":`Remove competitor ${l.domain}`,title:`Remove ${l.domain}`,onClick:m=>{m.stopPropagation(),n(l.domain)},children:"Remove"})})]},l.id)})})]})})}function _s({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 ec=6,es="__other__",zt="_socialTotal";function tc(t,s=ec){const n=new Map;for(const f of t)n.set(f.source,(n.get(f.source)??0)+f.sessions);const a=[...n.entries()].sort((f,d)=>d[1]!==f[1]?d[1]-f[1]:f[0].localeCompare(d[0])),i=a.slice(0,s),r=new Set(i.map(([f])=>f)),l=Math.max(0,a.length-s),u=new Map;for(const f of t){let d=u.get(f.date);d||(d={date:f.date,[zt]:0},u.set(f.date,d));const b=r.has(f.source)?f.source:es;d[b]=(d[b]??0)+f.sessions,d[zt]=(d[zt]??0)+f.sessions}const x=[...u.values()].sort((f,d)=>String(f.date).localeCompare(String(d.date))),m=i.map(([f])=>f);return l>0&&m.push(es),{data:x,sources:m,otherCount:l}}function Ht(t){return t.replace(/\+/g," ")}function yi(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const Aa="_totalSessions",$a="_organicSessions";function sc(t,s){const n=new Map;for(const l of s)n.set(l.date,{[Aa]:l.sessions,[$a]:l.organicSessions});for(const l of t.days){let u=n.get(l.date);u||(u={[Aa]:0,[$a]:0},n.set(l.date,u));for(const x of l.bySource)u[x.source]=(u[x.source]??0)+x.sessions}const a=[...n.entries()].sort(([l],[u])=>l.localeCompare(u)).map(([l,u])=>({date:l,...u})),i=a.map(l=>l.date),r=i.length>0?{start:i[0],end:i[i.length-1]}:null;return{data:a,sources:t.sources,dateRange:r}}const nc=["7d","30d","90d","all"],wt=Fe,Mn=_e.textDim,vi=_e.textFaint,ds=25;function ac(t){return bi(t.landingPage)}const ic=25,pn={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0};function qs(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function Ni(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 rc({projectName:t}){const{data:s,isLoading:n,isError:a}=fl(t);if(n)return e.jsx(Y,{className:"p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading server activity…"})});if(a)return e.jsx(Y,{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:"Server activity"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["Crawler, AI fetch, and referral activity from connected sources."," ",!Q()&&e.jsx(xt,{to:"/traffic",className:"text-link hover:underline",children:"Manage sources →"})]})]})}),i.length===0?e.jsx(Y,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-secondary",children:["No server traffic source connected yet."," ",!Q()&&e.jsxs(e.Fragment,{children:[e.jsx(xt,{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(Y,{className:"overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-bg-elevated/50 text-[10px] uppercase tracking-wide text-muted",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Source"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Status"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Crawler hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI sessions 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Last sync"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium","aria-label":"open"})]})}),e.jsx("tbody",{children:i.map(r=>e.jsxs("tr",{className:"border-t border-default",children:[e.jsx("td",{className:"px-4 py-3 text-heading",children:r.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(te,{tone:bl(r.status),children:r.status})}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:r.totals24h.crawlerHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:r.totals24h.aiUserFetchHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:r.totals24h.aiReferralHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right text-secondary text-xs",children:r.lastSyncedAt?Ni(r.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:Q()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(xt,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:r.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},r.id))})]})})]})}function oc({projectName:t}){return e.jsxs("div",{className:"space-y-10",children:[e.jsx(rc,{projectName:t}),e.jsx(lc,{projectName:t})]})}function lc({projectName:t}){const s=kt(),[n,a]=o.useState(null),[i,r]=o.useState(null),[l,u]=o.useState(!0),[x,m]=o.useState(!1),[f,d]=o.useState(!1),[b,A]=o.useState(null),[$,w]=o.useState(null),[g,D]=o.useState("sessions"),[F,T]=o.useState("desc"),[q,h]=o.useState("sessions"),[k,E]=o.useState("desc"),[X,le]=o.useState("sessions"),[S,p]=o.useState("desc"),[_,y]=o.useState("sessions"),[G,re]=o.useState("desc"),[J,U]=o.useState(pn),[oe,ae]=o.useState([]),[O,M]=o.useState([]),[j,Z]=o.useState(!1),[ie,v]=o.useState("30d");async function z(L){u(!0),A(null);try{const pe=await s.fetchQuery({...dr({client:V,path:{name:t}}),staleTime:cs});if(L.current)return;if(a(pe),!pe.connected){r(null),U(pn),ae([]),M([]),u(!1);return}const ne=ie==="all"?void 0:ie,[ue,Pe,tn,Ye]=await Promise.all([s.fetchQuery({...ur({client:V,path:{name:t},query:ne?{window:ne}:void 0}),staleTime:cs}).then(sn=>sn),s.fetchQuery({...mr({client:V,path:{name:t},query:ne?{window:ne}:void 0}),staleTime:cs}).catch(()=>pn),s.fetchQuery({...xr({client:V,path:{name:t},query:ne?{window:ne}:void 0}),staleTime:cs}).catch(()=>[]),s.fetchQuery({...hr({client:V,path:{name:t},query:ne?{window:ne}:void 0}),staleTime:cs}).catch(()=>[])]);if(L.current)return;r(ue),U(Pe),ae(tn),M(Ye),u(!1)}catch(pe){if(L.current)return;A(pe instanceof Error?pe.message:"Failed to load GA4 data"),u(!1)}}o.useEffect(()=>{const L={current:!1};return z(L),()=>{L.current=!0}},[t,ie,s]);async function K(){m(!0),A(null),w(null);try{const L=await Ya(t);w(`Synced ${L.rowCount.toLocaleString()} page rows, ${L.aiReferralCount.toLocaleString()} AI and ${L.socialReferralCount.toLocaleString()} social referral rows (${L.days} days)`),await De(s,"ga"),await z({current:!1})}catch(L){A(L instanceof Error?L.message:"Sync failed")}finally{m(!1)}}async function P(){d(!0),A(null),w(null);try{await pr(t),await De(s,"ga"),a({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),r(null),w("GA4 disconnected")}catch(L){A(L instanceof Error?L.message:"Disconnect failed")}finally{d(!1)}}function ee(L){g===L?T(pe=>pe==="desc"?"asc":"desc"):(D(L),T("desc"))}function fe(L){q===L?E(pe=>pe==="desc"?"asc":"desc"):(h(L),E("desc"))}function Ce(L){X===L?p(pe=>pe==="desc"?"asc":"desc"):(le(L),p("desc"))}const qe=o.useMemo(()=>i?.topPages?[...i.topPages].sort((L,pe)=>{const ne=L[g],ue=pe[g];return typeof ne=="string"&&typeof ue=="string"?F==="asc"?ne.localeCompare(ue):ue.localeCompare(ne):F==="asc"?ne-ue:ue-ne}):[],[i?.topPages,g,F]),Ge=o.useMemo(()=>i?.aiReferrals?[...i.aiReferrals].sort((L,pe)=>{const ne=L[q],ue=pe[q];return typeof ne=="string"&&typeof ue=="string"?k==="asc"?ne.localeCompare(ue):ue.localeCompare(ne):k==="asc"?ne-ue:ue-ne}):[],[i?.aiReferrals,q,k]),gt=o.useMemo(()=>i?.aiReferralLandingPages?[...i.aiReferralLandingPages].sort((L,pe)=>{const ne=L[_],ue=pe[_];return typeof ne=="string"&&typeof ue=="string"?G==="asc"?ne.localeCompare(ue):ue.localeCompare(ne):G==="asc"?ne-ue:ue-ne}):[],[i?.aiReferralLandingPages,_,G]),Ne=js({rows:gt,getSearchText:ac,pageSize:ic}),ft=Ne.totalRows>0?`${Ne.totalRows.toLocaleString()} ${Ne.hasQuery?Ne.totalRows===1?"match":"matches":Ne.totalRows===1?"row":"rows"}`:Ne.hasQuery&&(i?.aiReferralLandingPages.length??0)>0?"0 matches":"No landing-page rows";function We(L){Ne.setPage(1),_===L?re(pe=>pe==="desc"?"asc":"desc"):(y(L),re("desc"))}const Me=o.useMemo(()=>i?.socialReferrals?[...i.socialReferrals].sort((L,pe)=>{const ne=L[X],ue=pe[X];return typeof ne=="string"&&typeof ue=="string"?S==="asc"?ne.localeCompare(ue):ue.localeCompare(ne):S==="asc"?ne-ue:ue-ne}):[],[i?.socialReferrals,X,S]),{socialChartData:W,socialChartSources:be,socialOtherCount:Le}=o.useMemo(()=>{const L=tc(O);return{socialChartData:L.data,socialChartSources:L.sources,socialOtherCount:L.otherCount}},[O]),{chartData:at,chartSources:R,dateRange:we}=o.useMemo(()=>{const L=sc(J,oe);return{chartData:L.data,chartSources:L.sources,dateRange:L.dateRange}},[J,oe]);if(l&&!n)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!n?.connected)return Q()?e.jsx(Y,{className:"p-5",children:e.jsx("div",{className:"text-sm text-secondary",children:"No Google Analytics 4 property connected yet."})}):e.jsx(cc,{projectName:t,onConnected:()=>{(async()=>(await De(s,"ga"),await z({current:!1})))()}});const ke=i?.organicSharePctDisplay??"0%",bt=i?.channelBreakdown?.organic.sharePctDisplay??ke,N=i?.channelBreakdown?.organic.sessions??i?.totalOrganicSessions??0,ce=i?.aiSessionsDeduped??0,de=i?.channelBreakdown?.ai.sessions??i?.aiSessionsBySession??0,it=i?.channelBreakdown?.ai.sharePctDisplay??i?.aiSharePctBySessionDisplay??"0%",Ie=i?.paidAiSessionsBySession??0,Cs=i?.paidAiSharePctBySessionDisplay??"0%",Et=i?new Set(i.aiReferrals.map(L=>L.source.toLowerCase())).size:0,jt=Ge[0]??null,Zs=i?.totalDirectSessions??0,ks=i?.directSharePctDisplay??"0%",As=i?.channelBreakdown?.direct.sessions??Zs,en=i?.channelBreakdown?.direct.sharePctDisplay??ks,ss=i?.channelBreakdown?.other.sessions??i?.otherSessions??0,ns=i?.channelBreakdown?.other.sharePctDisplay??i?.otherSharePctDisplay??"0%",rt=i?.socialSessions??0,as=i?.socialSharePctDisplay??"0%",$s=i?.channelBreakdown?.social.sessions??rt,Ps=i?.channelBreakdown?.social.sharePctDisplay??as,ot=i?new Set(i.socialReferrals.map(L=>L.source.toLowerCase())).size:0,ze=Me[0]??null;return e.jsxs(e.Fragment,{children:[b&&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:b}),$&&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:$}),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})]})]})]}),!Q()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(I,{variant:"outline",size:"sm",disabled:x,onClick:he(K),children:[e.jsx(bs,{className:`w-3.5 h-3.5 mr-1.5 ${x?"animate-spin":""}`}),x?"Syncing…":"Sync"]}),e.jsxs(I,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:f,onClick:he(P),children:[e.jsx(Dl,{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($e,{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:"segmented",role:"group","aria-label":"Traffic time period",children:nc.map(L=>e.jsx("button",{type:"button","aria-pressed":ie===L,className:`segmented-option ${ie===L?"segmented-option-active":""}`,onClick:()=>v(L),children:L==="all"?"All":L},L))})]}),i?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(gn,{value:qs(i.totalSessions),label:"Total Sessions",subtitle:i.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(gn,{value:qs(i.totalOrganicSessions),label:"Organic Sessions",subtitle:`${ke} of total`,tone:"positive"}),e.jsx(gn,{value:qs(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."}),!Q()&&e.jsxs(I,{variant:"outline",size:"sm",disabled:x,onClick:he(K),children:[e.jsx(bs,{className:`w-3.5 h-3.5 mr-1.5 ${x?"animate-spin":""}`}),"Sync from GA4"]})]})]}),i&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Traffic Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Traffic by channel",e.jsx($e,{text:"Decomposes GA4 sessions into five disjoint channels — known AI referrers first, then organic search, social, direct, and other channels. Known AI includes paid and organic AI referrals; paid rows are labeled in the source table below. Known AI referrers are removed from their native GA4 channel before the residual Other bucket is computed."})]})]}),we&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(we.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(we.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),at.length>0&&e.jsxs(Y,{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:R.length>0?"AI vs. total sessions":"All sessions (baseline)"}),R.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),R.length===0&&e.jsx("p",{className:"text-xs text-muted",children:"No AI referrals detected yet"})]}),e.jsx("div",{className:"h-64",children:e.jsx(Wt,{width:"100%",height:"100%",children:e.jsxs(Yt,{data:at,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Jt,{dataKey:"date",tick:Ve,tickLine:!1,axisLine:{stroke:pt},tickFormatter:Dn}),e.jsx(Xt,{tick:Ve,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Zt,{...It,labelFormatter:Ws,formatter:(L,pe)=>{const ne=typeof L=="number"?L.toLocaleString():String(L??0),ue=String(pe??"");return ue==="_totalSessions"?[ne,"Total Sessions"]:ue==="_organicSessions"?[ne,"Organic Sessions"]:[ne,ue]}}),e.jsx(di,{wrapperStyle:{fontSize:11,color:_e.text},formatter:L=>L==="_totalSessions"?"Total Sessions":L==="_organicSessions"?"Organic Sessions":L}),e.jsx(Bt,{type:"monotone",dataKey:"_totalSessions",stroke:_e.textFaint,fill:_e.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),R.map((L,pe)=>e.jsx(Bt,{type:"monotone",dataKey:L,stackId:"ai",stroke:wt[pe%wt.length],fill:wt[pe%wt.length],fillOpacity:.4,strokeWidth:1.5},L))]})})})]}),e.jsxs(Y,{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:bt,hint:`${N.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:Ps,hint:`${$s.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:en,hint:`${As.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:it,hint:Ie>0?`${de.toLocaleString()} sessions · ${Ie.toLocaleString()} paid`:`${de.toLocaleString()} sessions`,tone:"positive",tooltip:"Sessions whose current sessionSource matched a known AI engine (e.g. chatgpt.com, claude.ai, gemini.google.com). Paid AI is inferred from paid/cpc/sponsored UTM values or GA4 paid channel groups. Untagged ad clicks with no referrer still fall under Direct because GA4 has no paid evidence for them."}),e.jsx(Ze,{label:"Other channels",value:ns,hint:`${ss.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."})]}),jt&&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:jt.source})," via ",jt.medium,", accounting for ",jt.sessions.toLocaleString()," sessions.",Ie>0&&e.jsxs("span",{children:[" Paid AI: ",Ie.toLocaleString()," sessions (",Cs,")."]})]})]}),e.jsxs(Y,{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?`${Et} unique sources, ${i.aiReferrals.length} rows`:"No source rows"})]}),i.aiReferrals.length>0?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(Qe,{label:"Source",sortKey:"source",current:q,dir:k,onSort:fe,align:"left"}),e.jsx(Qe,{label:"Medium",sortKey:"medium",current:q,dir:k,onSort:fe,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Class"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(Qe,{label:"Sessions",sortKey:"sessions",current:q,dir:k,onSort:fe,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:Ge.map(L=>e.jsx(uc,{referral:L,totalSessions:ce},`${L.source}:${L.medium}:${L.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(Y,{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:ft})]}),i.aiReferralLandingPages.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Qt,{value:Ne.query,onChange:Ne.setQuery,label:"Filter landing page URLs or query parameters",placeholder:"Filter URL or query parameters",className:"mb-4 max-w-md"}),Ne.totalRows>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(Qe,{label:"Landing Page",sortKey:"landingPage",current:_,dir:G,onSort:We,align:"left"}),e.jsx(Qe,{label:"Source",sortKey:"source",current:_,dir:G,onSort:We,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(Qe,{label:"Sessions",sortKey:"sessions",current:_,dir:G,onSort:We,align:"right"})]})}),e.jsx("tbody",{children:Ne.rows.map(L=>e.jsx(mc,{row:L},`${L.landingPage}:${L.source}:${L.medium}:${L.sourceDimension}`))})]})}),e.jsx(Tt,{page:Ne.page,pageSize:Ne.pageSize,visibleRows:Ne.rows.length,totalRows:Ne.totalRows,onPageChange:Ne.setPage,itemLabel:Ne.hasQuery?"matches":"rows"})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary",children:"No landing pages match this filter"}),e.jsx("button",{type:"button",onClick:()=>Ne.setQuery(""),className:"mt-2 text-xs text-link hover:underline focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",children:"Clear filter"})]})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No AI landing pages detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"Known-AI landing pages appear after a GA4 sync records visits from AI referrers."})]})]})]})]}),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($e,{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."})]})]}),W.length>0&&e.jsxs(Y,{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"})]}),Le>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",be.length-1," sources · ",Le," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(Wt,{width:"100%",height:"100%",children:e.jsxs(Yt,{data:W,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Jt,{dataKey:"date",tick:Ve,tickLine:!1,axisLine:{stroke:pt},tickFormatter:Dn}),e.jsx(Xt,{tick:Ve,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Zt,{...It,labelFormatter:Ws,formatter:(L,pe)=>{const ne=typeof L=="number"?L.toLocaleString():String(L??0),ue=String(pe??"");if(ue===zt)return[ne,"Total Social"];if(ue===es){const Pe=`Other (${Le} source${Le===1?"":"s"})`;return[ne,Pe]}return[ne,Ht(ue)]}}),e.jsx(Bt,{type:"monotone",dataKey:zt,stroke:vi,fill:_e.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),be.map((L,pe)=>{const ue=L===es?Mn:wt[pe%wt.length];return e.jsx(Bt,{type:"monotone",dataKey:L,stackId:"social",stroke:ue,fill:ue,fillOpacity:.4,strokeWidth:1.5},L)})]})})}),e.jsx(hc,{sources:be,otherCount:Le})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.5fr)]",children:[e.jsxs(Y,{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:qs(rt),hint:`${rt.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:as,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(ot),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."})]}),ze&&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:`${ze.source} via ${ze.medium}`,children:yi(Ht(ze.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:ze.medium,children:["via ",Ht(ze.medium)," · ",ze.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(Y,{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?Me.length>ds&&!j?`Top ${ds} of ${Me.length}`:`${Me.length} rows`:"No source rows"})]}),i.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm table-fixed",children:[e.jsxs("colgroup",{children:[e.jsx("col",{className:"w-[32%]"}),e.jsx("col",{className:"w-[22%]"}),e.jsx("col",{className:"w-[12%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[12%]"})]}),e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(Qe,{label:"Source",sortKey:"source",current:X,dir:S,onSort:Ce,align:"left"}),e.jsx(Qe,{label:"Medium",sortKey:"medium",current:X,dir:S,onSort:Ce,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(Qe,{label:"Sessions",sortKey:"sessions",current:X,dir:S,onSort:Ce,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(Qe,{label:"Users",sortKey:"users",current:X,dir:S,onSort:Ce,align:"right"})]})}),e.jsx("tbody",{children:(j?Me:Me.slice(0,ds)).map(L=>e.jsx(xc,{referral:L,totalSessions:rt},`${L.source}:${L.medium}:${L.channelGroup}`))})]})}),Me.length>ds&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>Z(L=>!L),className:"rounded-md border border-base px-3 py-1.5 text-xs text-secondary transition-colors hover:border-strong hover:text-strong",children:j?`Show top ${ds}`:`Show all ${Me.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($e,{text:"Landing pages ranked by session volume. Click column headers to sort. Organic % shows the share of sessions coming from Google organic search."})]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(Qe,{label:"Landing Page",sortKey:"landingPage",current:g,dir:F,onSort:ee,align:"left"}),e.jsx(Qe,{label:"Sessions",sortKey:"sessions",current:g,dir:F,onSort:ee,align:"right"}),e.jsx(Qe,{label:"Organic",sortKey:"organicSessions",current:g,dir:F,onSort:ee,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"})]})}),e.jsx("tbody",{children:qe.map(L=>e.jsx(dc,{page:L},L.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 ${Ni(i.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:i?`${i.topPages.length} pages · ${i.aiReferrals.length} AI rows · ${i.socialReferrals.length} social rows`:""})]})]})}function cc({projectName:t,onConnected:s}){const[n,a]=o.useState(""),[i,r]=o.useState(null),[l,u]=o.useState(null),[x,m]=o.useState(!1),[f,d]=o.useState(null),b=o.useRef(null),A=o.useCallback(w=>{const g=w.target.files?.[0];if(!g)return;d(null),r(g.name);const D=new FileReader;D.onload=()=>{const F=D.result;try{const T=JSON.parse(F);if(!T.client_email||!T.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)."),u(null);return}u(F)}catch{d("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),u(null)}},D.onerror=()=>{d("Failed to read file."),u(null)},D.readAsText(g)},[]);async function $(){if(d(null),!n.trim()){d("Property ID is required.");return}if(!l){d("Please upload a service account key file.");return}m(!0);try{await gr(t,{propertyId:n.trim(),keyJson:l});try{await Ya(t)}catch{}s()}catch(w){d(w instanceof Error?w.message:"Failed to connect GA4")}finally{m(!1)}}return e.jsxs(Y,{className:"surface-card p-6",children:[e.jsx("h3",{className:"text-base font-semibold text-primary mb-1",children:"Connect Google Analytics 4"}),e.jsx("p",{className:"text-sm text-secondary mb-5",children:"Connect a GA4 property to see traffic data for this project. You'll need a service account key file from Google Cloud Console."}),f&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative",children:f}),e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{htmlFor:"ga4-property-id",className:"block text-xs font-medium text-secondary mb-1.5",children:"GA4 Property ID"}),e.jsx("input",{id:"ga4-property-id",type:"text",placeholder:"e.g. 123456789",value:n,onChange:w=>a(w.target.value),className:"w-full rounded-lg bg-bg-elevated/60 border border-default px-3 py-2 text-sm text-strong placeholder-mono-600 focus:outline-none focus:ring-1 focus:ring-mono-600"}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:"Find this in GA4 → Admin → Property Settings. It's a numeric ID, not the Measurement ID (G-XXXXXX)."})]}),e.jsxs("div",{className:"mb-5",children:[e.jsx("label",{className:"block text-xs font-medium text-secondary mb-1.5",children:"Service Account Key File"}),e.jsx("input",{ref:b,type:"file",accept:".json,application/json",onChange:A,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>b.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(Tl,{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(I,{variant:"default",size:"sm",disabled:x||!n.trim()||!l,onClick:he($),children:x?"Connecting & syncing…":"Connect GA4"})]})}function Qe({label:t,sortKey:s,current:n,dir:a,onSort:i,align:r}){const l=n===s;return e.jsx("th",{className:`py-1 ${r==="right"?"text-right":"text-left"}`,children:e.jsxs("button",{type:"button",className:"font-medium cursor-pointer select-none hover:text-neutral transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-400 rounded",onClick:()=>i(s),"aria-label":`Sort by ${t}${l?` (currently ${a==="asc"?"ascending":"descending"})`:""}`,children:[t,l&&e.jsx("span",{className:"ml-0.5",children:a==="asc"?"↑":"↓"})]})})}const wi={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function gn({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 ${wi[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($e,{text:i})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${wi[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function dc({page:t}){const s=t.sessions>0?(t.organicSessions/t.sessions*100).toFixed(1):"0.0";return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 text-neutral max-w-[400px] truncate",title:t.landingPage,children:t.landingPage}),e.jsx("td",{className:"py-1.5 text-right text-strong tabular-nums",children:t.sessions.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.organicSessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[s,"%"]})]})}const Si={session:"Session",first_user:"First Visit",manual_utm:"UTM"},Ci={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 uc({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=Si[t.sourceDimension]??t.sourceDimension,i=Ci[t.sourceDimension]??"",r=t.trafficClass==="paid"?"Paid":"Organic",l=t.trafficClass==="paid"?"Paid AI traffic inferred from paid/cpc/sponsored UTM values or a GA4 paid channel group":"AI traffic without a paid attribution signal";return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 text-strong max-w-[220px] truncate",title:t.source,children:t.source}),e.jsx("td",{className:"py-1.5 text-muted max-w-[180px] truncate",title:t.medium,children:t.medium}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:`inline-block text-[10px] px-1.5 py-0.5 rounded-full border ${t.trafficClass==="paid"?"border-caution-700 text-caution-300":"border-strong text-secondary"}`,title:l,children:r})}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:i,children:a})}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[n,"%"]})]})}function mc({row:t}){const s=Si[t.sourceDimension]??t.sourceDimension,n=Ci[t.sourceDimension]??"";return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"max-w-[400px] py-1.5 text-neutral",children:e.jsx(ps,{value:t.landingPage,className:"whitespace-nowrap"})}),e.jsx("td",{className:"py-1.5 text-strong max-w-[220px] truncate",title:t.source,children:t.source}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:n,children:s})}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.sessions.toLocaleString()})]})}function xc({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=t.channelGroup==="Paid Social"?"Paid":"Organic",i=Ht(t.source),r=Ht(t.medium);return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 pr-3 text-strong truncate",title:t.source,children:i}),e.jsx("td",{className:"py-1.5 pr-3 text-muted truncate",title:t.medium,children:r}),e.jsx("td",{className:"py-1.5 pr-3",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:`GA4 channel group: ${t.channelGroup}`,children:a})}),e.jsx("td",{className:"py-1.5 text-right text-info-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[n,"%"]}),e.jsx("td",{className:"py-1.5 text-right text-strong tabular-nums",children:t.users.toLocaleString()})]})}function hc({sources:t,otherCount:s}){const n=[{key:zt,color:vi,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const i=t[a];if(i===es)n.push({key:es,color:Mn,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const r=Ht(i);n.push({key:i,color:wt[a%wt.length]??Mn,label:yi(r,32),tooltip:r})}}return e.jsx("div",{className:"mt-3 flex flex-wrap gap-x-4 gap-y-1.5 text-[11px] text-secondary",children:n.map(a=>e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 max-w-[260px]",title:a.tooltip,children:[e.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-sm shrink-0",style:{backgroundColor:a.color},"aria-hidden":"true"}),e.jsx("span",{className:"truncate",children:a.label})]},a.key))})}function pc(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 gc=["7d","30d","90d","all"],Gs=500,vt=25,fc="canonry:google-oauth-complete";function Pa(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function La(t){const s=Number(t.errors??0),n=Number(t.warnings??0);return[s>0?`${s} error${s===1?"":"s"}`:"",n>0?`${n} warning${n===1?"":"s"}`:""].filter(Boolean).join(" · ")}function Ra(t){return t.isPending?"Processing":Number(t.errors??0)>0?"Errors":Number(t.warnings??0)>0?"Warnings":"Success"}function bc({projectName:t,refreshNonce:s}){const n=kt(),[a,i]=o.useState(!1),[r,l]=o.useState([]),[u,x]=o.useState([]),[m,f]=o.useState([]),[d,b]=o.useState(null),[A,$]=o.useState([]),[w,g]=o.useState([]),[D,F]=o.useState(null),[T,q]=o.useState(""),[h,k]=o.useState(""),[E,X]=o.useState("30"),[le,S]=o.useState(!1),[p,_]=o.useState("30d"),[y,G]=o.useState({startDate:"",endDate:"",query:"",page:""}),[re,J]=o.useState(0),[U,oe]=o.useState(!1),[ae,O]=o.useState(0),[M,j]=o.useState(!1),[Z,ie]=o.useState(""),[v,z]=o.useState(!0),[K,P]=o.useState(!1),[ee,fe]=o.useState(!1),[Ce,qe]=o.useState(!1),[Ge,gt]=o.useState(!1),[Ne,ft]=o.useState(!1),[We,Me]=o.useState(!1),[W,be]=o.useState(null),[Le,at]=o.useState(!1),[R,we]=o.useState(!1),[ke,bt]=o.useState(null),[N,ce]=o.useState(null),[de,it]=o.useState([]),[Ie,Cs]=o.useState(new Set),[Et,jt]=o.useState({}),[Zs,ks]=o.useState(new Set),[As,en]=o.useState(""),[ss,ns]=o.useState(null),[rt,as]=o.useState(""),[$s,Ps]=o.useState(!1),[ot,ze]=o.useState(!1),[L,pe]=o.useState(!1),[ne,ue]=o.useState(!1),[Pe,tn]=o.useState("indexed"),[Ye,sn]=o.useState(null),nn=!!(y.query.trim()||y.page.trim()||Ye),Ti=Ye!==null,Xn=o.useMemo(()=>{if(!Ye)return m;const{key:c,dir:C}=Ye;return[...m].sort((B,H)=>{const xe=c===Rt.CTR?Number.isFinite(B.ctr)?B.ctr:0:B[c],je=c===Rt.CTR?Number.isFinite(H.ctr)?H.ctr:0:H[c];return C==="asc"?xe-je:je-xe})},[m,Ye]),Ot=js({rows:Xn,pageSize:et}),Zn=M?Ot.rows:Xn,Ft=js({rows:(ke??[]).filter(c=>c.path.toLowerCase().includes(As.trim().toLowerCase())),pageSize:et}),[tt,ea]=o.useState([]),[Je,Ls]=o.useState(null),[Mi,ta]=o.useState(1),is=o.useMemo(()=>{if(tt.length<2)return null;const c=tt[tt.length-1],C=tt[tt.length-2];return{indexed:c.indexed-C.indexed,notIndexed:c.notIndexed-C.notIndexed}},[tt]);o.useEffect(()=>{ta(1)},[W,Pe,Je]);const Rs=o.useMemo(()=>Je?(W?.reasonGroups??[]).find(c=>c.reason===Je):void 0,[W,Je]),an=o.useMemo(()=>W?Pe==="indexed"?W.indexed:Pe==="deindexed"?W.deindexed:Pe==="notIndexed"?Je?Rs?.urls??[]:(W.reasonGroups??[]).length===0?W.notIndexed:[]:[]:[],[W,Pe,Je,Rs]),Ei=Math.max(1,Math.ceil(an.length/vt)),sa=Math.min(Math.max(1,Mi),Ei),Ue=(sa-1)*vt,Oi=o.useMemo(()=>W?.indexed.slice(Ue,Ue+vt)??[],[W,Ue]),Fi=o.useMemo(()=>W?.notIndexed.slice(Ue,Ue+vt)??[],[W,Ue]),_i=o.useMemo(()=>W?.deindexed.slice(Ue,Ue+vt)??[],[W,Ue]),qi=o.useMemo(()=>(Rs?.urls??[]).slice(Ue,Ue+vt),[Rs,Ue]),[rs,Ds]=o.useState(!1),[na,ge]=o.useState(null),[lt,Is]=o.useState(null),[aa,ct]=o.useState(null);function Gi(c,C){const B=jl(c),H=pc(B);H?(Is(H),ge(null)):(Is(null),ge(B.message||C))}const Be=r.find(c=>c.connectionType==="gsc"),At=(Be?.scopes??[]).includes("https://www.googleapis.com/auth/webmasters"),rn=de.length>0?de:(ke??[]).map(c=>c.path),ia=rn.filter(c=>ke?.some(C=>C.path===c&&C.isSitemapsIndex)).length,Bi=ia===1?"Resubmit sitemap index":ia>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",Ui=m.length>0||A.length>0||w.length>0,on=fr(),ln=br();async function ra(c,C=!1){if(!c){x([]),q("");return}fe(!0);try{const{sites:B}=await n.fetchQuery({...Rr({client:V,path:{name:t}}),staleTime:C?0:Te});x(B),q(c.propertyId??B[0]?.siteUrl??""),Is(null)}catch(B){x([]),Gi(B,"Failed to load Search Console properties")}finally{fe(!1)}}async function os(c){gt(!0);const C=c??re;try{const B=nn?Gs:et,H=nn?0:C,xe={limit:String(B)};y.startDate&&(xe.startDate=y.startDate),y.endDate&&(xe.endDate=y.endDate),y.query&&(xe.query=y.query),y.page&&(xe.page=y.page),H>0&&(xe.offset=String(H)),p&&p!=="all"&&!y.startDate&&(xe.window=p);const je=await n.fetchQuery({...yr({client:V,path:{name:t},query:xe}),staleTime:Te}),ye=je.rows;nn?(oe(!1),f(ye),O(ye.length),j(!0)):(oe(H+ye.length<je.totalMatching),f(ye),O(0),j(!1))}catch(B){f([]),oe(!1),O(0),ge(B instanceof Error?B.message:"Failed to load GSC performance data")}finally{gt(!1)}}async function cn(){try{const c={};y.startDate&&(c.startDate=y.startDate),y.endDate&&(c.endDate=y.endDate),p&&p!=="all"&&!y.startDate&&(c.window=p);const C=await n.fetchQuery({...vr({client:V,path:{name:t},query:c}),staleTime:Te});b(C)}catch{b(null)}}async function Ts(c=!1){ft(!0);try{const C=Z.trim()||void 0,B={limit:"20"};C&&(B.url=C);const[H,xe]=await Promise.all([n.fetchQuery({...Pr({client:V,path:{name:t},query:B}),staleTime:c?0:Te}),n.fetchQuery({...Lr({client:V,path:{name:t}}),staleTime:c?0:Te})]);$(H),g(xe)}catch(C){$([]),g([]),ge(C instanceof Error?C.message:"Failed to load GSC inspection history")}finally{ft(!1)}}async function oa(c=!1){at(!0);try{const[C,B]=await Promise.all([n.fetchQuery({...Xa({client:V,path:{name:t}}),staleTime:c?0:Te}),n.fetchQuery({...Sr({client:V,path:{name:t}}),staleTime:c?0:Te}).catch(()=>[])]);be(C),ea(B)}catch(C){be(null),ea([]),ge(C instanceof Error?C.message:"Failed to load coverage data")}finally{at(!1)}}async function la(c){Ds(!0),ge(null);try{const C=await ga(t,{urls:c}),{succeeded:B,failed:H,total:xe}=C.summary;se({title:"Indexing requested",detail:H===0?`${B} URL${B!==1?"s":""} submitted for indexing.`:`${B}/${xe} submitted successfully, ${H} failed.`,tone:H===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(C){ge(C instanceof Error?C.message:"Failed to request indexing")}finally{Ds(!1)}}async function Qi(){Ds(!0),ge(null);try{const c=await ga(t,{urls:[],allUnindexed:!0}),{succeeded:C,failed:B,total:H}=c.summary;se({title:"Indexing requested",detail:B===0?`${C} unindexed URL${C!==1?"s":""} submitted for indexing.`:`${C}/${H} submitted successfully, ${B} failed.`,tone:B===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(c){ge(c instanceof Error?c.message:"Failed to request indexing")}finally{Ds(!1)}}async function dn(){we(!0),ge(null);try{const c=await un(t);n.setQueryData(Cr({client:V,path:{name:t}}),c),bt(c.sitemaps),ce(c.summary),it(c.preferredSubmissionUrls),Cs(new Set),jt({}),c.sitemaps.length===0&&ct("No sitemaps found in this GSC property. Submit one here to start Google processing it.")}catch(c){ge(c instanceof Error?c.message:"Failed to list sitemaps")}finally{we(!1)}}async function zi(c){const C=Ie.has(c);if(Cs(B=>{const H=new Set(B);return C?H.delete(c):H.add(c),H}),!(C||Et[c])){ks(B=>new Set(B).add(c));try{const B=await un(t,c);jt(H=>({...H,[c]:B.sitemaps}))}catch(B){ge(B instanceof Error?B.message:"Failed to load sitemap files")}finally{ks(B=>{const H=new Set(B);return H.delete(c),H})}}}async function _t(c){if(!At||c.length===0)return;const C=[...new Set(c)];ze(!0),ge(null),ns({completed:0,total:C.length});let B=0,H=0,xe=0,je=null;try{for(let Ae=0;Ae<C.length;Ae+=50){const me=C.slice(Ae,Ae+50);try{const Ee=await kr(t,me);B+=Ee.summary.accepted,H+=Ee.summary.failed,xe+=me.length,ns({completed:xe,total:C.length})}catch(Ee){xe+=me.length;const Xe=me.length,$t=C.length-xe,qt=Ee instanceof Error?Ee.message:"The batch request failed",ls=`${B} accepted, ${H} failed, ${Xe} unconfirmed, ${$t} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;je=`Sitemap submission stopped after a batch request failed. ${ls} ${qt}`,ge(je),se({title:"Sitemap resubmission partially completed",detail:ls,tone:"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"});return}}const ye=C.length;se({title:H===0?"Sitemap submitted to Google":"Some sitemap submissions need attention",detail:H===0?"Google accepted the sitemap submission/refetch request; indexing is not guaranteed.":`Google accepted ${B}/${ye} sitemap submissions; ${H} failed. Indexing is not guaranteed.`,tone:H===0?"positive":"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"}),as("")}catch(ye){ge(ye instanceof Error?ye.message:"Failed to submit sitemap to Google")}finally{ze(!1),ns(null),await dn(),je&&ge(je)}}async function Hi(){ze(!0);const c=ke??[];try{const C=c.filter(H=>H.isSitemapsIndex),B=[];for(let H=0;H<C.length;H+=4)(await Promise.all(C.slice(H,H+4).map(async je=>{const ye=Et[je.path];if(ye)return ye;const Ae=await un(t,je.path);return jt(me=>({...me,[je.path]:Ae.sitemaps})),Ae.sitemaps}))).forEach((je,ye)=>{B.push(...je.length>0?je.map(Ae=>Ae.path):[C[H+ye].path])});await _t([...c.filter(H=>!H.isSitemapsIndex).map(H=>H.path),...B])}catch(C){ge(C instanceof Error?C.message:"Failed to load sitemap files"),ze(!1)}}async function ca(c){Ps(!0),ge(null);try{await Ar(t,"gsc",c),await De(n,"google"),l(C=>C.map(B=>B.connectionType==="gsc"?{...B,sitemapUrl:c}:B)),se({title:"Default sitemap updated",detail:c,tone:"positive",dedupeKey:`gsc:sitemap-default:${t}`,dedupeMode:"replace"})}catch(C){ge(C instanceof Error?C.message:"Failed to set the default sitemap")}finally{Ps(!1)}}async function da(c){try{await ln.mutateAsync({projectName:t,projectLabel:t,opts:c?{sitemapUrl:c}:void 0})}catch{}}async function ua(){z(!0),ge(null);try{const[c,C]=await Promise.all([Ja().catch(()=>null),n.fetchQuery({...Gn({client:V,path:{name:t}}),staleTime:Te}).catch(()=>[])]);i(!!c?.google?.configured),l(C);const B=C.find(H=>H.connectionType==="gsc");await Promise.all([ra(B),os(),cn(),Ts(),oa(),B?.propertyId?dn():Promise.resolve()])}finally{z(!1)}}o.useEffect(()=>{ua()},[t,s]),o.useEffect(()=>{J(0),os(0),cn()},[p]);const ma=o.useRef(!1);o.useEffect(()=>{if(!ma.current){ma.current=!0;return}J(0),os(0)},[Ti]);async function xa(){if(!a){ge("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}P(!0),ge(null),ct(null);try{let c=function(Ee){if(Ee.source!==H||Ee.origin!==xe||!Ee.data||typeof Ee.data!="object")return;const Xe=Ee.data;Xe.type!==fc||Xe.connectionType!=="gsc"||me(!0)};const{authUrl:C,redirectUri:B}=await wr(t,"gsc");if(!C.startsWith("https://accounts.google.com/")){ge("Unexpected OAuth redirect URL. Please try again.");return}const H=window.open(C,"_blank","width=600,height=700");if(!H){window.location.assign(C);return}const xe=B?new URL(B).origin:window.location.origin;let je=!1,ye=null;const Ae=()=>{ye!==null&&window.clearInterval(ye),window.removeEventListener("message",c)},me=async Ee=>{if(!je){je=!0,Ae(),ct(Ee?"Google connected. Refreshing access…":"Refreshing Google connection…");try{await De(n,"google"),await ua()}finally{ct(null)}}};window.addEventListener("message",c),ct("Finish the Google consent flow in the popup. This page will refresh automatically."),ye=window.setInterval(()=>{H.closed&&me(!1)},1e3)}catch(c){ge(c instanceof Error?c.message:"Failed to start OAuth flow")}finally{P(!1)}}async function Ki(){ge(null),ct(null);try{await Nr(t,"gsc"),await De(n,"google"),l(c=>c.filter(C=>C.connectionType!=="gsc")),x([]),q("")}catch(c){ge(c instanceof Error?c.message:"Failed to disconnect")}}async function Vi(){if(T){qe(!0),ge(null);try{await Dr(t,"gsc",T),await De(n,"google"),l(c=>c.map(C=>C.connectionType==="gsc"?{...C,propertyId:T}:C)),se({title:"GSC property updated",detail:`${t} is now linked to ${T}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(c){ge(c instanceof Error?c.message:"Failed to save GSC property")}finally{qe(!1)}}}async function Wi(){ge(null),ct(null);try{await on.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(E,10)||void 0,full:le||void 0}}),await De(n,"gsc")}catch{}}async function ha(){if(h.trim()){Me(!0),ge(null),ct(null);try{const c=await $r(t,h.trim());await De(n,"gsc"),F(c),k(""),await Ts()}catch(c){ge(c instanceof Error?c.message:"Failed to inspect URL")}finally{Me(!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"})]})}),lt&&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:lt.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:lt.message}),(Pt(lt.enableUrl)||Pt(lt.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[Pt(lt.enableUrl)&&e.jsx("a",{href:Pt(lt.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 ↗"}),Pt(lt.indexingApiUrl)&&e.jsx("a",{href:Pt(lt.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:()=>Is(null),children:"×"})]})}),na&&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:[na,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>ge(null),children:"×"})]}),aa&&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:[aa,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>ct(null),children:"×"})]}),v?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[Be?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:Be.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Last updated ",st(Be.updatedAt)]}),e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:he(Ki),children:"Disconnect"})]}):e.jsxs(Y,{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(te,{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(I,{type:"button",variant:"outline",size:"sm",disabled:K,onClick:he(xa),children:K?"Opening…":"Connect Google Search Console"}):e.jsx(I,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(xt,{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."})]})]})]}),(Be||Ui)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs(Y,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Performance"}),e.jsx("h3",{children:"Search performance"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"segmented",role:"group","aria-label":"Performance time period",children:gc.map(c=>e.jsx("button",{type:"button","aria-pressed":p===c,className:`segmented-option ${p===c?"segmented-option-active":""}`,onClick:()=>{_(c),J(0),Ot.setPage(1)},children:c==="all"?"All":c},c))}),e.jsx(I,{type:"button",variant:"outline",size:"sm",disabled:Ge,onClick:()=>{J(0),Ot.setPage(1),os(0),cn()},children:Ge?"Loading…":"Apply filters"})]})]}),d&&d.daily.length>0&&(()=>{const c=d.daily,C=Math.max(...c.map(Se=>Se.impressions),1),{clicks:B,impressions:H,ctr:xe}=d.totals,je=(xe*100).toFixed(1),ye=700,Ae=220,me={top:12,bottom:36,left:48,right:12},Ee=ye-me.left-me.right,Xe=Ae-me.top-me.bottom,$t=Ee/c.length,qt=Math.max(Math.min($t*.35,24),4),ls=Math.max(qt*.15,1),Yi=Se=>{if(Se<=0)return 1;const dt=Math.pow(10,Math.floor(Math.log10(Se))),He=Se/dt,yt=He<=1.5?1.5:He<=3?3:He<=5?5:10;return Math.ceil(yt*dt)},Ms=4,Es=Math.ceil(Yi(C)/Ms)*Ms,Ji=Array.from({length:Ms+1},(Se,dt)=>Es/Ms*dt),Xi=Se=>Se>=1e3?`${(Se/1e3).toFixed(Se>=1e4?0:1)}k`:String(Se);return e.jsxs("div",{className:"mt-3",children:[e.jsxs("div",{className:"flex items-center gap-5 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-sm bg-positive-500"}),e.jsxs("span",{className:"text-xs text-secondary",children:["Clicks ",e.jsx("span",{className:"text-strong tabular-nums font-medium",children:B.toLocaleString()})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-sm bg-chart-series-2"}),e.jsxs("span",{className:"text-xs text-secondary",children:["Impressions ",e.jsx("span",{className:"text-strong tabular-nums font-medium",children:H.toLocaleString()})]})]}),e.jsxs("span",{className:"text-xs text-muted",children:["CTR ",e.jsxs("span",{className:"text-caution-400 tabular-nums font-medium",children:[je,"%"]})]})]}),e.jsx("div",{className:"relative w-full",style:{aspectRatio:`${ye} / ${Ae}`},children:e.jsxs("svg",{viewBox:`0 0 ${ye} ${Ae}`,className:"h-full w-full",children:[Ji.map((Se,dt)=>{const He=me.top+Xe-Se/Es*Xe;return e.jsxs("g",{children:[e.jsx("line",{x1:me.left,y1:He,x2:ye-me.right,y2:He,stroke:_e.gridLine,strokeWidth:"1"}),e.jsx("text",{x:me.left-6,y:He+3.5,textAnchor:"end",fill:_e.text,fontSize:"10",fontFamily:"inherit",children:Xi(Se)})]},`t-${dt}`)}),c.map((Se,dt)=>{const He=me.left+$t*dt+$t/2,yt=Se.impressions/Es*Xe,Os=Se.clicks/Es*Xe;return e.jsxs("g",{children:[e.jsx("title",{children:`${Se.date}
|
|
2
2
|
Clicks: ${Se.clicks}
|
|
3
3
|
Impressions: ${Se.impressions}
|
|
4
4
|
CTR: ${(Se.ctr*100).toFixed(1)}%`}),e.jsx("rect",{x:He-qt-ls/2,y:me.top+Xe-yt,width:qt,height:Math.max(yt,1),rx:2,fill:Fe[1],opacity:.85}),e.jsx("rect",{x:He+ls/2,y:me.top+Xe-Os,width:qt,height:Math.max(Os,1),rx:2,fill:ht.positiveDeep,opacity:.85})]},Se.date)}),(()=>{const Se=Math.min(c.length,7);return Array.from({length:Se},(dt,He)=>{const yt=c.length===1?0:Math.round(He/(Se-1)*(c.length-1)),Os=me.left+$t*yt+$t/2;return e.jsx("text",{x:Os,y:Ae-8,textAnchor:"middle",fill:_e.textDim,fontSize:"10",fontFamily:"inherit",children:c[yt].date.slice(5)},`xl-${yt}`)})})()]})})]})})(),e.jsxs("div",{className:"mt-3 grid gap-2 lg:grid-cols-4",children:[e.jsx("input",{className:"rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"date","aria-label":"Start date",title:"Start date (inclusive). Leave blank to use the window above.",value:y.startDate,onChange:c=>G(C=>({...C,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:y.endDate,onChange:c=>G(C=>({...C,endDate:c.target.value}))}),e.jsx(Qt,{value:y.query,onChange:c=>G(C=>({...C,query:c})),label:"Filter search queries",placeholder:"Contains query…"}),e.jsx(Qt,{value:y.page,onChange:c=>G(C=>({...C,page:c})),label:"Filter page URLs",placeholder:"Contains page URL…"})]}),e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Query and page filters match case-insensitive substrings. Click Apply filters to run. Filtering and sorting examine up to ",Gs.toLocaleString()," matching rows while the table stays at ",et," rows per page."]}),m.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Date"}),e.jsx("th",{className:"text-left",children:"Query"}),e.jsx("th",{className:"text-left",children:"Page"}),Object.values(Rt).map(c=>e.jsx("th",{className:"text-right","aria-sort":Ye?.key===c?Ye.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:()=>{Ot.setPage(1),sn(C=>C?.key===c?C.dir==="desc"?{key:c,dir:"asc"}:null:{key:c,dir:"desc"})},children:[jr[c],Ye?.key===c?Ye.dir==="desc"?" ↓":" ↑":""]})},c))]})}),e.jsx("tbody",{children:Zn.map((c,C)=>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 text-secondary",children:e.jsx(ps,{value: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}:${C}`))})]})}),e.jsx(Tt,{page:M?Ot.page:Math.floor(re/et)+1,pageSize:et,visibleRows:Zn.length,totalRows:M?ae:void 0,hasNextPage:M?void 0:U,disabled:Ge,itemLabel:M?"matches":"rows",onPageChange:c=>{if(M){Ot.setPage(c);return}const C=(c-1)*et;J(C),os(C)}}),M&&ae>=Gs?e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Results are capped at ",Gs.toLocaleString(),"; narrow the filters to search beyond this set."]}):null]}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No performance rows match the current filters yet."})]}),e.jsxs(Y,{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:[W&&W.notIndexed.length>0&&e.jsx(I,{type:"button",variant:"outline",size:"sm",disabled:rs,onClick:()=>{Qi()},children:rs?"Requesting…":`Request indexing (${W.notIndexed.length})`}),e.jsx(I,{type:"button",variant:"outline",size:"sm",disabled:Le,onClick:()=>{oa(!0)},children:Le?"Loading…":"Reload saved coverage"})]})]}),W&&W.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const c=W.summary.indexed+W.summary.notIndexed,C=c>0?W.summary.indexed/c:0,B=c>0?W.summary.notIndexed/c:0,H=54,xe=2*Math.PI*H,je=xe*(1-C),ye=xe*B,Ae=xe*C;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:H,fill:"none",stroke:_e.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:H,fill:"none",stroke:ht.positiveDeep,strokeWidth:"14",strokeDasharray:xe,strokeDashoffset:je,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),W.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:H,fill:"none",stroke:_e.textFaint,strokeWidth:"14",strokeDasharray:`${ye} ${xe-ye}`,strokeDashoffset:-Ae,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:[(C*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:W.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:W.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:["Not indexed",(W.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-faint",children:["· ",(W.reasonGroups??[]).length," ",(W.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),W.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:W.summary.deindexed.toLocaleString()}),e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:"Deindexed"})]})]})]})]})]})})()}),e.jsx("div",{className:"mt-3 flex border-b border-default",role:"tablist","aria-label":"Coverage status",children:["indexed","notIndexed","deindexed"].map(c=>{const C=c==="indexed"?W.indexed.length:c==="notIndexed"?W.notIndexed.length:W.deindexed.length,B=c==="indexed"?"Indexed":c==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",role:"tab","aria-selected":Pe===c,className:`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${Pe===c?"border-accent text-heading":"border-transparent text-secondary hover:border-mono-600 hover:text-strong"}`,onClick:()=>{tn(c),Ls(null)},children:[B," (",C,")"]},c)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[Pe==="indexed"&&W.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:Oi.map(c=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:c.url}),e.jsx("td",{className:"text-secondary",children:c.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:c.crawlTime?c.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:c.isMobileFriendly===!0?"Yes":c.isMobileFriendly===!1?"No":"—"})]},c.id))})]}),Pe==="notIndexed"&&!Je&&(W.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:(W.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:()=>Ls(c.reason),onKeyDown:C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),Ls(c.reason))},tabIndex:0,role:"button","aria-label":`View ${c.reason} pages`,children:[e.jsx("td",{className:"text-strong",children:c.reason}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:c.count})]},c.reason))})]}),Pe==="notIndexed"&&!Je&&(W.reasonGroups??[]).length===0&&W.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:Fi.map(c=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:c.url}),e.jsx("td",{className:"text-secondary",children:c.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:c.coverageState??"Unknown"})]},c.id))})]}),Pe==="notIndexed"&&Je&&(()=>{const c=(W.reasonGroups??[]).find(C=>C.reason===Je);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:()=>Ls(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(I,{type:"button",variant:"outline",size:"sm",disabled:rs,onClick:()=>{la(c.urls.map(C=>C.url))},children:rs?"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:qi.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.crawlTime?C.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-strong transition-colors",disabled:rs,onClick:()=>{la([C.url])},title:"Request indexing",children:"Index"})})]},C.id))})]})]}):null})(),Pe==="deindexed"&&W.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:_i.map((c,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}),e.jsx("td",{className:"text-secondary",children:c.currentState}),e.jsx("td",{className:"text-secondary",children:c.transitionDate.split("T")[0]})]},`${c.url}-${C}`))})]}),(Pe==="indexed"&&W.indexed.length===0||Pe==="notIndexed"&&!Je&&W.notIndexed.length===0||Pe==="deindexed"&&W.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),e.jsx(Tt,{page:sa,pageSize:vt,visibleRows:Math.min(vt,an.length-Ue),totalRows:an.length,onPageChange:ta,itemLabel:"URLs"})]}),e.jsx("p",{className:"mt-3 text-xs text-muted",children:"Google's Indexing API is intended for eligible JobPosting and BroadcastEvent pages. Sitemap resubmission is the general-site bulk path."}),e.jsxs("div",{className:"mt-4 border-t border-default pt-3",children:[e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between text-left text-xs text-secondary hover:text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400","aria-expanded":ne,onClick:()=>ue(c=>!c),children:[e.jsx("span",{children:"Coverage history"}),e.jsx("span",{children:ne?"Hide snapshots":tt.length>0?`View ${tt.length} snapshots`:"View history"})]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["Current: ",W.summary.indexed.toLocaleString()," indexed, ",W.summary.notIndexed.toLocaleString()," not indexed.",is&&e.jsxs(e.Fragment,{children:[" Since the last snapshot: ",is.indexed>=0?"+":"",is.indexed.toLocaleString()," indexed, ",is.notIndexed>=0?"+":"",is.notIndexed.toLocaleString()," not indexed."]})]}),ne&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:tt.length>0?e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Date"}),e.jsx("th",{className:"text-right",children:"Indexed"}),e.jsx("th",{className:"text-right",children:"Not indexed"})]})}),e.jsx("tbody",{children:tt.map(c=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:c.date}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:c.indexed.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:c.notIndexed.toLocaleString()})]},c.date))})]}):e.jsx("p",{className:"text-sm text-muted",children:"No saved coverage snapshots yet."})})]})]}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:Le?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),e.jsxs(Y,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Sitemaps"}),e.jsx("h3",{children:"Sitemap operations"})]}),e.jsx(I,{type:"button",variant:"outline",size:"sm",disabled:R||!Be?.propertyId,onClick:()=>{dn()},children:R?"Reloading…":"Reload from Google"})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"url",placeholder:"https://example.com/sitemap.xml",value:rt,onChange:c=>as(c.target.value),onKeyDown:c=>c.key==="Enter"&&void _t([rt.trim()])}),e.jsx(I,{type:"button",size:"sm",disabled:!At||ot||!rt.trim(),onClick:()=>{_t([rt.trim()])},children:ot?"Submitting…":"Submit sitemap to Google"})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(I,{type:"button",size:"sm",variant:"outline",disabled:!At||ot||rn.length===0,onClick:()=>{_t(rn)},children:ot?"Resubmitting…":Bi}),e.jsx(I,{type:"button",size:"sm",variant:"outline",disabled:!At||ot||!ke?.length,onClick:()=>{Hi()},children:"Resubmit all files"}),N&&e.jsxs("span",{className:"text-xs text-muted",children:["Top level: ",N.indexes," index",N.indexes===1?"":"es",", ",N.files," file",N.files===1?"":"s"]}),ss&&e.jsxs("span",{className:"text-xs text-secondary",children:["Submitting ",ss.completed,"/",ss.total]})]}),e.jsx("p",{className:"mt-2 text-xs text-muted",children:"Google is asked to refetch these sitemaps. Indexing is not guaranteed."}),!At&&Be&&e.jsxs("div",{className:"mt-2 flex items-center gap-2 text-xs text-caution",children:[e.jsx("span",{children:"Reconnect to let Canonry submit sitemaps. Your current Canonry OAuth grant is read-only."}),e.jsx("button",{type:"button",className:"text-secondary underline hover:text-strong",onClick:he(xa),children:"Reconnect"})]}),ke&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:ke.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Qt,{value:As,onChange:c=>{en(c),Ft.setPage(1)},label:"Filter sitemaps",placeholder:"Filter sitemaps…"}),e.jsxs("table",{className:"data-table mt-3 w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Sitemap"}),e.jsx("th",{className:"text-left",children:"Type"}),e.jsx("th",{className:"text-left",children:"Google status"}),e.jsx("th",{className:"text-left",children:"Last submitted"}),e.jsx("th",{className:"text-left",children:"Last read"}),e.jsx("th",{className:"text-right",children:"Discovered URLs"}),e.jsx("th",{className:"text-left",children:"Issues"}),e.jsx("th",{className:"text-left",children:"Actions"})]})}),e.jsx("tbody",{children:Ft.rows.flatMap(c=>{const C=Pa(c),B=La(c),H=Ra(c),xe=Et[c.path]??[],je=Ie.has(c.path),ye=e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs text-strong",children:e.jsx(ps,{value:c.path})}),e.jsx("td",{className:"text-secondary",children:c.isSitemapsIndex?e.jsx("button",{type:"button",className:"text-secondary hover:text-strong","aria-expanded":je,"aria-label":`${je?"Collapse":"Expand"} files in ${c.path}`,onClick:()=>{zi(c.path)},children:Zs.has(c.path)?"Loading…":`${je?"▾":"▸"} Index${Et[c.path]?` (${xe.length})`:""}`}):"Sitemap"}),e.jsx("td",{className:"text-secondary",children:H}),e.jsx("td",{className:"text-secondary",children:c.lastSubmitted?c.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:c.lastDownloaded?c.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:C.toLocaleString()}),e.jsx("td",{className:"max-w-48 text-secondary",children:B||"—"}),e.jsx("td",{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:!At||ot,onClick:()=>{_t([c.path])},children:c.lastSubmitted?"Resubmit to Google":"Submit to Google"}),Be?.sitemapUrl===c.path?e.jsx("span",{className:"text-xs text-muted",title:"Used when no sitemap URL is provided for Canonry GSC operations.",children:"Default sitemap"}):e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:$s,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{ca(c.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:ln.isPending,onClick:()=>{da(c.path)},children:"Inspect URLs"})]})})]},c.path),Ae=c.isSitemapsIndex&&je?xe.map(me=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs pl-6 text-secondary",children:e.jsx(ps,{value:me.path})}),e.jsx("td",{className:"text-secondary",children:"File"}),e.jsx("td",{className:"text-secondary",children:Ra(me)}),e.jsx("td",{className:"text-secondary",children:me.lastSubmitted?me.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:me.lastDownloaded?me.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:Pa(me).toLocaleString()}),e.jsx("td",{className:"text-secondary",children:La(me)||"—"}),e.jsx("td",{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:!At||ot,onClick:()=>{_t([me.path])},children:"Resubmit"}),Be?.sitemapUrl===me.path?e.jsx("span",{className:"text-xs text-muted",title:"Used when no sitemap URL is provided for Canonry GSC operations.",children:"Default sitemap"}):e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:$s,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{ca(me.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:ln.isPending,onClick:()=>{da(me.path)},children:"Inspect URLs"})]})})]},`${c.path}:${me.path}`)):[];return[ye,...Ae]})})]}),e.jsx(Tt,{page:Ft.page,pageSize:et,visibleRows:Ft.rows.length,totalRows:Ft.totalRows,onPageChange:Ft.setPage,itemLabel:"sitemaps"})]}):e.jsx("p",{className:"text-sm text-muted",children:"No sitemaps found for this property."})})]}),e.jsxs(Y,{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:h,onChange:c=>k(c.target.value),onKeyDown:c=>c.key==="Enter"&&void ha()}),e.jsx(I,{type:"button",size:"sm",disabled:We||!Be?.propertyId||!h.trim(),onClick:he(ha),children:We?"Inspecting…":"Inspect URL"})]}),D&&e.jsxs("div",{className:"mt-3 grid gap-3 md:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Indexing state"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:D.indexingState??"Unknown"})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Verdict"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:D.verdict??"Unknown"})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Mobile friendly"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:pa(D.isMobileFriendly??null)})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Last crawl"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:st(D.crawlTime)})]})]})]}),e.jsxs(Y,{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(I,{type:"button",variant:"outline",size:"sm",disabled:Ne,onClick:()=>{Ts(!0)},children:Ne?"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:Z,onChange:c=>ie(c.target.value)}),e.jsx(I,{type:"button",size:"sm",variant:"outline",disabled:Ne,onClick:()=>{Ts(!0)},children:"Apply filter"})]}),A.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:A.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:pa(c.isMobileFriendly??null)}),e.jsx("td",{className:"text-secondary",children:st(c.inspectedAt)})]},c.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No inspection history yet."})]}),e.jsxs(Y,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Deindexed"}),e.jsx("h3",{children:"Recent indexing losses"})]})}),w.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Previous"}),e.jsx("th",{className:"text-left",children:"Current"}),e.jsx("th",{className:"text-left",children:"Changed at"})]})}),e.jsx("tbody",{children:w.map(c=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:c.url}),e.jsx("td",{className:"text-secondary",children:c.previousState??"Unknown"}),e.jsx("td",{className:"text-neutral",children:c.currentState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:st(c.transitionDate)})]},`${c.url}:${c.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No deindexed transitions recorded."})]})]}),Be&&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:()=>pe(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 ${L?"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"})]})}),L&&e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(Y,{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:T,disabled:ee||u.length===0,onChange:c=>q(c.target.value),children:u.length===0?e.jsx("option",{value:"",children:ee?"Loading properties…":"No properties available"}):u.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(I,{type:"button",size:"sm",variant:"outline",disabled:ee,onClick:()=>{ra(Be,!0)},children:ee?"Refreshing…":"Refresh properties"}),e.jsx(I,{type:"button",size:"sm",disabled:!T||Ce,onClick:he(Vi),children:Ce?"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(Y,{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=>X(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:le,onChange:c=>S(c.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(I,{type:"button",size:"sm",disabled:on.isPending||!Be.propertyId,onClick:he(Wi),children:on.isPending?"Queueing…":"Queue sync"}),!Be.propertyId&&e.jsx("p",{className:"text-xs text-caution-400",children:"Select a Search Console property before queueing a sync."})]})]})]})})]})]})]})}const jc=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function yc({projectName:t,projectId:s}){const n=kt(),[a,i]=o.useState(null),[r,l]=o.useState(null),[u,x]=o.useState(!1),m=ve(Gn({client:V,path:{name:t}})),f=m.data?.find(P=>P.connectionType==="gbp"),d=!!f,b=a?{locationName:a}:void 0,A=ve({...Ir({client:V,path:{name:t}}),enabled:d}),$=ve({...Tr({client:V,path:{name:t},query:b}),enabled:d}),w=ve({...Mr({client:V,path:{name:t},query:b}),enabled:d}),g=ve({...Er({client:V,path:{name:t},query:b}),enabled:d}),D=ve({...Or({client:V,path:{name:t},query:b}),enabled:d}),F=ve({...Fr({client:V,path:{name:t},query:b}),enabled:d}),T=ve({queryKey:["gbp-section-insights",t],queryFn:()=>_r(t),enabled:d});function q(){De(n,"gbp")}const h=fs({...Gr(),onSuccess:P=>{qr({id:P.runId,projectId:s,kind:Mt["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),se({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),k=o.useSyncExternalStore(Za,Ks,Ks),E=Object.values(k.runs).some(P=>P.kind===Mt["gbp-sync"]&&P.projectId===s),X=h.isPending||E,le=fs({...Br(),onSuccess:()=>q()});if(o.useEffect(()=>{if(!a||!A.data)return;const P=A.data.locations.filter(ee=>ee.selected);(P.length<=1||!P.some(ee=>ee.locationName===a))&&i(null)},[a,A.data]),o.useEffect(()=>{if(!r||!A.data)return;(a?[a]:A.data.locations.filter(ee=>ee.selected).map(ee=>ee.locationName)).includes(r)||l(null)},[r,A.data,a]),m.isLoading)return null;if(!f){const P=[{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(Y,{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:P.map((ee,fe)=>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:fe+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:ee.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:ee.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:ee.note})]})]},ee.title))})]})})}const S=$.data,p=A.data?.locations??[],_=p.filter(P=>P.selected),y=w.data?.keywords??[],G=g.data?.lodging??[],re=D.data?.placeActions??[],J=F.data?.places??[],U=p.length>0?p[0].accountName:f.domain,oe=a?p.find(P=>P.locationName===a)?.displayName??null:null,ae=a?p.filter(P=>P.locationName===a):_,O=new Set(ae.map(P=>P.locationName)),M=G.filter(P=>O.has(P.locationName)),j=re.filter(P=>O.has(P.locationName)),Z=J.filter(P=>O.has(P.locationName)),ie=new Set(_.map(P=>P.locationName)),v=a?y:y.filter(P=>ie.has(P.locationName)),z=!a&&_.length>1,K=(T.data??[]).filter(P=>!P.dismissed&&jc.has(P.type)&&(!oe||P.query===oe||P.query===a||P.title.startsWith(oe)));return e.jsx("section",{className:"page-section-divider",children:e.jsxs(Y,{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($e,{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(te,{tone:"positive",children:"Connected"}),!Q()&&e.jsx(I,{type:"button",variant:"outline",size:"sm",disabled:X,onClick:()=>h.mutate({client:V,path:{name:t},body:{}}),children:X?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-muted",children:[U?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-secondary",children:U})," · "]}):null,A.data?`${A.data.totalSelected} of ${A.data.totalDiscovered} locations tracked`:"Loading locations…"]}),_.length>1&&e.jsxs("div",{className:"mb-5 max-w-xs",children:[e.jsx("label",{htmlFor:"local-presence-location",className:"mb-1 block text-sm font-medium text-secondary",children:"Location"}),e.jsxs("select",{id:"local-presence-location",value:a??"",onChange:P=>i(P.target.value||null),className:"w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-strong focus:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:[e.jsx("option",{value:"",children:"All locations"}),_.map(P=>e.jsx("option",{value:P.locationName,children:P.displayName},P.id))]})]}),_.length===0?e.jsxs("p",{className:"text-sm text-muted",children:["No locations are tracked yet. Open ",e.jsx("span",{className:"font-medium text-neutral",children:"Manage locations"})," below to track the one(s) for this business."]}):e.jsxs(e.Fragment,{children:[K.length>0&&e.jsxs("div",{className:"mb-6 grid gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Needs attention"}),K.map(P=>e.jsx("div",{className:["insight-card",Ic(P.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:[P.title,P.recommendation?.reason&&e.jsx($e,{text:P.recommendation.reason})]})},P.id))]}),S&&e.jsx(Oc,{performance:S.performance,freshness:S.freshness,timeseries:S.timeseries}),S?.profileCompleteness&&e.jsx(vc,{summary:S.profileCompleteness}),ae.length>0&&e.jsx(Nc,{locations:ae,lodging:M,places:Z,placeActions:j,expandedLocation:r,onToggleExpanded:P=>{l(ee=>ee===P?null:P)}}),e.jsxs("div",{className:"mb-2",children:[e.jsxs("div",{className:"section-head section-head-inline mb-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search terms"}),w.data&&w.data.total>0&&e.jsxs("span",{className:"text-[11px] text-faint",children:[w.data.thresholdedPct,"% privacy-thresholded"]})]}),v.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"}),z&&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:v.slice(0,25).map(P=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-neutral",children:P.keyword}),z&&e.jsx("td",{className:"text-muted",children:p.find(ee=>ee.locationName===P.locationName)?.displayName??P.locationName}),e.jsx("td",{className:"text-right font-mono text-strong",children:P.valueCount!==null?P.valueCount.toLocaleString():e.jsxs("span",{className:"text-muted",title:"Privacy floor — Google withheld the exact count",children:["<",P.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-faint",children:[P.periodStart,"–",P.periodEnd]})]},`${P.locationName}:${P.keyword}`))})]})]})]}),e.jsxs("div",{className:"mt-6 border-t border-default pt-4",children:[e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 text-xs font-medium text-secondary hover:text-strong",onClick:()=>x(P=>!P),"aria-expanded":u,children:[e.jsx("span",{"aria-hidden":"true",children:u?"▾":"▸"})," Manage locations (",p.length,")"]}),u&&e.jsx("div",{className:"mt-3",children:p.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"}),!Q()&&e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:p.map(P=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:P.displayName}),e.jsx("td",{className:"text-muted",children:P.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(te,{tone:P.selected?"positive":"neutral",children:P.selected?"Tracked":"Not tracked"})}),!Q()&&e.jsx("td",{className:"text-right",children:e.jsx(I,{type:"button",variant:"outline",size:"sm",disabled:le.isPending,onClick:()=>le.mutate({client:V,path:{name:t,locationName:P.locationName},body:{selected:!P.selected}}),children:P.selected?"Untrack":"Track"})})]},P.id))})]})})]})]})})}function vc({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:us(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:us(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:us(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:us(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:us(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($e,{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 ${Dc(a.tone)}`,children:a.value}),a.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-faint",children:a.detail})]},a.label))})]})}function Nc({locations:t,lodging:s,places:n,placeActions:a,expandedLocation:i,onToggleExpanded:r}){const l=new Map(s.map(m=>[m.locationName,m])),u=new Map(n.map(m=>[m.locationName,m])),x=new Map;for(const m of a){const f=x.get(m.locationName)??[];f.push(m),x.set(m.locationName,f)}return e.jsxs("div",{className:"mb-6",children:[e.jsxs("div",{className:"section-head section-head-inline mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Source evidence"}),e.jsx($e,{text:Q()?"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest sync, not that every Google product lacks the information.":"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest Canonry sync, not that every Google product lacks the information."})]}),e.jsxs("span",{className:"text-[11px] text-faint",children:[t.length," location",t.length===1?"":"s"]})]}),e.jsx("div",{className:"data-table-wrapper",children:e.jsxs("table",{className:"data-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"min-w-[14rem]",children:"Location"}),e.jsx("th",{className:"min-w-[15rem]",children:"Owner profile"}),e.jsx("th",{className:"min-w-[11rem]",children:"Hotel data"}),e.jsx("th",{className:"min-w-[11rem]",children:"Public Maps"}),e.jsx("th",{className:"min-w-[10rem]",children:"CTAs"}),e.jsx("th",{className:"text-right",children:"Detail"})]})}),e.jsx("tbody",{children:t.map(m=>{const f=l.get(m.locationName)??null,d=u.get(m.locationName)??null,b=x.get(m.locationName)??[],A=i===m.locationName;return e.jsxs(o.Fragment,{children:[e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-strong",children:m.displayName}),e.jsx("p",{className:"mt-1 text-xs text-faint",children:m.primaryCategoryDisplayName??"Primary category not returned"}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[e.jsx(te,{tone:m.selected?"positive":"neutral",children:m.selected?"Tracked":"Not tracked"}),m.openStatus&&m.openStatus!=="OPEN"&&e.jsx(te,{tone:m.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:ki(m.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(Sc,{location:m})}),e.jsx("td",{children:e.jsx(Cc,{lodging:f})}),e.jsx("td",{children:e.jsx(Ac,{place:d,mapsUri:m.mapsUri})}),e.jsx("td",{children:e.jsx(Pc,{actions:b})}),e.jsx("td",{className:"text-right",children:e.jsx(I,{type:"button",variant:"outline",size:"sm",onClick:()=>r(m.locationName),children:A?"Hide":"Details"})})]}),A&&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(Rc,{location:m,lodging:f,place:d,placeActions:b})})})]},m.id)})})]})})]})}function wc(t){return[{label:"Description",tone:Lt(t.description)?"positive":"neutral",value:Lt(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:Lt(t.primaryPhone)?"positive":"neutral",value:Lt(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:Lt(t.websiteUri)?"positive":"neutral",value:Lt(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 Sc({location:t}){const s=wc(t);return e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>e.jsxs(te,{tone:n.tone,children:[n.label," ",n.value]},n.label))})}function Cc({lodging:t}){return e.jsx(Kn,{...kc(t)})}function kc(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 Ac({place:t,mapsUri:s}){return e.jsx(Kn,{...$c(t,s)})}function $c(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 Pc({actions:t}){return e.jsx(Kn,{...Lc(t)})}function Lc(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 Kn({tone:t,label:s,detail:n}){return e.jsxs("div",{children:[e.jsx(te,{tone:t,children:s}),e.jsx("p",{className:"mt-1.5 text-xs leading-5 text-faint",children:n})]})}function Rc({location:t,lodging:s,place:n,placeActions:a}){const i=s?Mc(s.attributes):[];return e.jsxs("div",{className:"grid gap-5 text-xs lg:grid-cols-3",children:[e.jsxs(fn,{title:"Owner profile · Business Information",children:[e.jsx(Oe,{label:"Primary category",value:t.primaryCategoryDisplayName??"Not returned"}),e.jsx(Oe,{label:"Secondary categories",value:t.additionalCategories.length>0?t.additionalCategories.join(", "):"Not returned"}),e.jsx(Oe,{label:"Description",value:Lt(t.description)?t.description:"Not returned"}),e.jsx(Oe,{label:"Hours",value:t.regularHours?"Returned by Google":"Not returned"}),e.jsx(Oe,{label:"Service area",value:t.serviceArea?"Returned by Google":"Not returned"}),e.jsx(Oe,{label:"Phone",value:t.primaryPhone??"Not returned"}),e.jsx(Oe,{label:"Website",value:t.websiteUri??"Not returned"}),e.jsx(Oe,{label:"Open status",value:ki(t.openStatus)}),e.jsx(Oe,{label:"Opening date",value:t.openingDate??"Not returned"})]}),e.jsx(fn,{title:"Hotel data · Lodging API",children:s?e.jsxs(e.Fragment,{children:[e.jsx(Oe,{label:"Last checked",value:Da(s.syncedAt)}),e.jsx(Oe,{label:"Groups returned",value:String(s.populatedGroupCount)}),e.jsx(Oe,{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(fn,{title:"Public listing + CTAs",children:[n?e.jsxs(e.Fragment,{children:[e.jsx(Oe,{label:"Places tier",value:n.tier}),e.jsx(Oe,{label:"Last checked",value:Da(n.syncedAt)}),e.jsx(Oe,{label:"Public signals",value:n.amenities.length>0?n.amenities.join(", "):"No supported signals detected"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Places Details snapshot was stored for this location."}),t.mapsUri&&e.jsx("a",{href:t.mapsUri,target:"_blank",rel:"noopener noreferrer",className:"inline-block text-muted hover:text-neutral",children:"View on Google Maps →"}),e.jsx("div",{className:"mt-3 border-t border-default pt-3",children:a.length===0?e.jsx("p",{className:"leading-5 text-muted",children:"No placeActionLinks returned."}):e.jsx("div",{className:"grid gap-2",children:a.map(r=>e.jsxs("div",{className:"grid gap-0.5",children:[e.jsxs("span",{className:"font-medium text-neutral",children:[Ys(r.placeActionType),r.isPreferred?" · preferred":""]}),e.jsxs("span",{className:"text-faint",children:[Ys(r.providerType),r.uri?` · ${Tc(r.uri)}`:""]})]},r.placeActionLinkName))})})]})]})}function fn({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 Oe({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 us(t,s,n){return t===s?"positive":t===0?n:"caution"}function Dc(t){switch(t){case"positive":return"text-positive";case"caution":return"text-caution";case"negative":return"text-negative";case"neutral":return"text-neutral"}}function Ic(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function Lt(t){return typeof t=="string"&&t.trim().length>0}function ki(t){return t?Ys(t):"Not returned"}function Ys(t){return t?t.toLowerCase().split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"Unknown"}function Tc(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function Da(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Mc(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&Ec(n)).map(([s])=>Ys(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function Ec(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function Oc({performance:t,freshness:s,timeseries:n}){const a=t.totals,i=Ur.filter($=>(a[$]??0)>0),r=Qr.filter($=>(a[$]??0)>0),l=Object.keys(a).filter($=>(a[$]??0)>0&&zr($)==="other").sort(($,w)=>(a[w]??0)-(a[$]??0)),u=Object.keys(a).filter($=>(a[$]??0)===0).sort(),x=n.map($=>{const w={date:$.date};for(const[g,D]of Object.entries($.metrics))w[g]=D;return w}),m=n.find($=>$.pending)?.date,f=n.length>0?n[n.length-1].date:void 0,d=x.length>0,b=s.dataThroughDate?`Data through ${Ws(s.dataThroughDate)}${s.pendingDays>0?` · ${s.pendingDays}d pending`:""}`:null,A=[...i,...l];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"}),b&&e.jsx("span",{className:"text-[11px] text-muted",children:b})]}),!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(Ia,{data:x,metrics:i,kind:"line",firstPending:m,lastDate:f}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-x-5 gap-y-1",children:A.map($=>e.jsxs("span",{className:"text-sm text-secondary",children:[Vs($)," ",e.jsx("span",{className:"font-mono text-heading",children:(a[$]??0).toLocaleString()})]},$))})]})]}),d&&r.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(Ia,{data:x,metrics:r,kind:"area",firstPending:m,lastDate:f})]}),u.length>0&&e.jsxs("p",{className:"text-xs text-faint",children:["Not active: ",u.map($=>Vs($)).join(", ")]})]})}function Ia({data:t,metrics:s,kind:n,firstPending:a,lastDate:i}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(Wt,{width:"100%",height:"100%",children:e.jsxs(Yt,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(zn,{stroke:Un,vertical:!1}),e.jsx(Jt,{dataKey:"date",tick:Ve,tickLine:!1,axisLine:{stroke:pt},tickFormatter:Dn,minTickGap:24}),e.jsx(Xt,{tick:Ve,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Zt,{...It,labelFormatter:Ws,formatter:(r,l)=>[typeof r=="number"?r.toLocaleString():String(r??0),Vs(String(l??""))]}),e.jsx(di,{wrapperStyle:{fontSize:11,color:_e.text},formatter:r=>Vs(r)}),a&&i&&e.jsx(yl,{x1:a,x2:i,fill:_e.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:_e.textDim,fontSize:10}}),s.map((r,l)=>n==="line"?e.jsx(Hn,{type:"monotone",dataKey:r,stroke:Fe[l%Fe.length],strokeWidth:2,dot:!1,isAnimationActive:!1},r):e.jsx(Bt,{type:"monotone",dataKey:r,stackId:"reach",stroke:Fe[l%Fe.length],fill:Fe[l%Fe.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},r))]})})})}function Fc(t){return Qn(nt(String(t)))}function _c(t){return Ct(nt(String(t)))}function bn({children:t,label:s="More info",placement:n="top",className:a}){const i=o.useId(),[r,l]=o.useState(!1);return e.jsxs("span",{className:`relative inline-flex ${a??""}`,children:[e.jsx("button",{type:"button","aria-label":s,"aria-describedby":r?i:void 0,className:"inline-flex h-4 w-4 items-center justify-center rounded-full text-muted hover:text-strong focus:text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),onFocus:()=>l(!0),onBlur:()=>l(!1),children:e.jsx(Nl,{className:"h-3.5 w-3.5","aria-hidden":!0})}),r&&e.jsx("span",{id:i,role:"tooltip",className:`absolute z-50 w-64 rounded border border-strong bg-bg-elevated px-3 py-2 text-xs font-normal leading-relaxed text-strong shadow-lg ${n==="top"?"bottom-full mb-2":"top-full mt-2"} left-1/2 -translate-x-1/2 whitespace-normal`,children:t})]})}const Bs=et;function Gt(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function jn(t){return t.toLocaleString()}function qc(t){const s=Number(t);return Number.isFinite(s)?`${(s*100).toFixed(1)}%`:"—"}function Gc(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 Bc(t){const s=t.filter(n=>n.kind===Mt["backlink-extract"]&&!ei(n.status));return s.length===0?null:s.reduce((n,a)=>n.createdAt>a.createdAt?n:a)}function Uc(t,s){const n=new Date(t??s).getTime(),a=Math.max(0,Math.floor((Date.now()-n)/1e3));if(a<60)return`${a}s`;const i=Math.floor(a/60),r=a%60;return r===0?`${i}m`:`${i}m ${r}s`}function Qc({projectName:t}){const[s,n]=o.useState(null),[a,i]=o.useState(null),[r,l]=o.useState([]),[u,x]=o.useState(null),[m,f]=o.useState(null),[d,b]=o.useState(null),[A,$]=o.useState(Date.now()),[w,g]=o.useState(0),[D,F]=o.useState(!0),[T,q]=o.useState(!1),[h,k]=o.useState(null),E=o.useCallback(async()=>{F(!0),k(null);try{const[U,oe,ae,O,M]=await Promise.all([Hr().catch(()=>null),Kr(t,{excludeCrawlers:!0}).catch(()=>null),Vr(t,{limit:Bs,offset:w,excludeCrawlers:!0}).catch(Z=>{if(Z instanceof Ln&&Z.code==="NOT_FOUND")return null;throw Z}),Wr(t).catch(()=>[]),Yr(t).catch(()=>[])]);x(U),n(oe),i(ae),l(O);const j=Bc(M);f(j)}catch(U){k(U instanceof Error?U.message:"Failed to load backlinks")}finally{F(!1)}},[t,w]);o.useEffect(()=>{E()},[E]),o.useEffect(()=>{if(!m)return;const U=m.id;let oe=!1;const ae=async()=>{try{const M=await ti(U);if(oe)return;ei(M.status)?(f(null),b(M),await E()):f(j=>j?.id===M.id?{...j,...M}:j)}catch{}},O=window.setInterval(()=>{ae()},3e3);return()=>{oe=!0,window.clearInterval(O)}},[m,E]),o.useEffect(()=>{if(!m)return;const U=window.setInterval(()=>$(Date.now()),1e3);return()=>window.clearInterval(U)},[m]),o.useEffect(()=>{if(!d||d.status==="failed")return;const U=window.setTimeout(()=>b(null),1e4);return()=>window.clearTimeout(U)},[d]);async function X(){q(!0),k(null);try{const U=await Zr(t);f(U)}catch(U){U instanceof Ln&&U.code==="MISSING_DEPENDENCY"?k("DuckDB is not installed. Visit the Backlinks admin page to install it."):k(U instanceof Error?U.message:"Failed to trigger extract")}finally{q(!1)}}const le=o.useMemo(()=>r.slice().sort((U,oe)=>U.queriedAt.localeCompare(oe.queriedAt)).map(U=>({date:U.queriedAt,linkingDomains:U.totalLinkingDomains})),[r]),S=a?.rows??[],p=a?.total??0,_=s?.excludedLinkingDomains??0,y=Math.floor(w/Bs)+1;return o.useEffect(()=>{w>0&&w>=p&&g(0)},[w,p]),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"})]})}),h&&e.jsx(Y,{className:"surface-card p-4 mb-4 border-negative-800/60",children:e.jsx("p",{className:"text-sm text-negative",children:h})}),m&&e.jsx(Y,{className:"surface-card p-4 mb-4 border-info-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Rn,{className:"h-5 w-5 text-info-400 animate-spin shrink-0 mt-0.5","aria-hidden":!0}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"Extract running"}),e.jsx(te,{tone:"neutral",children:m.status}),e.jsxs("span",{className:"text-sm text-secondary tabular-nums",children:[Uc(m.startedAt??null,m.createdAt)," elapsed · refreshing every 3s"]}),e.jsxs("span",{className:"sr-only",children:["now=",A]})]}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Refreshing this project from the current Common Crawl release."})]})]})}),d&&!m&&e.jsx(Y,{className:`surface-card p-4 mb-4 ${d.status==="failed"?"border-negative-800/60":"border-positive-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[d.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(mi,{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 ${d.status==="failed"?"text-negative":"text-positive"}`,children:d.status==="failed"?"Extract failed":"Extract complete"}),d.error?e.jsx("p",{className:"text-sm text-secondary mt-1",children:Jr(d.error)}):d.status!=="failed"?e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),G()]});function G(){return D?e.jsx(Y,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading backlinks…"})}):re()}function re(){const U=s!==null&&s.totalLinkingDomains>0,oe=d?.status==="failed",ae=s!==null&&s.totalLinkingDomains===0&&!oe,O=u?.status==="ready",M=u?.status==="failed",j=u&&(u.status==="downloading"||u.status==="querying"||u.status==="queued");return U?J(e.jsxs(e.Fragment,{children:[!Q()&&e.jsxs(e.Fragment,{children:[e.jsxs(I,{type:"button",variant:"outline",size:"sm",disabled:T||m!==null,onClick:he(X),children:[e.jsx(ui,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),m?"Extract running…":T?"Queuing…":"Re-run extract"]}),e.jsx(bn,{label:"About re-running",children:"Re-queries the current release for this project without downloading it again."})]}),!Q()&&e.jsx(I,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Gt("/backlinks"),children:"Open admin"})})]})):e.jsx(Y,{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(Xr,{className:"h-5 w-5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1",children:[!u&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No release sync yet"}),e.jsx("p",{className:"text-sm text-muted mt-1",children:"Run a workspace release sync to populate backlinks for every project in this workspace."}),!Q()&&e.jsx("div",{className:"mt-4",children:e.jsx(I,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Gt("/backlinks"),children:"Set up backlinks"})})})]}),j&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Sync in progress"}),e.jsxs("p",{className:"text-sm text-muted mt-1",children:["A workspace release sync is running (",u.status,u.phaseDetail?` — ${u.phaseDetail}`:"","). Backlinks will appear here once it finishes."]}),!Q()&&e.jsx("div",{className:"mt-4",children:e.jsx(I,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Gt("/backlinks"),children:"View sync status"})})})]}),M&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Last sync failed"}),e.jsx("p",{className:"text-sm text-muted mt-1",children:u.error??"The workspace release sync failed. Retry from the Backlinks admin page."}),!Q()&&e.jsx("div",{className:"mt-4",children:e.jsx(I,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Gt("/backlinks"),children:"Go to Backlinks admin"})})})]}),O&&!j&&!ae&&!oe&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No backlinks yet for this project"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["Release ",e.jsx("code",{className:"text-neutral",children:u.release})," is ready. Run an extract for this project."]}),!Q()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(I,{type:"button",size:"sm",disabled:T||m!==null,onClick:he(X),children:[e.jsx(Vt,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),m?"Extract running…":T?"Queuing…":"Run extract"]}),e.jsx(bn,{label:"About extraction",children:"Queries the current release for this project without downloading it again."})]})]}),oe&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Last extract failed"}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"See the error above, then check the workspace source before retrying."}),!Q()&&e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(I,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Gt("/backlinks"),children:"Go to Backlinks admin"})})})]}),ae&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No referring domains found"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["The latest release found no referring domains for ",s.targetDomain,". Try a newer release or re-run this extract."]}),!Q()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(I,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Gt("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(I,{type:"button",variant:"outline",size:"sm",disabled:T||m!==null,onClick:he(X),children:[e.jsx(Vt,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),m?"Extract running…":T?"Queuing…":"Re-run extract"]}),e.jsxs(bn,{label:"What does Re-run extract do?",children:[e.jsxs("span",{className:"block",children:["Re-queries the cached release for ",e.jsx("span",{className:"text-strong",children:s.targetDomain}),". Only useful if the cache files were incomplete last time."]}),e.jsx("span",{className:"mt-2 block text-secondary",children:"No re-download. ~5 min. If the release genuinely has no links for your domain, this won’t help — sync a different release instead."})]})]})]})]})]})})}function J(U){if(!s)return null;const oe="Linking hosts",ae="linking hosts",O="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:jn(s.totalLinkingDomains)})}),e.jsxs("p",{className:"metric-card-sub",children:["unique domains linking to ",s.targetDomain]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("p",{className:"metric-card-eyebrow",children:["Total ",ae]}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:jn(s.totalHosts)})}),e.jsxs("p",{className:"metric-card-sub",children:["aggregate ",ae," 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:qc(s.top10HostsShare)})}),e.jsxs("p",{className:"metric-card-sub",children:["share of ",ae," from the 10 largest linking domains"]})]})]}),e.jsxs("p",{className:"text-xs text-muted mt-2",children:[e.jsx("span",{className:"text-secondary",children:"Common Crawl"})," · ",O," ",e.jsx("code",{className:"text-secondary",children:s.release})," · queried ",Gc(s.queriedAt),_>0&&e.jsxs(e.Fragment,{children:[" · ",_," excluded domain",_===1?"":"s"]})]}),le.length>=2&&e.jsxs(Y,{className:"surface-card p-4 mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Referring domains over time"}),e.jsx("div",{className:"h-40 mt-2",children:e.jsx(Wt,{width:"100%",height:"100%",children:e.jsxs(Yt,{data:le,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:Fe[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:Fe[0],stopOpacity:0})]})}),e.jsx(Jt,{dataKey:"date",tick:Ve,stroke:pt,tickFormatter:Fc}),e.jsx(Xt,{tick:Ve,stroke:pt,allowDecimals:!1}),e.jsx(Zt,{contentStyle:It.contentStyle,labelStyle:It.labelStyle,itemStyle:It.itemStyle,labelFormatter:_c}),e.jsx(Bt,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:Fe[0],fill:"url(#bl-gradient)",strokeWidth:2})]})})})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Top referring domains"}),e.jsx(Y,{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:oe})]})}),e.jsxs("tbody",{children:[S.map(M=>e.jsxs("tr",{className:"border-b border-mono-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-strong",children:M.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-secondary tabular-nums",children:jn(M.numHosts)})]},M.linkingDomain)),S.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-muted",colSpan:2,children:_>0&&p===0?`Every referring domain in this ${O} was a crawler/proxy host (${_} hidden).`:`No referring domains in this ${O}.`})})]})]})}),e.jsx(Tt,{page:y,pageSize:Bs,visibleRows:S.length,totalRows:p,onPageChange:M=>g((M-1)*Bs)})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:U})]})}}function zc({projectName:t}){const s=ve({...eo({client:V,path:{name:t}}),staleTime:si}),n=s.data??null,a=s.error;if(s.isLoading&&!n)return null;if(a)return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsx("h2",{children:"Citation + answer-mention coverage"})]})}),e.jsx("p",{className:"text-sm text-negative-400",children:a instanceof Error?a.message:String(a)})]});if(!n)return null;if(n.status==="no-data")return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsx("h2",{children:"Citation + answer-mention coverage"})]})}),e.jsx("p",{className:"text-sm text-muted",children:n.reason==="no-queries"?"Add queries to start tracking AI citations.":"Run a sweep to see which engines cite this project."})]});const{providersCiting:i,providersMentioning:r,providersConfigured:l}=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 ",l," engines",e.jsx($e,{text:"An engine is ‘citing’ when our domain appears in its grounding source list (the structured citation/search-result attribution it returns alongside the answer). Counts each configured engine that cites the project on at least one tracked query in the latest snapshot per (query × provider)."})]}),e.jsxs("p",{className:"text-base text-neutral flex items-center gap-2",children:["Mentioned in ",r," of ",l," engine answers",e.jsx($e,{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(Hc,{data:n}),e.jsx(Kc,{data:n}),n.competitorGaps.length>0&&e.jsx(Jc,{data:n})]})}function Hc({data:t}){const{totalQueries:s,queriesCitedAndMentioned:n,queriesCitedOnly:a,queriesMentionedOnly:i,queriesInvisible:r}=t.summary;return e.jsxs("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4 mb-4",children:[e.jsx(Us,{label:"Cited + mentioned",value:`${n} / ${s}`,helper:"In sources AND named in answer",tone:n>0?"positive":"neutral"}),e.jsx(Us,{label:"Cited only",value:`${a} / ${s}`,helper:"In sources, not named in answer",tone:a>0?"positive-dim":"neutral"}),e.jsx(Us,{label:"Mentioned only",value:`${i} / ${s}`,helper:"Named in answer, no source link",tone:i>0?"caution":"neutral"}),e.jsx(Us,{label:"Invisible",value:`${r} / ${s}`,helper:"No engine cites or mentions",tone:r>0?"negative":"neutral"})]})}function Us({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 Kc({data:t}){const s=o.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(Vc,{}),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(Kt,{provider:n})},n)),e.jsx("th",{className:"text-right",children:"Cite"}),e.jsx("th",{className:"text-right",children:"Ment"})]})}),e.jsx("tbody",{children:t.byQuery.map(n=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:n.query}),s.map(a=>{const i=n.providers.find(r=>r.provider===a);return e.jsx("td",{className:"text-center",children:i==null?e.jsx($l,{className:"inline h-3.5 w-3.5 text-mono-700","aria-label":"no data"}):e.jsx(Wc,{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 Vc(){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(Ut,{active:!0,tone:"cited"}),e.jsx("span",{children:"cited (in sources)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ut,{active:!0,tone:"mentioned"}),e.jsx("span",{children:"mentioned (in answer)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ut,{active:!1,tone:"cited"}),e.jsx(Ut,{active:!1,tone:"mentioned"}),e.jsx("span",{children:"neither"})]})]})}function Wc({provider:t}){const s=Yc(t);return e.jsxs("span",{className:"inline-flex items-center justify-center gap-1",title:s,children:[e.jsx(Ut,{active:t.cited,tone:"cited"}),e.jsx(Ut,{active:t.mentioned,tone:"mentioned"})]})}function Yc(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 Ut({active:t,tone:s}){if(!t)return e.jsx("span",{className:"inline-block h-2 w-2 rounded-full border border-strong bg-transparent","aria-hidden":"true"});const n=s==="cited"?"inline-block h-2 w-2 rounded-full bg-positive-400 shadow-[0_0_0_1px_rgba(16,185,129,0.25)]":"inline-block h-2 w-2 rounded-full bg-info-400 shadow-[0_0_0_1px_rgba(56,189,248,0.25)]";return e.jsx("span",{className:n,"aria-hidden":"true"})}function Jc({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($e,{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(Kt,{provider:s.provider})}),e.jsx("td",{className:"text-neutral",children:s.citingCompetitors.join(", ")})]},`${s.queryId}::${s.provider}`))})]})})]})}const ws="__cited__",Ss="__mentioned__",Ke="__mentionShare__";function Ai(t){const s=t,{dataStartDate:n,dataEndDate:a}=s;return typeof n!="string"||typeof a!="string"?null:{start:nt(n),end:nt(a),sweepCount:s.sweepCount??1}}function Js(t){const s=Ai(t);if(!s)return"Sweep date unavailable";const n=Ct(s.start),a=Ct(s.end);return n===a?n:`${n} – ${a} · ${s.sweepCount} sweeps combined`}function Xc(t){const s=Ai(t);return s?Qn(s.start):""}function ts(t){return t.trim().toLowerCase()}function En(t){return Math.round(t*1e3)/10}function On(t){return t.byProvider??{}}function Zc(t,s,n){const a=t.buckets.length>0,i=t.buckets.length===1;if(n==="overall"){const x=s==="cited"?ws:Ss,m=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(d=>({date:d.startDate,[x]:En(d[m])})),series:[x],hasData:a,singleBucket:i}}const r=s==="mentioned"?"mentionRate":"citationRate",l=[...new Set(t.buckets.flatMap(x=>Object.keys(On(x))))].sort();return{rows:t.buckets.map(x=>{const m={date:x.startDate},f=On(x);for(const d of l){const b=f[d];m[d]=b?En(b[r]):null}return m}),series:l,hasData:a,singleBucket:i}}function $i(t){const s=t;return Object.hasOwn(s,"modelEvidenceByProvider")?s.modelEvidenceByProvider??{}:null}function ed(t){const s=t;return Object.hasOwn(s,"modelAttribution")?s.modelAttribution??{}:null}function td(t){return t.servedModelAttribution??{}}function sd(t){return t.modelServiceMismatch??{}}function nd(t){return t.modelPointerChanges??{}}function ad(t){return t.length>0?t.join(", "):null}function Ta(t,s){const n=ts(s);return Object.entries(t).find(([a])=>ts(a)===n)?.[1]}function ut(t){switch(t.status){case"known":return t.model;case"unknown":return"Unknown model";case"mixed":return`Mixed: ${t.models.join(", ")}${t.includesUnknown?" + unknown":""}`}}function id(t,s){for(let n=t.length-1;n>=0;n-=1){const a=t[n];if(!Ta(On(a),s))continue;const i=$i(a);return i?Ta(i,s)??null:null}return null}function rd(t){const s=new Map;for(const[n,a]of Object.entries(t))for(const i of a.events){const r=s.get(i.bucketStartDate)??[];r.push({provider:n,event:i}),s.set(i.bucketStartDate,r)}return[...s.entries()].sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>({bucketStartDate:n,events:[...a].sort((i,r)=>i.provider.localeCompare(r.provider)||i.event.observedAt.localeCompare(r.event.observedAt))}))}function od(t){const s={},n=[];for(const[a,i]of Object.entries(t)){const r=i.events.filter(l=>!l.fromPreWindowAnchor);for(const l of i.events)l.fromPreWindowAnchor&&n.push({provider:a,event:l});r.length>0&&(s[a]={...i,events:r})}return{buckets:rd(s),beforeWindow:n.sort((a,i)=>a.event.observedAt.localeCompare(i.event.observedAt)||a.provider.localeCompare(i.provider))}}function ld(t){let s=0,n=0;for(const a of Object.values(t))s+=a.events.length,n+=a.eventTotal??a.events.length;return{shown:s,total:n}}function cd(t){const s=[];for(const[n,a]of Object.entries(t)){const i=a.eventTotal??a.events.length;i>a.events.length&&s.push({provider:n,shown:a.events.length,total:i})}return s.sort((n,a)=>n.provider.localeCompare(a.provider))}function dd(t){const s=t.buckets.map(a=>{const i=a.mentionShare;return{date:a.startDate,[Ke]:i?.rate==null?null:En(i.rate)}}),n=s.map(a=>a[Ke]).filter(a=>typeof a=="number"&&Number.isFinite(a));return{rows:s,series:[Ke],hasData:n.length>0,singleBucket:n.length===1}}function ud(t,s,n){return s==="mentionShare"?dd(t):Zc(t,s,n)}function Ma(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 Ea(t){const[,s,n]=t.slice(0,10).split("-");return!s||!n?t:`${s}/${n}`}function Oa(t){return t>0?`+${t}`:`${t}`}function md(t){if(t.length===0)return null;if(t.length<=2)return`Query set changed: ${t.map(n=>`${Oa(n.delta)} on ${Ea(n.date)}`).join(", ")}`;const s=[...t].sort((n,a)=>a.date.localeCompare(n.date))[0];return`Query set changed ${t.length} times (latest ${Oa(s.delta)} on ${Ea(s.date)})`}const xd=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],hd=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],pd=[{value:"mentioned",label:"Mentioned",description:"Your brand or domain appears in the answer text."},{value:"cited",label:"Cited",description:"Your domain appears in source or grounding links."},{value:"mentionShare",label:"Mention share",description:"Of all answer-text brand mentions for you and tracked competitors, the share that were you."}],Vn=Fe[2],gd="var(--chart-tooltip-bg)",fd={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",local:"Local"};function mt(t){const s=ts(t);return fd[s]??t.charAt(0).toUpperCase()+t.slice(1)}function St(t){return Math.round(t*10)/10}function bd(t){return t===ws||t===Ss||t===Ke}function Pi(t){return t===ws?"Cited":t===Ss?"Mentioned":t===Ke?"Mention share":mt(t)}function xs(t,s){return t===ws?ht.positive:t===Ss?Fe[1]:t===Ke?Vn:gl(ts(t),s)}function jd(t,s){for(const n of t){const a=n[s];if(typeof a=="number"&&Number.isFinite(a))return a}return null}function yd(t){return t.map(s=>s.trim().toLowerCase()).filter(Boolean).sort().join(`
|