@canonry/canonry 4.147.1 → 4.148.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.
Files changed (26) hide show
  1. package/assets/agent-workspace/skills/canonry/references/canonry-cli.md +2 -2
  2. package/assets/assets/{AuditHistoryPanel-BbEZ_0W9.js → AuditHistoryPanel-D5fRv5sF.js} +1 -1
  3. package/assets/assets/{BacklinksPage-B72RKxC-.js → BacklinksPage-CFdO1s1V.js} +1 -1
  4. package/assets/assets/{ChartPrimitives-Cf-jQ3c8.js → ChartPrimitives-BoB1RfNf.js} +1 -1
  5. package/assets/assets/{HistoryPage-C2U1kxKw.js → HistoryPage-YT2JCo2G.js} +1 -1
  6. package/assets/assets/{MeasurementPropertyPage-ltcSZ0tw.js → MeasurementPropertyPage-JDEzHX1H.js} +1 -1
  7. package/assets/assets/{ProjectPage-ZcGjsDlb.js → ProjectPage-B6t_j9tN.js} +1 -1
  8. package/assets/assets/{RunRow-DxO-zxCm.js → RunRow-yKrIU8zY.js} +1 -1
  9. package/assets/assets/{RunsPage-B1ON2nQC.js → RunsPage-DAeC6Ebm.js} +1 -1
  10. package/assets/assets/{SettingsPage-Cp0bHFHk.js → SettingsPage-8Z251PH0.js} +1 -1
  11. package/assets/assets/{TrafficPage-QzitDjhV.js → TrafficPage-DNJGp16_.js} +1 -1
  12. package/assets/assets/{TrafficSourceDetailPage-BjfFyG2y.js → TrafficSourceDetailPage-BuzdNFB8.js} +1 -1
  13. package/assets/assets/{arrow-left-DJ8ZwUlj.js → arrow-left-BrVL2J2e.js} +1 -1
  14. package/assets/assets/{extract-error-message-CX8ZNJ8S.js → extract-error-message-jd9FdYvE.js} +1 -1
  15. package/assets/assets/{index-DF8X6nM0.js → index-Bo0hzrG2.js} +38 -38
  16. package/assets/assets/{trash-2-UHAxuTT7.js → trash-2-lAIhBm6w.js} +1 -1
  17. package/assets/index.html +1 -1
  18. package/dist/{chunk-2NTWZHNF.js → chunk-3HYF3LUP.js} +1 -1
  19. package/dist/{chunk-BVOU4UJM.js → chunk-43XIYBG4.js} +8 -0
  20. package/dist/{chunk-GNKVF6TZ.js → chunk-MHTZ4THA.js} +4 -4
  21. package/dist/{chunk-ZRUNFIGA.js → chunk-VUTKHFTM.js} +16 -7
  22. package/dist/cli.js +13 -7
  23. package/dist/index.js +4 -4
  24. package/dist/{intelligence-service-2E5YAXI3.js → intelligence-service-OGOGIQJD.js} +2 -2
  25. package/dist/mcp.js +2 -2
  26. package/package.json +8 -8
@@ -1,4 +1,4 @@
1
- import{j as e,r as l,L as Ut,o as as,u as Le,p as tn,B as Wr,C as al,k as rl,l as il,D as ll}from"./vendor-tanstack-BjS7iY3g.js";import{c as ln,T as oe,t as ol,a as cl,S as dl,X as ul,C as Aa,u as Yr,b as ml,P as Is,B as k,h as hl,d as xl,e as pl,f as me,i as Z,g as it,j as Ie,I as Ze,k as zs,l as gl,m as Q,n as fl,o as bl,p as jl,q as yl,r as Jr,s as vl,v as Nl,w as xs,x as wl,y as Sl,z as ms,A as _t,D as Cl,E as tr,F as Xr,G as ct,H as Ra,J as kl,K as Pl,L as Al,M as Rl,N as sr,O as Ne,Q as Zr,R as $l,U as Vn,V as Il,W as Ll,Y as Ml,Z as Tl,_ as Dl,$ as El,a0 as ql,a1 as Ol,a2 as Fl,a3 as _l,a4 as Ul,a5 as Gl,a6 as Bl,a7 as zl,a8 as Vl,a9 as Kl,aa as bs,ab as Ql,ac as ei,ad as $n,ae as Hl,af as Wl,ag as Yl,ah as Jl,ai as In,aj as Xl,ak as Zl,al as eo,am as Ls,an as to,ao as so,ap as ga,aq as no,ar as ao,as as Ms,at as ti,au as si,av as ro,aw as ni,ax as io,ay as lo,az as oo,aA as co,aB as ai,aC as uo,aD as mo,aE as ho,aF as Js,aG as ps,aH as xo,aI as po,aJ as go,aK as fo,aL as ri,aM as bo,aN as jo,aO as yo,aP as vo,aQ as No,aR as ii,aS as wo,aT as $a,aU as So,aV as Co,aW as ko,aX as We,aY as Po,aZ as Ao,a_ as Ro,a$ as $o,b0 as Io,b1 as Lo,b2 as Mo,b3 as To,b4 as Do,b5 as Eo,b6 as qo,b7 as Oo,b8 as Fo,b9 as _o,ba as Uo,bb as Go,bc as Bo,bd as zo,be as Vo,bf as Ko,bg as Qo,bh as Ho,bi as Wo,bj as Yo,bk as Jo,bl as Xo,bm as Zo,bn as ec,bo as tc,bp as sc,bq as nc,br as ac,bs as rc,bt as ic,bu as lc,bv as oc,bw as cc,bx as dc,by as Kn,bz as uc,bA as mc,bB as nr,bC as hc,bD as xc,bE as pc,bF as gc,bG as fc,bH as bc,bI as jc,bJ as yc,bK as vc,bL as Nc,bM as wc,bN as Sc,bO as Cc,bP as li,bQ as kc,bR as Pc,bS as Ac,bT as Rc,bU as $c,bV as Ic,bW as ar,bX as Lc,bY as Qn,bZ as ft,b_ as Mc,b$ as Tc,c0 as Dc,c1 as Ec,c2 as qc,c3 as Oc,c4 as Fc,c5 as _c,c6 as oi,c7 as ci,c8 as Uc,c9 as di,ca as Gc,cb as ui,cc as Bc,cd as zc,ce as fn,cf as Vc,cg as Kc,ch as Qc,ci as rr}from"./index-DF8X6nM0.js";import{R as Hc}from"./RunRow-DxO-zxCm.js";import{C as Wc,R as sn,f as fa,a as Ht,b as Lt,c as Ln,d as gs,e as gt,g as pt,h as Qt,i as Ia,j as La,k as ns,o as Gt,p as Yc}from"./ChartPrimitives-Cf-jQ3c8.js";import{u as Jc,t as Xc,e as Zc,a as ir}from"./extract-error-message-CX8ZNJ8S.js";import{R as Ts,C as Ds,X as Es,Y as qs,T as Os,L as mi,A as ks,a as Ma,b as ed,d as Ta,e as td}from"./vendor-recharts-33ACLxsD.js";import{D as hi,C as sd,E as nd,T as ad}from"./trash-2-UHAxuTT7.js";import{A as rd}from"./AuditHistoryPanel-BbEZ_0W9.js";import{a as id,b as ld}from"./v2-overview-adapter-BHmxTmCf.js";import"./vendor-radix-DnzzbllM.js";import"./vendor-markdown-CpDJch4G.js";const od=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],xi=ln("circle-check",od);const cd=[["path",{d:"M5 12h14",key:"1ays0h"}]],dd=ln("minus",cd);const ud=[["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"}]],md=ln("scan-search",ud);const hd=[["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"}]],xd=ln("unplug",hd);const pd=[["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"}]],gd=ln("upload",pd);function An(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 fd(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} (${An(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${An(t.prior)} ${s})`:`Flat ${n} (${An(t.prior)} ${s})`}const pi=30;function lr(t){return Math.round(t*10)/10}function bd(t){return t.prior>=pi&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% vs prior`:`${t.deltaAbs>0?"+":""}${lr(t.deltaAbs)} vs ${lr(t.prior)}`}function jd(t,s,n){return t.prior>=pi&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% ${n}`:`${t.deltaAbs>0?"+":""}${An(Math.round(t.deltaAbs))} ${s} ${n}`}const yd=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function gi(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function fi(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 bi(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(gi).map(fi).filter(Boolean)):new Set}function ji(t,s){const n=gi(t).map(fi).filter(Boolean).filter(a=>!yd.has(a)).filter(a=>!s.has(a));return[...new Set(n)].sort().join(" ")}function vd(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function Nd(t,s){const n=bi(t);if(s.length<=1||n.size===0)return[...s];const a=new Set,r=[];for(const i of s){if(i.category!=="content"){r.push(i);continue}const o=ji(vd(i),n);!o||a.has(o)||(a.add(o),r.push(i))}return r}function wd(t){const s=bi(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const a=new Set;return n.filter(r=>{const i=ji(r.query,s);return!i||a.has(i)?!1:(a.add(i),!0)})}function ba({state:t,label:s}){return e.jsx(oe,{tone:cl(t),children:s??ol(t)})}const Et=25;function Sd(t){return t.trim().toLocaleLowerCase().split(/\s+/).filter(Boolean)}function yi(t){let s=t;try{s=decodeURIComponent(t.replace(/\+/g," "))}catch{}let n="";const a=t.indexOf("?");return a>=0&&new URLSearchParams(t.slice(a+1)).forEach((i,o)=>{n+=` ${o} ${i}`}),`${t} ${s}${n}`}function Cd(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 Xs({value:t,headLength:s,tailLength:n,className:a,title:r}){const i=Cd(t,s,n);return e.jsx("span",{className:a,title:r??t,children:i===t?t:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"sr-only",children:t}),e.jsx("span",{"aria-hidden":"true",children:i})]})})}function nn({rows:t,getSearchText:s,pageSize:n=Et}){const[a,r]=l.useState(""),[i,o]=l.useState(1),u=l.useMemo(()=>Sd(a),[a]),d=l.useMemo(()=>u.length===0||!s?t:t.filter(b=>{const p=s(b).toLocaleLowerCase();return u.every(L=>p.includes(L))}),[s,t,u]),h=Math.max(1,Math.ceil(d.length/n)),x=Math.min(Math.max(1,i),h),c=(x-1)*n,y=l.useMemo(()=>d.slice(c,c+n),[d,n,c]),N=l.useCallback(b=>{r(b),o(1)},[]),f=l.useCallback(b=>{o(Math.max(1,b))},[]);return{query:a,setQuery:N,page:x,setPage:f,rows:y,filteredRows:d,totalRows:d.length,totalPages:h,pageSize:n,rangeStart:d.length===0?0:c+1,rangeEnd:c+y.length,hasQuery:a.trim().length>0}}function As({value:t,onChange:s,label:n,placeholder:a="Filter rows",className:r}){return e.jsxs("div",{className:`relative ${r??""}`,children:[e.jsx(dl,{"aria-hidden":"true",className:"pointer-events-none absolute left-3 top-1/2 size-3.5 -translate-y-1/2 text-muted"}),e.jsx("input",{type:"search",value:t,onChange:i=>s(i.target.value),"aria-label":n,placeholder:a,autoComplete:"off",spellCheck:!1,className:"h-9 w-full rounded-md border border-default bg-surface/50 pl-9 pr-9 text-sm text-strong placeholder:text-muted outline-none transition focus:border-mono-500 focus:ring-1 focus:ring-mono-500 [&::-webkit-search-cancel-button]:appearance-none"}),t.trim().length>0?e.jsx("button",{type:"button",onClick:()=>s(""),"aria-label":`Clear ${n.toLocaleLowerCase()}`,className:"absolute right-2 top-1/2 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded text-muted transition-colors hover:bg-surface-hover hover:text-strong focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",children:e.jsx(ul,{"aria-hidden":"true",className:"size-3.5"})}):null]})}function fs({page:t,pageSize:s=Et,visibleRows:n,totalRows:a,hasNextPage:r,onPageChange:i,itemLabel:o="rows",className:u,disabled:d=!1}){if(n===0)return null;const h=(t-1)*s+1,x=h+n-1,c=a===void 0?void 0:Math.max(1,Math.ceil(a/s)),y=r??(c!==void 0&&t<c),N=t>1||y;return e.jsxs("div",{className:`mt-3 flex flex-wrap items-center justify-between gap-x-4 gap-y-2 text-xs text-secondary ${u??""}`,children:[e.jsxs("p",{className:"tabular-nums",children:[h.toLocaleString("en-US"),"–",x.toLocaleString("en-US"),a===void 0?`${y?"+":""} ${o}`:` of ${a.toLocaleString("en-US")} ${o}`]}),N?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>i(t-1),disabled:d||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(Wc,{"aria-hidden":"true",className:"size-3.5"}),"Previous"]}),e.jsx("span",{className:"tabular-nums",children:c===void 0?`Page ${t}`:`Page ${t} of ${c}`}),e.jsxs("button",{type:"button",onClick:()=>i(t+1),disabled:d||!y,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(Aa,{"aria-hidden":"true",className:"size-3.5"})]})]}):null]})}function or({history:t,maxDots:s=12}){const n=t.slice(-s);if(n.length===0)return e.jsx("span",{className:"text-[11px] text-faint",children:"No data"});const a={cited:"bg-positive-400","not-cited":"bg-mono-600",lost:"bg-negative-400",emerging:"bg-caution-400 ring-1 ring-caution-300/60"},r={cited:"rounded-full","not-cited":"rounded-sm",lost:"rotate-45 rounded-[1px]",emerging:"rounded-full"},i=n.length-1,o=new Date(n[0].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),u=new Date(n[i].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),d=n.map((h,x)=>{const c=new Date(h.createdAt).toLocaleDateString();return`${x===i?"Latest run, ":""}${c}: ${h.citationState}${h.model?`, model ${h.model}`:""}`}).join("; ");return e.jsxs("div",{className:"flex items-center gap-1",role:"img","aria-label":`Citation history across ${n.length} runs. ${d}`,children:[e.jsx("span",{className:"text-[9px] text-faint shrink-0","aria-hidden":"true",children:o}),e.jsx("div",{className:"flex items-center gap-[3px]",title:`${n.length} runs`,"aria-hidden":"true",children:n.map((h,x)=>{const c=!!(h.model&&x>0&&n[x-1]?.model&&n[x-1].model!==h.model),y=x===i;return e.jsx("span",{className:`h-2.5 w-2.5 ${r[h.citationState]??"rounded-sm"} ${a[h.citationState]??"bg-mono-700"} ${c?"ring-1 ring-caution-300/80 ring-offset-1 ring-offset-bg":""} ${y?"outline outline-1 outline-offset-2 outline-mono-400":""}`,title:[h.citationState,new Date(h.createdAt).toLocaleDateString(),h.model?`model ${h.model}`:null,c?"model changed":null,y?"latest run":null].filter(Boolean).join(" · ")},`${h.runId}:${h.createdAt}`)})}),e.jsxs("span",{className:"text-[9px] shrink-0 text-secondary","aria-hidden":"true",children:[u," ",e.jsx("span",{className:"text-faint",children:"latest"})]})]})}function ja(t){const s=new Map;for(const a of t)for(const r of a.runHistory){const i=s.get(r.createdAt);i?i.states.push(r.citationState):s.set(r.createdAt,{states:[r.citationState],runId:r.runId})}return[...s.entries()].sort(([a],[r])=>a.localeCompare(r)).map(([a,{states:r,runId:i}])=>({runId:i,createdAt:a,citationState:r.includes("cited")?"cited":r.includes("emerging")?"emerging":"not-cited"}))}const kd=320;function Pd(t){return[t.phrase,t.location??"",...t.rawItems.map(s=>s.provider)].join(" ")}function cr(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 dr(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 ur(t,s){const n=s==="mentions"?"mentioned":"cited",a=s==="mentions"?"Mentioned":"Cited";if(t.length===0)return"Awaiting first run";if(t.length===1)return"First observation";const r=t[t.length-1].citationState,i=t[t.length-2].citationState;if(i!=="cited"&&r==="cited")return`Newly ${n}`;if(i==="cited"&&r!=="cited")return"Lost since last run";let o=0;for(let u=t.length-1;u>=0&&t[u].citationState===r;u--)o++;return r==="cited"?o<=1?`${a} in latest run`:`${a} for ${o} runs`:o<=1?`Not ${n} in latest run`:`Not ${n} across ${o} runs`}function Ad(t,s){return t.map(n=>vi(n,s))}function vi(t,s){return s==="citations"?t:{...t,citationState:cr(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:cr(n,s)}))}}function mr(t,s){const n=s==="mentions"?"mention":"citation",a=s==="mentions"?"Mention":"Citation";if(t.length===0)return{key:s,label:`${a} pending`,tone:"pending"};const r=t[t.length-1].citationState,i=t.length>=2?t[t.length-2].citationState:null,o=r==="cited"||r==="emerging",u=i==="cited"||i==="emerging";return r==="lost"||i!==null&&u&&!o?{key:s,label:`Lost ${n}`,tone:"negative"}:r==="emerging"||i!==null&&!u&&o?{key:s,label:`New ${n}`,tone:"positive"}:i===null&&o?{key:s,label:`First ${n}`,tone:"positive"}:o?{key:s,label:s==="mentions"?"Still mentioned":"Still cited",tone:"neutral"}:{key:s,label:`No ${n}`,tone:"neutral"}}function Rd(t){const s=ja(Ad(t,"mentions")),n=ja(t);return[mr(s,"mentions"),mr(n,"citations")]}function $d({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 hr({items:t}){return e.jsx("div",{className:"mt-1 flex flex-wrap gap-1","aria-label":"Latest run mention and citation signals",children:Rd(t).map(s=>e.jsx($d,{signal:s},s.key))})}function Id({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:a}=Yr(),[r,i]=l.useState(new Set),[o,u]=l.useState("mentions"),[d,h]=l.useState(n),x=l.useMemo(()=>{const E=new Map;for(const q of t){const $=q.query,g=s?q.location??null:null,v=s?JSON.stringify([$,g]):$,w=E.get(v)??{key:v,phrase:$,location:g,items:[],rawItems:[]};w.items.push(vi(q,o)),w.rawItems.push(q),E.set(v,w)}return[...E.values()]},[t,o,s]),c=nn({rows:x,getSearchText:Pd}),y=c.rows.map(E=>E.key),N=y.length>0&&y.every(E=>r.has(E)),f=E=>{i(q=>{const $=new Set(q);return $.has(E)?$.delete(E):$.add(E),$})},b=o==="mentions"?"mentioned":"cited",p=o==="mentions"?"Mention History":"Citation History",L=o==="mentions"?"mentioned":"cited";return e.jsxs("div",{children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"View by"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-bg-elevated/60 border border-subtle",role:"tablist","aria-label":"Citation tracking view",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":o==="mentions",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${o==="mentions"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>u("mentions"),children:"Mentions"}),e.jsx("button",{type:"button",role:"tab","aria-selected":o==="citations",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${o==="citations"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>u("citations"),children:"Citations"})]}),e.jsx("span",{className:"text-[11px] text-muted",children:o==="mentions"?"Brand or domain in answer text":"Brand or domain in source links"}),e.jsxs("div",{className:"ml-auto flex items-center gap-3",children:[e.jsx("button",{type:"button",className:"text-[11px] text-secondary hover:text-strong",onClick:()=>{i(E=>{const q=new Set(E);for(const $ of y)N?q.delete($):q.add($);return q})},children:N?"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":d==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${d==="compact"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>h("compact"),children:"Compact"}),e.jsx("button",{type:"button",role:"tab","aria-selected":d==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${d==="detailed"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>h("detailed"),children:"Detailed"})]})]})]})]}),x.length>0?e.jsx(As,{value:c.query,onChange:c.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:p}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:c.rows.map(({key:E,phrase:q,location:$,items:g,rawItems:v})=>{const w=r.has(E),ee=g.map(S=>S.citationState),W=ee.includes("cited")?"cited":ee.includes("emerging")?"emerging":ee.includes("lost")?"lost":ee.every(S=>S==="pending")?"pending":"not-cited",A=ja(g),j=g.filter(S=>S.citationState===ml.cited||S.citationState==="emerging").length,D=ur(A,o);return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"cursor-pointer hover:bg-mono-800/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>f(E),onKeyDown:S=>{(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),f(E))},tabIndex:0,role:"button","aria-expanded":w,children:[e.jsx("td",{children:e.jsx(Aa,{size:14,className:`transition-transform duration-150 text-muted ${w?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-heading",children:q}),s&&e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-muted",children:$??"No location"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:g.map(S=>e.jsx(Is,{provider:S.provider},S.id))})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ba,{state:W,label:dr(W,o)}),e.jsxs("span",{className:"text-[11px] text-muted",title:`${j} of ${g.length} engines ${L}`,children:[j,"/",g.length]})]})}),e.jsx("td",{children:e.jsx(or,{history:A})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:D}),e.jsx(hr,{items:v})]}),e.jsx("td",{})]}),w&&g.map((S,V)=>e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"bg-surface",children:[e.jsx("td",{}),e.jsx("td",{className:"evidence-query-cell pl-5",children:e.jsx(Is,{provider:S.provider})}),e.jsx("td",{children:e.jsx(ba,{state:S.citationState,label:dr(S.citationState,o)})}),e.jsx("td",{children:e.jsx(or,{history:S.runHistory})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:ur(S.runHistory,o)}),e.jsx(hr,{items:[v[V]??S]})]}),e.jsx("td",{children:e.jsx(k,{variant:"ghost",size:"sm",type:"button",onClick:pe=>{pe.stopPropagation(),a(S.id)},children:"View"})})]}),d==="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(Td,{item:S,onViewFull:()=>a(S.id)})})]})]},S.id))]},E)})})]})}),c.totalRows===0&&c.hasQuery?e.jsx("p",{className:"supporting-copy mt-3",children:"No tracked queries match this filter."}):null,e.jsx(fs,{page:c.page,pageSize:c.pageSize,visibleRows:c.rows.length,totalRows:c.totalRows,onPageChange:c.setPage,itemLabel:c.hasQuery?"matches":"queries"}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",b==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function Ld(t){const s=(t.matchedTerms??[]).filter(r=>r.trim().length>2),n=[...t.competitorDomains.flatMap(r=>{const i=xl(r);return i.length>=4?[i]:[]}),...t.recommendedCompetitors??[]].filter(r=>r.trim().length>2),a=[];return s.length>0&&a.push({terms:s,className:"answer-highlight-brand"}),n.length>0&&a.push({terms:n,className:"answer-highlight-competitor"}),a}function Md(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 Td({item:t,onViewFull:s}){if(!(t.answerSnippet.trim().length>0))return e.jsx("p",{className:"text-[11px] text-muted italic",children:"No answer text captured for this run."});const{body:a,truncated:r}=Md(t.answerSnippet,kd),i=Ld(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:hl(a,i)}),(t.citedDomains.length>0||t.competitorDomains.length>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[t.citedDomains.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Cited:"}),t.citedDomains.slice(0,6).map(o=>e.jsx("span",{className:"rounded-full border border-mono-700/60 bg-bg-elevated/60 px-2 py-0.5 text-[11px] text-neutral",children:o},`c-${o}`)),t.citedDomains.length>6&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.citedDomains.length-6," more"]})]}),t.competitorDomains.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-negative-500/80",children:"Competitors:"}),t.competitorDomains.slice(0,4).map(o=>e.jsx("span",{className:"rounded-full border border-negative-900/40 bg-negative-950/30 px-2 py-0.5 text-[11px] text-negative",children:o},`co-${o}`)),t.competitorDomains.length>4&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.competitorDomains.length-4," more"]})]})]}),r&&e.jsx("button",{type:"button",className:"text-[11px] font-medium text-positive-400 hover:text-positive",onClick:o=>{o.stopPropagation(),s()},children:"View full answer →"})]})}function Dd({competitors:t,onSelectCompetitor:s,onRemoveCompetitor:n,activeFilter:a}){if(t.length===0)return e.jsx("p",{className:"text-sm text-muted",children:"No competitors configured. Add competitors to track overlap."});const r=s!=null,i=n!=null;return e.jsx("div",{className:"competitor-table-wrap",children:e.jsxs("table",{className:"competitor-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Domain"}),e.jsx("th",{children:"Pressure"}),e.jsx("th",{children:"Citations"}),e.jsx("th",{children:"Queries"}),i&&e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{children:t.map(o=>{const u=a!=null&&a.toLowerCase()===o.domain.toLowerCase(),d=[r?"cursor-pointer hover:bg-mono-800/30 transition-colors":"",u?"bg-negative-950/20":""].filter(Boolean).join(" ");return e.jsxs("tr",{className:d,onClick:r?()=>s(o.domain):void 0,title:r?`Filter answers to queries where ${o.domain} surfaced`:void 0,children:[e.jsx("td",{className:"font-medium text-heading",children:o.domain}),e.jsx("td",{children:e.jsx(oe,{tone:pl(o.pressureLabel),children:o.pressureLabel})}),e.jsx("td",{className:"text-neutral tabular-nums",children:o.totalQueries>0?`${o.citationCount} / ${o.totalQueries}`:"—"}),e.jsx("td",{className:"text-muted text-xs",children:o.citedQueries.length>0?o.citedQueries.join(", "):"Not cited"}),i&&e.jsx("td",{className:"text-right",children:e.jsx("button",{type:"button",className:"rounded px-1.5 py-0.5 text-xs text-muted transition-colors hover:text-negative-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-negative-500","aria-label":`Remove competitor ${o.domain}`,title:`Remove ${o.domain}`,onClick:h=>{h.stopPropagation(),n(o.domain)},children:"Remove"})})]},o.id)})})]})})}function bn({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 Ed=6,Fs="__other__",Rs="_socialTotal";function qd(t,s=Ed){const n=new Map;for(const x of t)n.set(x.source,(n.get(x.source)??0)+x.sessions);const a=[...n.entries()].sort((x,c)=>c[1]!==x[1]?c[1]-x[1]:x[0].localeCompare(c[0])),r=a.slice(0,s),i=new Set(r.map(([x])=>x)),o=Math.max(0,a.length-s),u=new Map;for(const x of t){let c=u.get(x.date);c||(c={date:x.date,[Rs]:0},u.set(x.date,c));const y=i.has(x.source)?x.source:Fs;c[y]=(c[y]??0)+x.sessions,c[Rs]=(c[Rs]??0)+x.sessions}const d=[...u.values()].sort((x,c)=>String(x.date).localeCompare(String(c.date))),h=r.map(([x])=>x);return o>0&&h.push(Fs),{data:d,sources:h,otherCount:o}}function $s(t){return t.replace(/\+/g," ")}function Ni(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const xr="_totalSessions",pr="_organicSessions";function Od(t,s){const n=new Map;for(const o of s)n.set(o.date,{[xr]:o.sessions,[pr]:o.organicSessions});for(const o of t.days){let u=n.get(o.date);u||(u={[xr]:0,[pr]:0},n.set(o.date,u));for(const d of o.bySource)u[d.source]=(u[d.source]??0)+d.sessions}const a=[...n.entries()].sort(([o],[u])=>o.localeCompare(u)).map(([o,u])=>({date:o,...u})),r=a.map(o=>o.date),i=r.length>0?{start:r[0],end:r[r.length-1]}:null;return{data:a,sources:t.sources,dateRange:i}}const Fd=["7d","30d","90d","all"],es=pt,ya=gt.textDim,wi=gt.textFaint,Vs=25;function _d(t){return yi(t.landingPage)}const Ud=25,Wn={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0};function jn(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function Si(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 Gd({projectName:t}){const{data:s,isLoading:n,isError:a}=Jc(t);if(n)return e.jsx(me,{className:"p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading server activity…"})});if(a)return e.jsx(me,{className:"p-5",children:e.jsx("div",{className:"text-sm text-negative-400",children:"Failed to load server activity."})});const r=s?.sources??[];return e.jsxs("section",{children:[e.jsx("div",{className:"flex items-baseline justify-between mb-3",children:e.jsxs("div",{children:[e.jsx("div",{className:"eyebrow",children:"Server activity (last 24h)"}),e.jsx("h2",{className:"text-lg font-semibold text-primary",children:"Server activity"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["Crawler, AI fetch, and referral activity from connected sources."," ",!Z()&&e.jsx(Ut,{to:"/traffic",className:"text-link hover:underline",children:"Manage sources →"})]})]})}),r.length===0?e.jsx(me,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-secondary",children:["No server traffic source connected yet."," ",!Z()&&e.jsxs(e.Fragment,{children:[e.jsx(Ut,{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(me,{className:"overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-bg-elevated/50 text-[10px] uppercase tracking-wide text-muted",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Source"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Status"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Crawler hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI sessions 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Last sync"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium","aria-label":"open"})]})}),e.jsx("tbody",{children:r.map(i=>e.jsxs("tr",{className:"border-t border-default",children:[e.jsx("td",{className:"px-4 py-3 text-heading",children:i.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(oe,{tone:Xc(i.status),children:i.status})}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:i.totals24h.crawlerHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:i.totals24h.aiUserFetchHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:i.totals24h.aiReferralHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right text-secondary text-xs",children:i.lastSyncedAt?Si(i.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:Z()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(Ut,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:i.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},i.id))})]})})]})}function Bd({projectName:t}){return e.jsxs("div",{className:"space-y-10",children:[e.jsx(Gd,{projectName:t}),e.jsx(zd,{projectName:t})]})}function zd({projectName:t}){const s=as(),[n,a]=l.useState(null),[r,i]=l.useState(null),[o,u]=l.useState(!0),[d,h]=l.useState(!1),[x,c]=l.useState(!1),[y,N]=l.useState(null),[f,b]=l.useState(null),[p,L]=l.useState("sessions"),[E,q]=l.useState("desc"),[$,g]=l.useState("sessions"),[v,w]=l.useState("desc"),[ee,W]=l.useState("sessions"),[A,j]=l.useState("desc"),[D,S]=l.useState("sessions"),[V,pe]=l.useState("desc"),[ne,X]=l.useState(Wn),[te,ce]=l.useState([]),[B,G]=l.useState([]),[P,re]=l.useState(!1),[le,C]=l.useState("30d");async function U(F){u(!0),N(null);try{const Ce=await s.fetchQuery({...gl({client:Q,path:{name:t}}),staleTime:zs});if(F.current)return;if(a(Ce),!Ce.connected){i(null),X(Wn),ce([]),G([]),u(!1);return}const de=le==="all"?void 0:le,[ve,Ke,Wt,st]=await Promise.all([s.fetchQuery({...fl({client:Q,path:{name:t},query:de?{window:de}:void 0}),staleTime:zs}).then(kt=>kt),s.fetchQuery({...bl({client:Q,path:{name:t},query:de?{window:de}:void 0}),staleTime:zs}).catch(()=>Wn),s.fetchQuery({...jl({client:Q,path:{name:t},query:de?{window:de}:void 0}),staleTime:zs}).catch(()=>[]),s.fetchQuery({...yl({client:Q,path:{name:t},query:de?{window:de}:void 0}),staleTime:zs}).catch(()=>[])]);if(F.current)return;i(ve),X(Ke),ce(Wt),G(st),u(!1)}catch(Ce){if(F.current)return;N(Ce instanceof Error?Ce.message:"Failed to load GA4 data"),u(!1)}}l.useEffect(()=>{const F={current:!1};return U(F),()=>{F.current=!0}},[t,le,s]);async function se(){h(!0),N(null),b(null);try{const F=await Jr(t);b(`Synced ${F.rowCount.toLocaleString()} page rows, ${F.aiReferralCount.toLocaleString()} AI and ${F.socialReferralCount.toLocaleString()} social referral rows (${F.days} days)`),await it(s,"ga"),await U({current:!1})}catch(F){N(F instanceof Error?F.message:"Sync failed")}finally{h(!1)}}async function M(){c(!0),N(null),b(null);try{await vl(t),await it(s,"ga"),a({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),i(null),b("GA4 disconnected")}catch(F){N(F instanceof Error?F.message:"Disconnect failed")}finally{c(!1)}}function z(F){p===F?q(Ce=>Ce==="desc"?"asc":"desc"):(L(F),q("desc"))}function we(F){$===F?w(Ce=>Ce==="desc"?"asc":"desc"):(g(F),w("desc"))}function Oe(F){ee===F?j(Ce=>Ce==="desc"?"asc":"desc"):(W(F),j("desc"))}const K=l.useMemo(()=>r?.topPages?[...r.topPages].sort((F,Ce)=>{const de=F[p],ve=Ce[p];return typeof de=="string"&&typeof ve=="string"?E==="asc"?de.localeCompare(ve):ve.localeCompare(de):E==="asc"?de-ve:ve-de}):[],[r?.topPages,p,E]),ge=l.useMemo(()=>r?.aiReferrals?[...r.aiReferrals].sort((F,Ce)=>{const de=F[$],ve=Ce[$];return typeof de=="string"&&typeof ve=="string"?v==="asc"?de.localeCompare(ve):ve.localeCompare(de):v==="asc"?de-ve:ve-de}):[],[r?.aiReferrals,$,v]),Te=l.useMemo(()=>r?.aiReferralLandingPages?[...r.aiReferralLandingPages].sort((F,Ce)=>{const de=F[D],ve=Ce[D];return typeof de=="string"&&typeof ve=="string"?V==="asc"?de.localeCompare(ve):ve.localeCompare(de):V==="asc"?de-ve:ve-de}):[],[r?.aiReferralLandingPages,D,V]),je=nn({rows:Te,getSearchText:_d,pageSize:Ud}),Be=je.totalRows>0?`${je.totalRows.toLocaleString()} ${je.hasQuery?je.totalRows===1?"match":"matches":je.totalRows===1?"row":"rows"}`:je.hasQuery&&(r?.aiReferralLandingPages.length??0)>0?"0 matches":"No landing-page rows";function et(F){je.setPage(1),D===F?pe(Ce=>Ce==="desc"?"asc":"desc"):(S(F),pe("desc"))}const Me=l.useMemo(()=>r?.socialReferrals?[...r.socialReferrals].sort((F,Ce)=>{const de=F[ee],ve=Ce[ee];return typeof de=="string"&&typeof ve=="string"?A==="asc"?de.localeCompare(ve):ve.localeCompare(de):A==="asc"?de-ve:ve-de}):[],[r?.socialReferrals,ee,A]),{socialChartData:J,socialChartSources:De,socialOtherCount:xe}=l.useMemo(()=>{const F=qd(B);return{socialChartData:F.data,socialChartSources:F.sources,socialOtherCount:F.otherCount}},[B]),{chartData:Qe,chartSources:O,dateRange:_}=l.useMemo(()=>{const F=Od(ne,te);return{chartData:F.data,chartSources:F.sources,dateRange:F.dateRange}},[ne,te]);if(o&&!n)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!n?.connected)return Z()?e.jsx(me,{className:"p-5",children:e.jsx("div",{className:"text-sm text-secondary",children:"No Google Analytics 4 property connected yet."})}):e.jsx(Vd,{projectName:t,onConnected:()=>{(async()=>(await it(s,"ga"),await U({current:!1})))()}});const fe=r?.organicSharePctDisplay??"0%",Ee=r?.channelBreakdown?.organic.sharePctDisplay??fe,Ue=r?.channelBreakdown?.organic.sessions??r?.totalOrganicSessions??0,Ve=r?.aiSessionsDeduped??0,Nt=r?.channelBreakdown?.ai.sessions??r?.aiSessionsBySession??0,bt=r?.channelBreakdown?.ai.sharePctDisplay??r?.aiSharePctBySessionDisplay??"0%",ke=r?.paidAiSessionsBySession??0,Fe=r?.paidAiSharePctBySessionDisplay??"0%",qt=r?new Set(r.aiReferrals.map(F=>F.source.toLowerCase())).size:0,tt=ge[0]??null,dt=r?.totalDirectSessions??0,Ye=r?.directSharePctDisplay??"0%",wt=r?.channelBreakdown?.direct.sessions??dt,St=r?.channelBreakdown?.direct.sharePctDisplay??Ye,Re=r?.channelBreakdown?.other.sessions??r?.otherSessions??0,Ae=r?.channelBreakdown?.other.sharePctDisplay??r?.otherSharePctDisplay??"0%",lt=r?.socialSessions??0,Ge=r?.socialSharePctDisplay??"0%",Ot=r?.channelBreakdown?.social.sessions??lt,Ct=r?.channelBreakdown?.social.sharePctDisplay??Ge,Je=r?new Set(r.socialReferrals.map(F=>F.source.toLowerCase())).size:0,He=Me[0]??null;return e.jsxs(e.Fragment,{children:[y&&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:y}),f&&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:f}),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})]})]})]}),!Z()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(k,{variant:"outline",size:"sm",disabled:d,onClick:Ie(se),children:[e.jsx(sn,{className:`w-3.5 h-3.5 mr-1.5 ${d?"animate-spin":""}`}),d?"Syncing…":"Sync"]}),e.jsxs(k,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:x,onClick:Ie(M),children:[e.jsx(xd,{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(Ze,{text:`Aggregated traffic metrics from Google Analytics 4. Sessions and users are summed across the selected period.${r?.periodStart&&r?.periodEnd?` Data available: ${new Date(r.periodStart+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})} – ${new Date(r.periodEnd+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}.`:""} Organic sessions are Google organic search sessions specifically.`})]})]}),e.jsx("div",{className:"segmented",role:"group","aria-label":"Traffic time period",children:Fd.map(F=>e.jsx("button",{type:"button","aria-pressed":le===F,className:`segmented-option ${le===F?"segmented-option-active":""}`,onClick:()=>C(F),children:F==="all"?"All":F},F))})]}),r?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(Yn,{value:jn(r.totalSessions),label:"Total Sessions",subtitle:r.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(Yn,{value:jn(r.totalOrganicSessions),label:"Organic Sessions",subtitle:`${fe} of total`,tone:"positive"}),e.jsx(Yn,{value:jn(r.totalUsers),label:"Total Users",subtitle:r.totalUsers.toLocaleString(),tone:"neutral"})]}):e.jsxs("div",{className:"surface-card rounded-lg p-6 text-center border border-default",children:[e.jsx("p",{className:"text-sm text-secondary mb-3",children:"No traffic data yet."}),!Z()&&e.jsxs(k,{variant:"outline",size:"sm",disabled:d,onClick:Ie(se),children:[e.jsx(sn,{className:`w-3.5 h-3.5 mr-1.5 ${d?"animate-spin":""}`}),"Sync from GA4"]})]})]}),r&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Traffic Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Traffic by channel",e.jsx(Ze,{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."})]})]}),_&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(_.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(_.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),Qe.length>0&&e.jsxs(me,{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:O.length>0?"AI vs. total sessions":"All sessions (baseline)"}),O.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),O.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(Ts,{width:"100%",height:"100%",children:e.jsxs(Ds,{data:Qe,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Es,{dataKey:"date",tick:Lt,tickLine:!1,axisLine:{stroke:Ht},tickFormatter:fa}),e.jsx(qs,{tick:Lt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Os,{...gs,labelFormatter:Ln,formatter:(F,Ce)=>{const de=typeof F=="number"?F.toLocaleString():String(F??0),ve=String(Ce??"");return ve==="_totalSessions"?[de,"Total Sessions"]:ve==="_organicSessions"?[de,"Organic Sessions"]:[de,ve]}}),e.jsx(mi,{wrapperStyle:{fontSize:11,color:gt.text},formatter:F=>F==="_totalSessions"?"Total Sessions":F==="_organicSessions"?"Organic Sessions":F}),e.jsx(ks,{type:"monotone",dataKey:"_totalSessions",stroke:gt.textFaint,fill:gt.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),O.map((F,Ce)=>e.jsx(ks,{type:"monotone",dataKey:F,stackId:"ai",stroke:es[Ce%es.length],fill:es[Ce%es.length],fillOpacity:.4,strokeWidth:1.5},F))]})})})]}),e.jsxs(me,{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(Dt,{label:"Organic",value:Ee,hint:`${Ue.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(Dt,{label:"Social",value:Ct,hint:`${Ot.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(Dt,{label:"Direct",value:St,hint:`${wt.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(Dt,{label:"Known AI referrers (lower bound)",value:bt,hint:ke>0?`${Nt.toLocaleString()} sessions · ${ke.toLocaleString()} paid`:`${Nt.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(Dt,{label:"Other channels",value:Ae,hint:`${Re.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."})]}),tt&&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:tt.source})," via ",tt.medium,", accounting for ",tt.sessions.toLocaleString()," sessions.",ke>0&&e.jsxs("span",{children:[" Paid AI: ",ke.toLocaleString()," sessions (",Fe,")."]})]})]}),e.jsxs(me,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Detail"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Known AI referrers by source"})]}),e.jsx("p",{className:"text-xs text-muted",children:r.aiReferrals.length>0?`${qt} unique sources, ${r.aiReferrals.length} rows`:"No source rows"})]}),r.aiReferrals.length>0?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(vt,{label:"Source",sortKey:"source",current:$,dir:v,onSort:we,align:"left"}),e.jsx(vt,{label:"Medium",sortKey:"medium",current:$,dir:v,onSort:we,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(vt,{label:"Sessions",sortKey:"sessions",current:$,dir:v,onSort:we,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:ge.map(F=>e.jsx(Qd,{referral:F,totalSessions:Ve},`${F.source}:${F.medium}:${F.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(me,{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:Be})]}),r.aiReferralLandingPages.length>0?e.jsxs(e.Fragment,{children:[e.jsx(As,{value:je.query,onChange:je.setQuery,label:"Filter landing page URLs or query parameters",placeholder:"Filter URL or query parameters",className:"mb-4 max-w-md"}),je.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(vt,{label:"Landing Page",sortKey:"landingPage",current:D,dir:V,onSort:et,align:"left"}),e.jsx(vt,{label:"Source",sortKey:"source",current:D,dir:V,onSort:et,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(vt,{label:"Sessions",sortKey:"sessions",current:D,dir:V,onSort:et,align:"right"})]})}),e.jsx("tbody",{children:je.rows.map(F=>e.jsx(Hd,{row:F},`${F.landingPage}:${F.source}:${F.medium}:${F.sourceDimension}`))})]})}),e.jsx(fs,{page:je.page,pageSize:je.pageSize,visibleRows:je.rows.length,totalRows:je.totalRows,onPageChange:je.setPage,itemLabel:je.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:()=>je.setQuery(""),className:"mt-2 text-xs text-link hover:underline focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",children:"Clear filter"})]})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No AI landing pages detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"Known-AI landing pages appear after a GA4 sync records visits from AI referrers."})]})]})]})]}),r&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Social Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Social Media Traffic",e.jsx(Ze,{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."})]})]}),J.length>0&&e.jsxs(me,{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"})]}),xe>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",De.length-1," sources · ",xe," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(Ts,{width:"100%",height:"100%",children:e.jsxs(Ds,{data:J,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Es,{dataKey:"date",tick:Lt,tickLine:!1,axisLine:{stroke:Ht},tickFormatter:fa}),e.jsx(qs,{tick:Lt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Os,{...gs,labelFormatter:Ln,formatter:(F,Ce)=>{const de=typeof F=="number"?F.toLocaleString():String(F??0),ve=String(Ce??"");if(ve===Rs)return[de,"Total Social"];if(ve===Fs){const Ke=`Other (${xe} source${xe===1?"":"s"})`;return[de,Ke]}return[de,$s(ve)]}}),e.jsx(ks,{type:"monotone",dataKey:Rs,stroke:wi,fill:gt.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),De.map((F,Ce)=>{const ve=F===Fs?ya:es[Ce%es.length];return e.jsx(ks,{type:"monotone",dataKey:F,stackId:"social",stroke:ve,fill:ve,fillOpacity:.4,strokeWidth:1.5},F)})]})})}),e.jsx(Yd,{sources:De,otherCount:xe})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.5fr)]",children:[e.jsxs(me,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Summary"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social media visits"})]}),r.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(Dt,{label:"Social Sessions",value:jn(lt),hint:`${lt.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(Dt,{label:"Share of Traffic",value:Ge,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(Dt,{label:"Platforms",value:String(Je),hint:`${r.socialReferrals.length} source rows`,tone:"neutral",tooltip:"Number of distinct social media platforms detected. Each unique source/medium combination counts as one source row."})]}),He&&e.jsxs("div",{className:"mt-4 rounded-lg border border-info-800/40 bg-info-500/6 px-4 py-3 text-sm text-info-100",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-info-300/70 mb-1",children:"Top social source"}),e.jsx("p",{className:"font-medium truncate",title:`${He.source} via ${He.medium}`,children:Ni($s(He.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:He.medium,children:["via ",$s(He.medium)," · ",He.sessions.toLocaleString()," sessions"]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(Dt,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(Dt,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(Dt,{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(me,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Breakdown"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Source / medium"})]}),e.jsx("p",{className:"text-xs text-muted",children:r.socialReferrals.length>0?Me.length>Vs&&!P?`Top ${Vs} of ${Me.length}`:`${Me.length} rows`:"No source rows"})]}),r.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm table-fixed",children:[e.jsxs("colgroup",{children:[e.jsx("col",{className:"w-[32%]"}),e.jsx("col",{className:"w-[22%]"}),e.jsx("col",{className:"w-[12%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[12%]"})]}),e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(vt,{label:"Source",sortKey:"source",current:ee,dir:A,onSort:Oe,align:"left"}),e.jsx(vt,{label:"Medium",sortKey:"medium",current:ee,dir:A,onSort:Oe,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(vt,{label:"Sessions",sortKey:"sessions",current:ee,dir:A,onSort:Oe,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(vt,{label:"Users",sortKey:"users",current:ee,dir:A,onSort:Oe,align:"right"})]})}),e.jsx("tbody",{children:(P?Me:Me.slice(0,Vs)).map(F=>e.jsx(Wd,{referral:F,totalSessions:lt},`${F.source}:${F.medium}:${F.channelGroup}`))})]})}),Me.length>Vs&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>re(F=>!F),className:"rounded-md border border-base px-3 py-1.5 text-xs text-secondary transition-colors hover:border-strong hover:text-strong",children:P?`Show top ${Vs}`:`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."})]})]})]})]})]}),r&&r.topPages.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Page Performance"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Top Landing Pages",e.jsx(Ze,{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(vt,{label:"Landing Page",sortKey:"landingPage",current:p,dir:E,onSort:z,align:"left"}),e.jsx(vt,{label:"Sessions",sortKey:"sessions",current:p,dir:E,onSort:z,align:"right"}),e.jsx(vt,{label:"Organic",sortKey:"organicSessions",current:p,dir:E,onSort:z,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"})]})}),e.jsx("tbody",{children:K.map(F=>e.jsx(Kd,{page:F},F.landingPage))})]})})]})]}),e.jsxs("div",{className:"mt-6 flex items-center justify-between text-xs text-muted",children:[e.jsx("span",{children:r?.lastSyncedAt?`Last synced ${Si(r.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:r?`${r.topPages.length} pages · ${r.aiReferrals.length} AI rows · ${r.socialReferrals.length} social rows`:""})]})]})}function Vd({projectName:t,onConnected:s}){const[n,a]=l.useState(""),[r,i]=l.useState(null),[o,u]=l.useState(null),[d,h]=l.useState(!1),[x,c]=l.useState(null),y=l.useRef(null),N=l.useCallback(b=>{const p=b.target.files?.[0];if(!p)return;c(null),i(p.name);const L=new FileReader;L.onload=()=>{const E=L.result;try{const q=JSON.parse(E);if(!q.client_email||!q.private_key){c("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(E)}catch{c("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),u(null)}},L.onerror=()=>{c("Failed to read file."),u(null)},L.readAsText(p)},[]);async function f(){if(c(null),!n.trim()){c("Property ID is required.");return}if(!o){c("Please upload a service account key file.");return}h(!0);try{await Nl(t,{propertyId:n.trim(),keyJson:o});try{await Jr(t)}catch{}s()}catch(b){c(b instanceof Error?b.message:"Failed to connect GA4")}finally{h(!1)}}return e.jsxs(me,{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."}),x&&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:x}),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:b=>a(b.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:y,type:"file",accept:".json,application/json",onChange:N,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>y.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(gd,{className:"w-4 h-4 shrink-0"}),r?e.jsx("span",{className:"text-strong truncate",children:r}):e.jsx("span",{children:"Upload .json key file"})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Download from Google Cloud Console → IAM & Admin → Service Accounts → Keys → Add Key → JSON. The service account must have ",e.jsx("span",{className:"text-secondary",children:"Viewer"})," access on the GA4 property."]})]}),e.jsx(k,{variant:"default",size:"sm",disabled:d||!n.trim()||!o,onClick:Ie(f),children:d?"Connecting & syncing…":"Connect GA4"})]})}function vt({label:t,sortKey:s,current:n,dir:a,onSort:r,align:i}){const o=n===s;return e.jsx("th",{className:`py-1 ${i==="right"?"text-right":"text-left"}`,children:e.jsxs("button",{type:"button",className:"font-medium cursor-pointer select-none hover:text-neutral transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-400 rounded",onClick:()=>r(s),"aria-label":`Sort by ${t}${o?` (currently ${a==="asc"?"ascending":"descending"})`:""}`,children:[t,o&&e.jsx("span",{className:"ml-0.5",children:a==="asc"?"↑":"↓"})]})})}const Ci={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function Yn({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 ${Ci[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Dt({value:t,label:s,hint:n,tone:a,tooltip:r}){return e.jsxs("div",{className:"rounded-lg border border-default bg-bg/40 px-4 py-3 flex flex-col",children:[e.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1 flex items-center gap-1",children:[s,r&&e.jsx(Ze,{text:r})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${Ci[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Kd({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 ki={session:"Session",first_user:"First Visit",manual_utm:"UTM"},Pi={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 Qd({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=ki[t.sourceDimension]??t.sourceDimension,r=Pi[t.sourceDimension]??"",i=t.trafficClass==="paid"?"Paid":"Organic",o=t.trafficClass==="paid"?"Paid AI traffic inferred from paid/cpc/sponsored UTM values or a GA4 paid channel group":"AI traffic without a paid attribution signal";return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 text-strong max-w-[220px] truncate",title:t.source,children:t.source}),e.jsx("td",{className:"py-1.5 text-muted max-w-[180px] truncate",title:t.medium,children:t.medium}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:`inline-block text-[10px] px-1.5 py-0.5 rounded-full border ${t.trafficClass==="paid"?"border-caution-700 text-caution-300":"border-strong text-secondary"}`,title:o,children:i})}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:r,children:a})}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[n,"%"]})]})}function Hd({row:t}){const s=ki[t.sourceDimension]??t.sourceDimension,n=Pi[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(Xs,{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 Wd({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=t.channelGroup==="Paid Social"?"Paid":"Organic",r=$s(t.source),i=$s(t.medium);return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 pr-3 text-strong truncate",title:t.source,children:r}),e.jsx("td",{className:"py-1.5 pr-3 text-muted truncate",title:t.medium,children:i}),e.jsx("td",{className:"py-1.5 pr-3",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:`GA4 channel group: ${t.channelGroup}`,children:a})}),e.jsx("td",{className:"py-1.5 text-right text-info-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[n,"%"]}),e.jsx("td",{className:"py-1.5 text-right text-strong tabular-nums",children:t.users.toLocaleString()})]})}function Yd({sources:t,otherCount:s}){const n=[{key:Rs,color:wi,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const r=t[a];if(r===Fs)n.push({key:Fs,color:ya,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const i=$s(r);n.push({key:r,color:es[a%es.length]??ya,label:Ni(i,32),tooltip:i})}}return e.jsx("div",{className:"mt-3 flex flex-wrap gap-x-4 gap-y-1.5 text-[11px] text-secondary",children:n.map(a=>e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 max-w-[260px]",title:a.tooltip,children:[e.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-sm shrink-0",style:{backgroundColor:a.color},"aria-hidden":"true"}),e.jsx("span",{className:"truncate",children:a.label})]},a.key))})}function Jd(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 Xd=["7d","30d","90d","all"],yn=500,Xt=25,Zd="canonry:google-oauth-complete";function gr(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function fr(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 br(t){return t.isPending?"Processing":Number(t.errors??0)>0?"Errors":Number(t.warnings??0)>0?"Warnings":"Success"}function eu({projectName:t,refreshNonce:s}){const n=as(),[a,r]=l.useState(!1),[i,o]=l.useState([]),[u,d]=l.useState([]),[h,x]=l.useState([]),[c,y]=l.useState(null),[N,f]=l.useState([]),[b,p]=l.useState([]),[L,E]=l.useState(null),[q,$]=l.useState(""),[g,v]=l.useState(""),[w,ee]=l.useState("30"),[W,A]=l.useState(!1),[j,D]=l.useState("30d"),[S,V]=l.useState({startDate:"",endDate:"",query:"",page:""}),[pe,ne]=l.useState(0),[X,te]=l.useState(!1),[ce,B]=l.useState(0),[G,P]=l.useState(!1),[re,le]=l.useState(""),[C,U]=l.useState(!0),[se,M]=l.useState(!1),[z,we]=l.useState(!1),[Oe,K]=l.useState(!1),[ge,Te]=l.useState(!1),[je,Be]=l.useState(!1),[et,Me]=l.useState(!1),[J,De]=l.useState(null),[xe,Qe]=l.useState(!1),[O,_]=l.useState(!1),[fe,Ee]=l.useState(null),[Ue,Ve]=l.useState(null),[Nt,bt]=l.useState([]),[ke,Fe]=l.useState(new Set),[qt,tt]=l.useState({}),[dt,Ye]=l.useState(new Set),[wt,St]=l.useState(""),[Re,Ae]=l.useState(null),[lt,Ge]=l.useState(""),[Ot,Ct]=l.useState(!1),[Je,He]=l.useState(!1),[F,Ce]=l.useState(!1),[de,ve]=l.useState(!1),[Ke,Wt]=l.useState("indexed"),[st,kt]=l.useState(null),rs=!!(S.query.trim()||S.page.trim()||st),R=st!==null,be=l.useMemo(()=>{if(!st)return h;const{key:m,dir:T}=st;return[...h].sort((ae,ue)=>{const $e=m===xs.CTR?Number.isFinite(ae.ctr)?ae.ctr:0:ae[m],qe=m===xs.CTR?Number.isFinite(ue.ctr)?ue.ctr:0:ue[m];return T==="asc"?$e-qe:qe-$e})},[h,st]),ye=nn({rows:be,pageSize:Et}),Pt=G?ye.rows:be,nt=nn({rows:(fe??[]).filter(m=>m.path.toLowerCase().includes(wt.trim().toLowerCase())),pageSize:Et}),[At,dn]=l.useState([]),[jt,is]=l.useState(null),[En,un]=l.useState(1),ls=l.useMemo(()=>{if(At.length<2)return null;const m=At[At.length-1],T=At[At.length-2];return{indexed:m.indexed-T.indexed,notIndexed:m.notIndexed-T.notIndexed}},[At]);l.useEffect(()=>{un(1)},[J,Ke,jt]);const js=l.useMemo(()=>jt?(J?.reasonGroups??[]).find(m=>m.reason===jt):void 0,[J,jt]),Us=l.useMemo(()=>J?Ke==="indexed"?J.indexed:Ke==="deindexed"?J.deindexed:Ke==="notIndexed"?jt?js?.urls??[]:(J.reasonGroups??[]).length===0?J.notIndexed:[]:[]:[],[J,Ke,jt,js]),qn=Math.max(1,Math.ceil(Us.length/Xt)),mn=Math.min(Math.max(1,En),qn),ut=(mn-1)*Xt,ys=l.useMemo(()=>J?.indexed.slice(ut,ut+Xt)??[],[J,ut]),On=l.useMemo(()=>J?.notIndexed.slice(ut,ut+Xt)??[],[J,ut]),Fn=l.useMemo(()=>J?.deindexed.slice(ut,ut+Xt)??[],[J,ut]),I=l.useMemo(()=>(js?.urls??[]).slice(ut,ut+Xt),[js,ut]),[Y,he]=l.useState(!1),[ie,H]=l.useState(null),[Se,Mt]=l.useState(null),[ot,yt]=l.useState(null);function Yt(m,T){const ae=Zc(m),ue=Jd(ae);ue?(Mt(ue),H(null)):(Mt(null),H(ae.message||T))}const at=i.find(m=>m.connectionType==="gsc"),os=(at?.scopes??[]).includes("https://www.googleapis.com/auth/webmasters"),_n=Nt.length>0?Nt:(fe??[]).map(m=>m.path),Va=_n.filter(m=>fe?.some(T=>T.path===m&&T.isSitemapsIndex)).length,Qi=Va===1?"Resubmit sitemap index":Va>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",Hi=h.length>0||N.length>0||b.length>0,Un=wl(),Gn=Sl();async function Ka(m,T=!1){if(!m){d([]),$("");return}we(!0);try{const{sites:ae}=await n.fetchQuery({...ql({client:Q,path:{name:t}}),staleTime:T?0:ct});d(ae),$(m.propertyId??ae[0]?.siteUrl??""),Mt(null)}catch(ae){d([]),Yt(ae,"Failed to load Search Console properties")}finally{we(!1)}}async function Gs(m){Te(!0);const T=m??pe;try{const ae=rs?yn:Et,ue=rs?0:T,$e={limit:String(ae)};S.startDate&&($e.startDate=S.startDate),S.endDate&&($e.endDate=S.endDate),S.query&&($e.query=S.query),S.page&&($e.page=S.page),ue>0&&($e.offset=String(ue)),j&&j!=="all"&&!S.startDate&&($e.window=j);const qe=await n.fetchQuery({...kl({client:Q,path:{name:t},query:$e}),staleTime:ct}),_e=qe.rows;rs?(te(!1),x(_e),B(_e.length),P(!0)):(te(ue+_e.length<qe.totalMatching),x(_e),B(0),P(!1))}catch(ae){x([]),te(!1),B(0),H(ae instanceof Error?ae.message:"Failed to load GSC performance data")}finally{Te(!1)}}async function Bn(){try{const m={};S.startDate&&(m.startDate=S.startDate),S.endDate&&(m.endDate=S.endDate),j&&j!=="all"&&!S.startDate&&(m.window=j);const T=await n.fetchQuery({...Pl({client:Q,path:{name:t},query:m}),staleTime:ct});y(T)}catch{y(null)}}async function hn(m=!1){Be(!0);try{const T=re.trim()||void 0,ae={limit:"20"};T&&(ae.url=T);const[ue,$e]=await Promise.all([n.fetchQuery({...Dl({client:Q,path:{name:t},query:ae}),staleTime:m?0:ct}),n.fetchQuery({...El({client:Q,path:{name:t}}),staleTime:m?0:ct})]);f(ue),p($e)}catch(T){f([]),p([]),H(T instanceof Error?T.message:"Failed to load GSC inspection history")}finally{Be(!1)}}async function Qa(m=!1){Qe(!0);try{const[T,ae]=await Promise.all([n.fetchQuery({...Zr({client:Q,path:{name:t}}),staleTime:m?0:ct}),n.fetchQuery({...$l({client:Q,path:{name:t}}),staleTime:m?0:ct}).catch(()=>[])]);De(T),dn(ae)}catch(T){De(null),dn([]),H(T instanceof Error?T.message:"Failed to load coverage data")}finally{Qe(!1)}}async function Ha(m){he(!0),H(null);try{const T=await sr(t,{urls:m}),{succeeded:ae,failed:ue,total:$e}=T.summary;Ne({title:"Indexing requested",detail:ue===0?`${ae} URL${ae!==1?"s":""} submitted for indexing.`:`${ae}/${$e} submitted successfully, ${ue} failed.`,tone:ue===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(T){H(T instanceof Error?T.message:"Failed to request indexing")}finally{he(!1)}}async function Wi(){he(!0),H(null);try{const m=await sr(t,{urls:[],allUnindexed:!0}),{succeeded:T,failed:ae,total:ue}=m.summary;Ne({title:"Indexing requested",detail:ae===0?`${T} unindexed URL${T!==1?"s":""} submitted for indexing.`:`${T}/${ue} submitted successfully, ${ae} failed.`,tone:ae===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(m){H(m instanceof Error?m.message:"Failed to request indexing")}finally{he(!1)}}async function zn(){_(!0),H(null);try{const m=await Vn(t);n.setQueryData(Il({client:Q,path:{name:t}}),m),Ee(m.sitemaps),Ve(m.summary),bt(m.preferredSubmissionUrls),Fe(new Set),tt({}),m.sitemaps.length===0&&yt("No sitemaps found in this GSC property. Submit one here to start Google processing it.")}catch(m){H(m instanceof Error?m.message:"Failed to list sitemaps")}finally{_(!1)}}async function Yi(m){const T=ke.has(m);if(Fe(ae=>{const ue=new Set(ae);return T?ue.delete(m):ue.add(m),ue}),!(T||qt[m])){Ye(ae=>new Set(ae).add(m));try{const ae=await Vn(t,m);tt(ue=>({...ue,[m]:ae.sitemaps}))}catch(ae){H(ae instanceof Error?ae.message:"Failed to load sitemap files")}finally{Ye(ae=>{const ue=new Set(ae);return ue.delete(m),ue})}}}async function vs(m){if(!os||m.length===0)return;const T=[...new Set(m)];He(!0),H(null),Ae({completed:0,total:T.length});let ae=0,ue=0,$e=0,qe=null;try{for(let Xe=0;Xe<T.length;Xe+=50){const Pe=T.slice(Xe,Xe+50);try{const mt=await Ll(t,Pe);ae+=mt.summary.accepted,ue+=mt.summary.failed,$e+=Pe.length,Ae({completed:$e,total:T.length})}catch(mt){$e+=Pe.length;const Tt=Pe.length,cs=T.length-$e,Ns=mt instanceof Error?mt.message:"The batch request failed",Bs=`${ae} accepted, ${ue} failed, ${Tt} unconfirmed, ${cs} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;qe=`Sitemap submission stopped after a batch request failed. ${Bs} ${Ns}`,H(qe),Ne({title:"Sitemap resubmission partially completed",detail:Bs,tone:"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"});return}}const _e=T.length;Ne({title:ue===0?"Sitemap submitted to Google":"Some sitemap submissions need attention",detail:ue===0?"Google accepted the sitemap submission/refetch request; indexing is not guaranteed.":`Google accepted ${ae}/${_e} sitemap submissions; ${ue} failed. Indexing is not guaranteed.`,tone:ue===0?"positive":"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"}),Ge("")}catch(_e){H(_e instanceof Error?_e.message:"Failed to submit sitemap to Google")}finally{He(!1),Ae(null),await zn(),qe&&H(qe)}}async function Ji(){He(!0);const m=fe??[];try{const T=m.filter(ue=>ue.isSitemapsIndex),ae=[];for(let ue=0;ue<T.length;ue+=4)(await Promise.all(T.slice(ue,ue+4).map(async qe=>{const _e=qt[qe.path];if(_e)return _e;const Xe=await Vn(t,qe.path);return tt(Pe=>({...Pe,[qe.path]:Xe.sitemaps})),Xe.sitemaps}))).forEach((qe,_e)=>{ae.push(...qe.length>0?qe.map(Xe=>Xe.path):[T[ue+_e].path])});await vs([...m.filter(ue=>!ue.isSitemapsIndex).map(ue=>ue.path),...ae])}catch(T){H(T instanceof Error?T.message:"Failed to load sitemap files"),He(!1)}}async function Wa(m){Ct(!0),H(null);try{await Ml(t,"gsc",m),await it(n,"google"),o(T=>T.map(ae=>ae.connectionType==="gsc"?{...ae,sitemapUrl:m}:ae)),Ne({title:"Default sitemap updated",detail:m,tone:"positive",dedupeKey:`gsc:sitemap-default:${t}`,dedupeMode:"replace"})}catch(T){H(T instanceof Error?T.message:"Failed to set the default sitemap")}finally{Ct(!1)}}async function Ya(m){try{await Gn.mutateAsync({projectName:t,projectLabel:t,opts:m?{sitemapUrl:m}:void 0})}catch{}}async function Ja(){U(!0),H(null);try{const[m,T]=await Promise.all([Xr().catch(()=>null),n.fetchQuery({...Ra({client:Q,path:{name:t}}),staleTime:ct}).catch(()=>[])]);r(!!m?.google?.configured),o(T);const ae=T.find(ue=>ue.connectionType==="gsc");await Promise.all([Ka(ae),Gs(),Bn(),hn(),Qa(),ae?.propertyId?zn():Promise.resolve()])}finally{U(!1)}}l.useEffect(()=>{Ja()},[t,s]),l.useEffect(()=>{ne(0),Gs(0),Bn()},[j]);const Xa=l.useRef(!1);l.useEffect(()=>{if(!Xa.current){Xa.current=!0;return}ne(0),Gs(0)},[R]);async function Za(){if(!a){H("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}M(!0),H(null),yt(null);try{let m=function(mt){if(mt.source!==ue||mt.origin!==$e||!mt.data||typeof mt.data!="object")return;const Tt=mt.data;Tt.type!==Zd||Tt.connectionType!=="gsc"||Pe(!0)};const{authUrl:T,redirectUri:ae}=await Rl(t,"gsc");if(!T.startsWith("https://accounts.google.com/")){H("Unexpected OAuth redirect URL. Please try again.");return}const ue=window.open(T,"_blank","width=600,height=700");if(!ue){window.location.assign(T);return}const $e=ae?new URL(ae).origin:window.location.origin;let qe=!1,_e=null;const Xe=()=>{_e!==null&&window.clearInterval(_e),window.removeEventListener("message",m)},Pe=async mt=>{if(!qe){qe=!0,Xe(),yt(mt?"Google connected. Refreshing access…":"Refreshing Google connection…");try{await it(n,"google"),await Ja()}finally{yt(null)}}};window.addEventListener("message",m),yt("Finish the Google consent flow in the popup. This page will refresh automatically."),_e=window.setInterval(()=>{ue.closed&&Pe(!1)},1e3)}catch(m){H(m instanceof Error?m.message:"Failed to start OAuth flow")}finally{M(!1)}}async function Xi(){H(null),yt(null);try{await Al(t,"gsc"),await it(n,"google"),o(m=>m.filter(T=>T.connectionType!=="gsc")),d([]),$("")}catch(m){H(m instanceof Error?m.message:"Failed to disconnect")}}async function Zi(){if(q){K(!0),H(null);try{await Ol(t,"gsc",q),await it(n,"google"),o(m=>m.map(T=>T.connectionType==="gsc"?{...T,propertyId:q}:T)),Ne({title:"GSC property updated",detail:`${t} is now linked to ${q}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(m){H(m instanceof Error?m.message:"Failed to save GSC property")}finally{K(!1)}}}async function el(){H(null),yt(null);try{await Un.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(w,10)||void 0,full:W||void 0}}),await it(n,"gsc")}catch{}}async function er(){if(g.trim()){Me(!0),H(null),yt(null);try{const m=await Tl(t,g.trim());await it(n,"gsc"),E(m),v(""),await hn()}catch(m){H(m instanceof Error?m.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"})]})}),Se&&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:Se.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:Se.message}),(ms(Se.enableUrl)||ms(Se.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[ms(Se.enableUrl)&&e.jsx("a",{href:ms(Se.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 ↗"}),ms(Se.indexingApiUrl)&&e.jsx("a",{href:ms(Se.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:()=>Mt(null),children:"×"})]})}),ie&&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:[ie,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>H(null),children:"×"})]}),ot&&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:[ot,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>yt(null),children:"×"})]}),C?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[at?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:at.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Last updated ",_t(at.updatedAt)]}),e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:Ie(Xi),children:"Disconnect"})]}):e.jsxs(me,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(oe,{tone:a?"caution":"negative",children:a?"Ready to connect":"App credentials missing"})]}),e.jsxs("div",{className:"mt-3 rounded-lg border border-default bg-surface px-4 py-5",children:[e.jsx("p",{className:"text-sm text-neutral",children:a?"Generate a Google OAuth link for this project and have the client sign in with a Google account that already has access to the correct Search Console property.":"Set Google OAuth client credentials first. Once configured, you can generate a consent link for this project domain."}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[a?e.jsx(k,{type:"button",variant:"outline",size:"sm",disabled:se,onClick:Ie(Za),children:se?"Opening…":"Connect Google Search Console"}):e.jsx(k,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(Ut,{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."})]})]})]}),(at||Hi)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs(me,{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:Xd.map(m=>e.jsx("button",{type:"button","aria-pressed":j===m,className:`segmented-option ${j===m?"segmented-option-active":""}`,onClick:()=>{D(m),ne(0),ye.setPage(1)},children:m==="all"?"All":m},m))}),e.jsx(k,{type:"button",variant:"outline",size:"sm",disabled:ge,onClick:()=>{ne(0),ye.setPage(1),Gs(0),Bn()},children:ge?"Loading…":"Apply filters"})]})]}),c&&c.daily.length>0&&(()=>{const m=c.daily,T=Math.max(...m.map(ze=>ze.impressions),1),{clicks:ae,impressions:ue,ctr:$e}=c.totals,qe=($e*100).toFixed(1),_e=700,Xe=220,Pe={top:12,bottom:36,left:48,right:12},mt=_e-Pe.left-Pe.right,Tt=Xe-Pe.top-Pe.bottom,cs=mt/m.length,Ns=Math.max(Math.min(cs*.35,24),4),Bs=Math.max(Ns*.15,1),tl=ze=>{if(ze<=0)return 1;const Bt=Math.pow(10,Math.floor(Math.log10(ze))),Rt=ze/Bt,Jt=Rt<=1.5?1.5:Rt<=3?3:Rt<=5?5:10;return Math.ceil(Jt*Bt)},xn=4,pn=Math.ceil(tl(T)/xn)*xn,sl=Array.from({length:xn+1},(ze,Bt)=>pn/xn*Bt),nl=ze=>ze>=1e3?`${(ze/1e3).toFixed(ze>=1e4?0:1)}k`:String(ze);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:ae.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:ue.toLocaleString()})]})]}),e.jsxs("span",{className:"text-xs text-muted",children:["CTR ",e.jsxs("span",{className:"text-caution-400 tabular-nums font-medium",children:[qe,"%"]})]})]}),e.jsx("div",{className:"relative w-full",style:{aspectRatio:`${_e} / ${Xe}`},children:e.jsxs("svg",{viewBox:`0 0 ${_e} ${Xe}`,className:"h-full w-full",children:[sl.map((ze,Bt)=>{const Rt=Pe.top+Tt-ze/pn*Tt;return e.jsxs("g",{children:[e.jsx("line",{x1:Pe.left,y1:Rt,x2:_e-Pe.right,y2:Rt,stroke:gt.gridLine,strokeWidth:"1"}),e.jsx("text",{x:Pe.left-6,y:Rt+3.5,textAnchor:"end",fill:gt.text,fontSize:"10",fontFamily:"inherit",children:nl(ze)})]},`t-${Bt}`)}),m.map((ze,Bt)=>{const Rt=Pe.left+cs*Bt+cs/2,Jt=ze.impressions/pn*Tt,gn=ze.clicks/pn*Tt;return e.jsxs("g",{children:[e.jsx("title",{children:`${ze.date}
1
+ import{j as e,r as l,L as Ut,o as as,u as Le,p as tn,B as Wr,C as al,k as rl,l as il,D as ll}from"./vendor-tanstack-BjS7iY3g.js";import{c as ln,T as oe,t as ol,a as cl,S as dl,X as ul,C as Aa,u as Yr,b as ml,P as Is,B as k,h as hl,d as xl,e as pl,f as me,i as Z,g as it,j as Ie,I as Ze,k as zs,l as gl,m as Q,n as fl,o as bl,p as jl,q as yl,r as Jr,s as vl,v as Nl,w as xs,x as wl,y as Sl,z as ms,A as _t,D as Cl,E as tr,F as Xr,G as ct,H as Ra,J as kl,K as Pl,L as Al,M as Rl,N as sr,O as Ne,Q as Zr,R as $l,U as Vn,V as Il,W as Ll,Y as Ml,Z as Tl,_ as Dl,$ as El,a0 as ql,a1 as Ol,a2 as Fl,a3 as _l,a4 as Ul,a5 as Gl,a6 as Bl,a7 as zl,a8 as Vl,a9 as Kl,aa as bs,ab as Ql,ac as ei,ad as $n,ae as Hl,af as Wl,ag as Yl,ah as Jl,ai as In,aj as Xl,ak as Zl,al as eo,am as Ls,an as to,ao as so,ap as ga,aq as no,ar as ao,as as Ms,at as ti,au as si,av as ro,aw as ni,ax as io,ay as lo,az as oo,aA as co,aB as ai,aC as uo,aD as mo,aE as ho,aF as Js,aG as ps,aH as xo,aI as po,aJ as go,aK as fo,aL as ri,aM as bo,aN as jo,aO as yo,aP as vo,aQ as No,aR as ii,aS as wo,aT as $a,aU as So,aV as Co,aW as ko,aX as We,aY as Po,aZ as Ao,a_ as Ro,a$ as $o,b0 as Io,b1 as Lo,b2 as Mo,b3 as To,b4 as Do,b5 as Eo,b6 as qo,b7 as Oo,b8 as Fo,b9 as _o,ba as Uo,bb as Go,bc as Bo,bd as zo,be as Vo,bf as Ko,bg as Qo,bh as Ho,bi as Wo,bj as Yo,bk as Jo,bl as Xo,bm as Zo,bn as ec,bo as tc,bp as sc,bq as nc,br as ac,bs as rc,bt as ic,bu as lc,bv as oc,bw as cc,bx as dc,by as Kn,bz as uc,bA as mc,bB as nr,bC as hc,bD as xc,bE as pc,bF as gc,bG as fc,bH as bc,bI as jc,bJ as yc,bK as vc,bL as Nc,bM as wc,bN as Sc,bO as Cc,bP as li,bQ as kc,bR as Pc,bS as Ac,bT as Rc,bU as $c,bV as Ic,bW as ar,bX as Lc,bY as Qn,bZ as ft,b_ as Mc,b$ as Tc,c0 as Dc,c1 as Ec,c2 as qc,c3 as Oc,c4 as Fc,c5 as _c,c6 as oi,c7 as ci,c8 as Uc,c9 as di,ca as Gc,cb as ui,cc as Bc,cd as zc,ce as fn,cf as Vc,cg as Kc,ch as Qc,ci as rr}from"./index-Bo0hzrG2.js";import{R as Hc}from"./RunRow-yKrIU8zY.js";import{C as Wc,R as sn,f as fa,a as Ht,b as Lt,c as Ln,d as gs,e as gt,g as pt,h as Qt,i as Ia,j as La,k as ns,o as Gt,p as Yc}from"./ChartPrimitives-BoB1RfNf.js";import{u as Jc,t as Xc,e as Zc,a as ir}from"./extract-error-message-jd9FdYvE.js";import{R as Ts,C as Ds,X as Es,Y as qs,T as Os,L as mi,A as ks,a as Ma,b as ed,d as Ta,e as td}from"./vendor-recharts-33ACLxsD.js";import{D as hi,C as sd,E as nd,T as ad}from"./trash-2-lAIhBm6w.js";import{A as rd}from"./AuditHistoryPanel-D5fRv5sF.js";import{a as id,b as ld}from"./v2-overview-adapter-BHmxTmCf.js";import"./vendor-radix-DnzzbllM.js";import"./vendor-markdown-CpDJch4G.js";const od=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],xi=ln("circle-check",od);const cd=[["path",{d:"M5 12h14",key:"1ays0h"}]],dd=ln("minus",cd);const ud=[["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"}]],md=ln("scan-search",ud);const hd=[["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"}]],xd=ln("unplug",hd);const pd=[["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"}]],gd=ln("upload",pd);function An(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 fd(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} (${An(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${An(t.prior)} ${s})`:`Flat ${n} (${An(t.prior)} ${s})`}const pi=30;function lr(t){return Math.round(t*10)/10}function bd(t){return t.prior>=pi&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% vs prior`:`${t.deltaAbs>0?"+":""}${lr(t.deltaAbs)} vs ${lr(t.prior)}`}function jd(t,s,n){return t.prior>=pi&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% ${n}`:`${t.deltaAbs>0?"+":""}${An(Math.round(t.deltaAbs))} ${s} ${n}`}const yd=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function gi(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function fi(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 bi(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(gi).map(fi).filter(Boolean)):new Set}function ji(t,s){const n=gi(t).map(fi).filter(Boolean).filter(a=>!yd.has(a)).filter(a=>!s.has(a));return[...new Set(n)].sort().join(" ")}function vd(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function Nd(t,s){const n=bi(t);if(s.length<=1||n.size===0)return[...s];const a=new Set,r=[];for(const i of s){if(i.category!=="content"){r.push(i);continue}const o=ji(vd(i),n);!o||a.has(o)||(a.add(o),r.push(i))}return r}function wd(t){const s=bi(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const a=new Set;return n.filter(r=>{const i=ji(r.query,s);return!i||a.has(i)?!1:(a.add(i),!0)})}function ba({state:t,label:s}){return e.jsx(oe,{tone:cl(t),children:s??ol(t)})}const Et=25;function Sd(t){return t.trim().toLocaleLowerCase().split(/\s+/).filter(Boolean)}function yi(t){let s=t;try{s=decodeURIComponent(t.replace(/\+/g," "))}catch{}let n="";const a=t.indexOf("?");return a>=0&&new URLSearchParams(t.slice(a+1)).forEach((i,o)=>{n+=` ${o} ${i}`}),`${t} ${s}${n}`}function Cd(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 Xs({value:t,headLength:s,tailLength:n,className:a,title:r}){const i=Cd(t,s,n);return e.jsx("span",{className:a,title:r??t,children:i===t?t:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"sr-only",children:t}),e.jsx("span",{"aria-hidden":"true",children:i})]})})}function nn({rows:t,getSearchText:s,pageSize:n=Et}){const[a,r]=l.useState(""),[i,o]=l.useState(1),u=l.useMemo(()=>Sd(a),[a]),d=l.useMemo(()=>u.length===0||!s?t:t.filter(b=>{const p=s(b).toLocaleLowerCase();return u.every(L=>p.includes(L))}),[s,t,u]),h=Math.max(1,Math.ceil(d.length/n)),x=Math.min(Math.max(1,i),h),c=(x-1)*n,y=l.useMemo(()=>d.slice(c,c+n),[d,n,c]),N=l.useCallback(b=>{r(b),o(1)},[]),f=l.useCallback(b=>{o(Math.max(1,b))},[]);return{query:a,setQuery:N,page:x,setPage:f,rows:y,filteredRows:d,totalRows:d.length,totalPages:h,pageSize:n,rangeStart:d.length===0?0:c+1,rangeEnd:c+y.length,hasQuery:a.trim().length>0}}function As({value:t,onChange:s,label:n,placeholder:a="Filter rows",className:r}){return e.jsxs("div",{className:`relative ${r??""}`,children:[e.jsx(dl,{"aria-hidden":"true",className:"pointer-events-none absolute left-3 top-1/2 size-3.5 -translate-y-1/2 text-muted"}),e.jsx("input",{type:"search",value:t,onChange:i=>s(i.target.value),"aria-label":n,placeholder:a,autoComplete:"off",spellCheck:!1,className:"h-9 w-full rounded-md border border-default bg-surface/50 pl-9 pr-9 text-sm text-strong placeholder:text-muted outline-none transition focus:border-mono-500 focus:ring-1 focus:ring-mono-500 [&::-webkit-search-cancel-button]:appearance-none"}),t.trim().length>0?e.jsx("button",{type:"button",onClick:()=>s(""),"aria-label":`Clear ${n.toLocaleLowerCase()}`,className:"absolute right-2 top-1/2 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded text-muted transition-colors hover:bg-surface-hover hover:text-strong focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",children:e.jsx(ul,{"aria-hidden":"true",className:"size-3.5"})}):null]})}function fs({page:t,pageSize:s=Et,visibleRows:n,totalRows:a,hasNextPage:r,onPageChange:i,itemLabel:o="rows",className:u,disabled:d=!1}){if(n===0)return null;const h=(t-1)*s+1,x=h+n-1,c=a===void 0?void 0:Math.max(1,Math.ceil(a/s)),y=r??(c!==void 0&&t<c),N=t>1||y;return e.jsxs("div",{className:`mt-3 flex flex-wrap items-center justify-between gap-x-4 gap-y-2 text-xs text-secondary ${u??""}`,children:[e.jsxs("p",{className:"tabular-nums",children:[h.toLocaleString("en-US"),"–",x.toLocaleString("en-US"),a===void 0?`${y?"+":""} ${o}`:` of ${a.toLocaleString("en-US")} ${o}`]}),N?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>i(t-1),disabled:d||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(Wc,{"aria-hidden":"true",className:"size-3.5"}),"Previous"]}),e.jsx("span",{className:"tabular-nums",children:c===void 0?`Page ${t}`:`Page ${t} of ${c}`}),e.jsxs("button",{type:"button",onClick:()=>i(t+1),disabled:d||!y,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(Aa,{"aria-hidden":"true",className:"size-3.5"})]})]}):null]})}function or({history:t,maxDots:s=12}){const n=t.slice(-s);if(n.length===0)return e.jsx("span",{className:"text-[11px] text-faint",children:"No data"});const a={cited:"bg-positive-400","not-cited":"bg-mono-600",lost:"bg-negative-400",emerging:"bg-caution-400 ring-1 ring-caution-300/60"},r={cited:"rounded-full","not-cited":"rounded-sm",lost:"rotate-45 rounded-[1px]",emerging:"rounded-full"},i=n.length-1,o=new Date(n[0].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),u=new Date(n[i].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),d=n.map((h,x)=>{const c=new Date(h.createdAt).toLocaleDateString();return`${x===i?"Latest run, ":""}${c}: ${h.citationState}${h.model?`, model ${h.model}`:""}`}).join("; ");return e.jsxs("div",{className:"flex items-center gap-1",role:"img","aria-label":`Citation history across ${n.length} runs. ${d}`,children:[e.jsx("span",{className:"text-[9px] text-faint shrink-0","aria-hidden":"true",children:o}),e.jsx("div",{className:"flex items-center gap-[3px]",title:`${n.length} runs`,"aria-hidden":"true",children:n.map((h,x)=>{const c=!!(h.model&&x>0&&n[x-1]?.model&&n[x-1].model!==h.model),y=x===i;return e.jsx("span",{className:`h-2.5 w-2.5 ${r[h.citationState]??"rounded-sm"} ${a[h.citationState]??"bg-mono-700"} ${c?"ring-1 ring-caution-300/80 ring-offset-1 ring-offset-bg":""} ${y?"outline outline-1 outline-offset-2 outline-mono-400":""}`,title:[h.citationState,new Date(h.createdAt).toLocaleDateString(),h.model?`model ${h.model}`:null,c?"model changed":null,y?"latest run":null].filter(Boolean).join(" · ")},`${h.runId}:${h.createdAt}`)})}),e.jsxs("span",{className:"text-[9px] shrink-0 text-secondary","aria-hidden":"true",children:[u," ",e.jsx("span",{className:"text-faint",children:"latest"})]})]})}function ja(t){const s=new Map;for(const a of t)for(const r of a.runHistory){const i=s.get(r.createdAt);i?i.states.push(r.citationState):s.set(r.createdAt,{states:[r.citationState],runId:r.runId})}return[...s.entries()].sort(([a],[r])=>a.localeCompare(r)).map(([a,{states:r,runId:i}])=>({runId:i,createdAt:a,citationState:r.includes("cited")?"cited":r.includes("emerging")?"emerging":"not-cited"}))}const kd=320;function Pd(t){return[t.phrase,t.location??"",...t.rawItems.map(s=>s.provider)].join(" ")}function cr(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 dr(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 ur(t,s){const n=s==="mentions"?"mentioned":"cited",a=s==="mentions"?"Mentioned":"Cited";if(t.length===0)return"Awaiting first run";if(t.length===1)return"First observation";const r=t[t.length-1].citationState,i=t[t.length-2].citationState;if(i!=="cited"&&r==="cited")return`Newly ${n}`;if(i==="cited"&&r!=="cited")return"Lost since last run";let o=0;for(let u=t.length-1;u>=0&&t[u].citationState===r;u--)o++;return r==="cited"?o<=1?`${a} in latest run`:`${a} for ${o} runs`:o<=1?`Not ${n} in latest run`:`Not ${n} across ${o} runs`}function Ad(t,s){return t.map(n=>vi(n,s))}function vi(t,s){return s==="citations"?t:{...t,citationState:cr(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:cr(n,s)}))}}function mr(t,s){const n=s==="mentions"?"mention":"citation",a=s==="mentions"?"Mention":"Citation";if(t.length===0)return{key:s,label:`${a} pending`,tone:"pending"};const r=t[t.length-1].citationState,i=t.length>=2?t[t.length-2].citationState:null,o=r==="cited"||r==="emerging",u=i==="cited"||i==="emerging";return r==="lost"||i!==null&&u&&!o?{key:s,label:`Lost ${n}`,tone:"negative"}:r==="emerging"||i!==null&&!u&&o?{key:s,label:`New ${n}`,tone:"positive"}:i===null&&o?{key:s,label:`First ${n}`,tone:"positive"}:o?{key:s,label:s==="mentions"?"Still mentioned":"Still cited",tone:"neutral"}:{key:s,label:`No ${n}`,tone:"neutral"}}function Rd(t){const s=ja(Ad(t,"mentions")),n=ja(t);return[mr(s,"mentions"),mr(n,"citations")]}function $d({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 hr({items:t}){return e.jsx("div",{className:"mt-1 flex flex-wrap gap-1","aria-label":"Latest run mention and citation signals",children:Rd(t).map(s=>e.jsx($d,{signal:s},s.key))})}function Id({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:a}=Yr(),[r,i]=l.useState(new Set),[o,u]=l.useState("mentions"),[d,h]=l.useState(n),x=l.useMemo(()=>{const E=new Map;for(const q of t){const $=q.query,g=s?q.location??null:null,v=s?JSON.stringify([$,g]):$,w=E.get(v)??{key:v,phrase:$,location:g,items:[],rawItems:[]};w.items.push(vi(q,o)),w.rawItems.push(q),E.set(v,w)}return[...E.values()]},[t,o,s]),c=nn({rows:x,getSearchText:Pd}),y=c.rows.map(E=>E.key),N=y.length>0&&y.every(E=>r.has(E)),f=E=>{i(q=>{const $=new Set(q);return $.has(E)?$.delete(E):$.add(E),$})},b=o==="mentions"?"mentioned":"cited",p=o==="mentions"?"Mention History":"Citation History",L=o==="mentions"?"mentioned":"cited";return e.jsxs("div",{children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"View by"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-bg-elevated/60 border border-subtle",role:"tablist","aria-label":"Citation tracking view",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":o==="mentions",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${o==="mentions"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>u("mentions"),children:"Mentions"}),e.jsx("button",{type:"button",role:"tab","aria-selected":o==="citations",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${o==="citations"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>u("citations"),children:"Citations"})]}),e.jsx("span",{className:"text-[11px] text-muted",children:o==="mentions"?"Brand or domain in answer text":"Brand or domain in source links"}),e.jsxs("div",{className:"ml-auto flex items-center gap-3",children:[e.jsx("button",{type:"button",className:"text-[11px] text-secondary hover:text-strong",onClick:()=>{i(E=>{const q=new Set(E);for(const $ of y)N?q.delete($):q.add($);return q})},children:N?"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":d==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${d==="compact"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>h("compact"),children:"Compact"}),e.jsx("button",{type:"button",role:"tab","aria-selected":d==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${d==="detailed"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>h("detailed"),children:"Detailed"})]})]})]})]}),x.length>0?e.jsx(As,{value:c.query,onChange:c.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:p}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:c.rows.map(({key:E,phrase:q,location:$,items:g,rawItems:v})=>{const w=r.has(E),ee=g.map(S=>S.citationState),W=ee.includes("cited")?"cited":ee.includes("emerging")?"emerging":ee.includes("lost")?"lost":ee.every(S=>S==="pending")?"pending":"not-cited",A=ja(g),j=g.filter(S=>S.citationState===ml.cited||S.citationState==="emerging").length,D=ur(A,o);return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"cursor-pointer hover:bg-mono-800/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>f(E),onKeyDown:S=>{(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),f(E))},tabIndex:0,role:"button","aria-expanded":w,children:[e.jsx("td",{children:e.jsx(Aa,{size:14,className:`transition-transform duration-150 text-muted ${w?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-heading",children:q}),s&&e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-muted",children:$??"No location"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:g.map(S=>e.jsx(Is,{provider:S.provider},S.id))})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ba,{state:W,label:dr(W,o)}),e.jsxs("span",{className:"text-[11px] text-muted",title:`${j} of ${g.length} engines ${L}`,children:[j,"/",g.length]})]})}),e.jsx("td",{children:e.jsx(or,{history:A})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:D}),e.jsx(hr,{items:v})]}),e.jsx("td",{})]}),w&&g.map((S,V)=>e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"bg-surface",children:[e.jsx("td",{}),e.jsx("td",{className:"evidence-query-cell pl-5",children:e.jsx(Is,{provider:S.provider})}),e.jsx("td",{children:e.jsx(ba,{state:S.citationState,label:dr(S.citationState,o)})}),e.jsx("td",{children:e.jsx(or,{history:S.runHistory})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:ur(S.runHistory,o)}),e.jsx(hr,{items:[v[V]??S]})]}),e.jsx("td",{children:e.jsx(k,{variant:"ghost",size:"sm",type:"button",onClick:pe=>{pe.stopPropagation(),a(S.id)},children:"View"})})]}),d==="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(Td,{item:S,onViewFull:()=>a(S.id)})})]})]},S.id))]},E)})})]})}),c.totalRows===0&&c.hasQuery?e.jsx("p",{className:"supporting-copy mt-3",children:"No tracked queries match this filter."}):null,e.jsx(fs,{page:c.page,pageSize:c.pageSize,visibleRows:c.rows.length,totalRows:c.totalRows,onPageChange:c.setPage,itemLabel:c.hasQuery?"matches":"queries"}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",b==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function Ld(t){const s=(t.matchedTerms??[]).filter(r=>r.trim().length>2),n=[...t.competitorDomains.flatMap(r=>{const i=xl(r);return i.length>=4?[i]:[]}),...t.recommendedCompetitors??[]].filter(r=>r.trim().length>2),a=[];return s.length>0&&a.push({terms:s,className:"answer-highlight-brand"}),n.length>0&&a.push({terms:n,className:"answer-highlight-competitor"}),a}function Md(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 Td({item:t,onViewFull:s}){if(!(t.answerSnippet.trim().length>0))return e.jsx("p",{className:"text-[11px] text-muted italic",children:"No answer text captured for this run."});const{body:a,truncated:r}=Md(t.answerSnippet,kd),i=Ld(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:hl(a,i)}),(t.citedDomains.length>0||t.competitorDomains.length>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[t.citedDomains.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Cited:"}),t.citedDomains.slice(0,6).map(o=>e.jsx("span",{className:"rounded-full border border-mono-700/60 bg-bg-elevated/60 px-2 py-0.5 text-[11px] text-neutral",children:o},`c-${o}`)),t.citedDomains.length>6&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.citedDomains.length-6," more"]})]}),t.competitorDomains.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-negative-500/80",children:"Competitors:"}),t.competitorDomains.slice(0,4).map(o=>e.jsx("span",{className:"rounded-full border border-negative-900/40 bg-negative-950/30 px-2 py-0.5 text-[11px] text-negative",children:o},`co-${o}`)),t.competitorDomains.length>4&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.competitorDomains.length-4," more"]})]})]}),r&&e.jsx("button",{type:"button",className:"text-[11px] font-medium text-positive-400 hover:text-positive",onClick:o=>{o.stopPropagation(),s()},children:"View full answer →"})]})}function Dd({competitors:t,onSelectCompetitor:s,onRemoveCompetitor:n,activeFilter:a}){if(t.length===0)return e.jsx("p",{className:"text-sm text-muted",children:"No competitors configured. Add competitors to track overlap."});const r=s!=null,i=n!=null;return e.jsx("div",{className:"competitor-table-wrap",children:e.jsxs("table",{className:"competitor-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Domain"}),e.jsx("th",{children:"Pressure"}),e.jsx("th",{children:"Citations"}),e.jsx("th",{children:"Queries"}),i&&e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{children:t.map(o=>{const u=a!=null&&a.toLowerCase()===o.domain.toLowerCase(),d=[r?"cursor-pointer hover:bg-mono-800/30 transition-colors":"",u?"bg-negative-950/20":""].filter(Boolean).join(" ");return e.jsxs("tr",{className:d,onClick:r?()=>s(o.domain):void 0,title:r?`Filter answers to queries where ${o.domain} surfaced`:void 0,children:[e.jsx("td",{className:"font-medium text-heading",children:o.domain}),e.jsx("td",{children:e.jsx(oe,{tone:pl(o.pressureLabel),children:o.pressureLabel})}),e.jsx("td",{className:"text-neutral tabular-nums",children:o.totalQueries>0?`${o.citationCount} / ${o.totalQueries}`:"—"}),e.jsx("td",{className:"text-muted text-xs",children:o.citedQueries.length>0?o.citedQueries.join(", "):"Not cited"}),i&&e.jsx("td",{className:"text-right",children:e.jsx("button",{type:"button",className:"rounded px-1.5 py-0.5 text-xs text-muted transition-colors hover:text-negative-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-negative-500","aria-label":`Remove competitor ${o.domain}`,title:`Remove ${o.domain}`,onClick:h=>{h.stopPropagation(),n(o.domain)},children:"Remove"})})]},o.id)})})]})})}function bn({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 Ed=6,Fs="__other__",Rs="_socialTotal";function qd(t,s=Ed){const n=new Map;for(const x of t)n.set(x.source,(n.get(x.source)??0)+x.sessions);const a=[...n.entries()].sort((x,c)=>c[1]!==x[1]?c[1]-x[1]:x[0].localeCompare(c[0])),r=a.slice(0,s),i=new Set(r.map(([x])=>x)),o=Math.max(0,a.length-s),u=new Map;for(const x of t){let c=u.get(x.date);c||(c={date:x.date,[Rs]:0},u.set(x.date,c));const y=i.has(x.source)?x.source:Fs;c[y]=(c[y]??0)+x.sessions,c[Rs]=(c[Rs]??0)+x.sessions}const d=[...u.values()].sort((x,c)=>String(x.date).localeCompare(String(c.date))),h=r.map(([x])=>x);return o>0&&h.push(Fs),{data:d,sources:h,otherCount:o}}function $s(t){return t.replace(/\+/g," ")}function Ni(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const xr="_totalSessions",pr="_organicSessions";function Od(t,s){const n=new Map;for(const o of s)n.set(o.date,{[xr]:o.sessions,[pr]:o.organicSessions});for(const o of t.days){let u=n.get(o.date);u||(u={[xr]:0,[pr]:0},n.set(o.date,u));for(const d of o.bySource)u[d.source]=(u[d.source]??0)+d.sessions}const a=[...n.entries()].sort(([o],[u])=>o.localeCompare(u)).map(([o,u])=>({date:o,...u})),r=a.map(o=>o.date),i=r.length>0?{start:r[0],end:r[r.length-1]}:null;return{data:a,sources:t.sources,dateRange:i}}const Fd=["7d","30d","90d","all"],es=pt,ya=gt.textDim,wi=gt.textFaint,Vs=25;function _d(t){return yi(t.landingPage)}const Ud=25,Wn={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0};function jn(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function Si(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 Gd({projectName:t}){const{data:s,isLoading:n,isError:a}=Jc(t);if(n)return e.jsx(me,{className:"p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading server activity…"})});if(a)return e.jsx(me,{className:"p-5",children:e.jsx("div",{className:"text-sm text-negative-400",children:"Failed to load server activity."})});const r=s?.sources??[];return e.jsxs("section",{children:[e.jsx("div",{className:"flex items-baseline justify-between mb-3",children:e.jsxs("div",{children:[e.jsx("div",{className:"eyebrow",children:"Server activity (last 24h)"}),e.jsx("h2",{className:"text-lg font-semibold text-primary",children:"Server activity"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["Crawler, AI fetch, and referral activity from connected sources."," ",!Z()&&e.jsx(Ut,{to:"/traffic",className:"text-link hover:underline",children:"Manage sources →"})]})]})}),r.length===0?e.jsx(me,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-secondary",children:["No server traffic source connected yet."," ",!Z()&&e.jsxs(e.Fragment,{children:[e.jsx(Ut,{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(me,{className:"overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-bg-elevated/50 text-[10px] uppercase tracking-wide text-muted",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Source"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Status"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Crawler hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI sessions 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Last sync"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium","aria-label":"open"})]})}),e.jsx("tbody",{children:r.map(i=>e.jsxs("tr",{className:"border-t border-default",children:[e.jsx("td",{className:"px-4 py-3 text-heading",children:i.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(oe,{tone:Xc(i.status),children:i.status})}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:i.totals24h.crawlerHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:i.totals24h.aiUserFetchHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:i.totals24h.aiReferralHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right text-secondary text-xs",children:i.lastSyncedAt?Si(i.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:Z()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(Ut,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:i.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},i.id))})]})})]})}function Bd({projectName:t}){return e.jsxs("div",{className:"space-y-10",children:[e.jsx(Gd,{projectName:t}),e.jsx(zd,{projectName:t})]})}function zd({projectName:t}){const s=as(),[n,a]=l.useState(null),[r,i]=l.useState(null),[o,u]=l.useState(!0),[d,h]=l.useState(!1),[x,c]=l.useState(!1),[y,N]=l.useState(null),[f,b]=l.useState(null),[p,L]=l.useState("sessions"),[E,q]=l.useState("desc"),[$,g]=l.useState("sessions"),[v,w]=l.useState("desc"),[ee,W]=l.useState("sessions"),[A,j]=l.useState("desc"),[D,S]=l.useState("sessions"),[V,pe]=l.useState("desc"),[ne,X]=l.useState(Wn),[te,ce]=l.useState([]),[B,G]=l.useState([]),[P,re]=l.useState(!1),[le,C]=l.useState("30d");async function U(F){u(!0),N(null);try{const Ce=await s.fetchQuery({...gl({client:Q,path:{name:t}}),staleTime:zs});if(F.current)return;if(a(Ce),!Ce.connected){i(null),X(Wn),ce([]),G([]),u(!1);return}const de=le==="all"?void 0:le,[ve,Ke,Wt,st]=await Promise.all([s.fetchQuery({...fl({client:Q,path:{name:t},query:de?{window:de}:void 0}),staleTime:zs}).then(kt=>kt),s.fetchQuery({...bl({client:Q,path:{name:t},query:de?{window:de}:void 0}),staleTime:zs}).catch(()=>Wn),s.fetchQuery({...jl({client:Q,path:{name:t},query:de?{window:de}:void 0}),staleTime:zs}).catch(()=>[]),s.fetchQuery({...yl({client:Q,path:{name:t},query:de?{window:de}:void 0}),staleTime:zs}).catch(()=>[])]);if(F.current)return;i(ve),X(Ke),ce(Wt),G(st),u(!1)}catch(Ce){if(F.current)return;N(Ce instanceof Error?Ce.message:"Failed to load GA4 data"),u(!1)}}l.useEffect(()=>{const F={current:!1};return U(F),()=>{F.current=!0}},[t,le,s]);async function se(){h(!0),N(null),b(null);try{const F=await Jr(t);b(`Synced ${F.rowCount.toLocaleString()} page rows, ${F.aiReferralCount.toLocaleString()} AI and ${F.socialReferralCount.toLocaleString()} social referral rows (${F.days} days)`),await it(s,"ga"),await U({current:!1})}catch(F){N(F instanceof Error?F.message:"Sync failed")}finally{h(!1)}}async function M(){c(!0),N(null),b(null);try{await vl(t),await it(s,"ga"),a({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),i(null),b("GA4 disconnected")}catch(F){N(F instanceof Error?F.message:"Disconnect failed")}finally{c(!1)}}function z(F){p===F?q(Ce=>Ce==="desc"?"asc":"desc"):(L(F),q("desc"))}function we(F){$===F?w(Ce=>Ce==="desc"?"asc":"desc"):(g(F),w("desc"))}function Oe(F){ee===F?j(Ce=>Ce==="desc"?"asc":"desc"):(W(F),j("desc"))}const K=l.useMemo(()=>r?.topPages?[...r.topPages].sort((F,Ce)=>{const de=F[p],ve=Ce[p];return typeof de=="string"&&typeof ve=="string"?E==="asc"?de.localeCompare(ve):ve.localeCompare(de):E==="asc"?de-ve:ve-de}):[],[r?.topPages,p,E]),ge=l.useMemo(()=>r?.aiReferrals?[...r.aiReferrals].sort((F,Ce)=>{const de=F[$],ve=Ce[$];return typeof de=="string"&&typeof ve=="string"?v==="asc"?de.localeCompare(ve):ve.localeCompare(de):v==="asc"?de-ve:ve-de}):[],[r?.aiReferrals,$,v]),Te=l.useMemo(()=>r?.aiReferralLandingPages?[...r.aiReferralLandingPages].sort((F,Ce)=>{const de=F[D],ve=Ce[D];return typeof de=="string"&&typeof ve=="string"?V==="asc"?de.localeCompare(ve):ve.localeCompare(de):V==="asc"?de-ve:ve-de}):[],[r?.aiReferralLandingPages,D,V]),je=nn({rows:Te,getSearchText:_d,pageSize:Ud}),Be=je.totalRows>0?`${je.totalRows.toLocaleString()} ${je.hasQuery?je.totalRows===1?"match":"matches":je.totalRows===1?"row":"rows"}`:je.hasQuery&&(r?.aiReferralLandingPages.length??0)>0?"0 matches":"No landing-page rows";function et(F){je.setPage(1),D===F?pe(Ce=>Ce==="desc"?"asc":"desc"):(S(F),pe("desc"))}const Me=l.useMemo(()=>r?.socialReferrals?[...r.socialReferrals].sort((F,Ce)=>{const de=F[ee],ve=Ce[ee];return typeof de=="string"&&typeof ve=="string"?A==="asc"?de.localeCompare(ve):ve.localeCompare(de):A==="asc"?de-ve:ve-de}):[],[r?.socialReferrals,ee,A]),{socialChartData:J,socialChartSources:De,socialOtherCount:xe}=l.useMemo(()=>{const F=qd(B);return{socialChartData:F.data,socialChartSources:F.sources,socialOtherCount:F.otherCount}},[B]),{chartData:Qe,chartSources:O,dateRange:_}=l.useMemo(()=>{const F=Od(ne,te);return{chartData:F.data,chartSources:F.sources,dateRange:F.dateRange}},[ne,te]);if(o&&!n)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!n?.connected)return Z()?e.jsx(me,{className:"p-5",children:e.jsx("div",{className:"text-sm text-secondary",children:"No Google Analytics 4 property connected yet."})}):e.jsx(Vd,{projectName:t,onConnected:()=>{(async()=>(await it(s,"ga"),await U({current:!1})))()}});const fe=r?.organicSharePctDisplay??"0%",Ee=r?.channelBreakdown?.organic.sharePctDisplay??fe,Ue=r?.channelBreakdown?.organic.sessions??r?.totalOrganicSessions??0,Ve=r?.aiSessionsDeduped??0,Nt=r?.channelBreakdown?.ai.sessions??r?.aiSessionsBySession??0,bt=r?.channelBreakdown?.ai.sharePctDisplay??r?.aiSharePctBySessionDisplay??"0%",ke=r?.paidAiSessionsBySession??0,Fe=r?.paidAiSharePctBySessionDisplay??"0%",qt=r?new Set(r.aiReferrals.map(F=>F.source.toLowerCase())).size:0,tt=ge[0]??null,dt=r?.totalDirectSessions??0,Ye=r?.directSharePctDisplay??"0%",wt=r?.channelBreakdown?.direct.sessions??dt,St=r?.channelBreakdown?.direct.sharePctDisplay??Ye,Re=r?.channelBreakdown?.other.sessions??r?.otherSessions??0,Ae=r?.channelBreakdown?.other.sharePctDisplay??r?.otherSharePctDisplay??"0%",lt=r?.socialSessions??0,Ge=r?.socialSharePctDisplay??"0%",Ot=r?.channelBreakdown?.social.sessions??lt,Ct=r?.channelBreakdown?.social.sharePctDisplay??Ge,Je=r?new Set(r.socialReferrals.map(F=>F.source.toLowerCase())).size:0,He=Me[0]??null;return e.jsxs(e.Fragment,{children:[y&&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:y}),f&&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:f}),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})]})]})]}),!Z()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(k,{variant:"outline",size:"sm",disabled:d,onClick:Ie(se),children:[e.jsx(sn,{className:`w-3.5 h-3.5 mr-1.5 ${d?"animate-spin":""}`}),d?"Syncing…":"Sync"]}),e.jsxs(k,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:x,onClick:Ie(M),children:[e.jsx(xd,{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(Ze,{text:`Aggregated traffic metrics from Google Analytics 4. Sessions and users are summed across the selected period.${r?.periodStart&&r?.periodEnd?` Data available: ${new Date(r.periodStart+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})} – ${new Date(r.periodEnd+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}.`:""} Organic sessions are Google organic search sessions specifically.`})]})]}),e.jsx("div",{className:"segmented",role:"group","aria-label":"Traffic time period",children:Fd.map(F=>e.jsx("button",{type:"button","aria-pressed":le===F,className:`segmented-option ${le===F?"segmented-option-active":""}`,onClick:()=>C(F),children:F==="all"?"All":F},F))})]}),r?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(Yn,{value:jn(r.totalSessions),label:"Total Sessions",subtitle:r.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(Yn,{value:jn(r.totalOrganicSessions),label:"Organic Sessions",subtitle:`${fe} of total`,tone:"positive"}),e.jsx(Yn,{value:jn(r.totalUsers),label:"Total Users",subtitle:r.totalUsers.toLocaleString(),tone:"neutral"})]}):e.jsxs("div",{className:"surface-card rounded-lg p-6 text-center border border-default",children:[e.jsx("p",{className:"text-sm text-secondary mb-3",children:"No traffic data yet."}),!Z()&&e.jsxs(k,{variant:"outline",size:"sm",disabled:d,onClick:Ie(se),children:[e.jsx(sn,{className:`w-3.5 h-3.5 mr-1.5 ${d?"animate-spin":""}`}),"Sync from GA4"]})]})]}),r&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Traffic Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Traffic by channel",e.jsx(Ze,{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."})]})]}),_&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(_.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(_.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),Qe.length>0&&e.jsxs(me,{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:O.length>0?"AI vs. total sessions":"All sessions (baseline)"}),O.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),O.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(Ts,{width:"100%",height:"100%",children:e.jsxs(Ds,{data:Qe,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Es,{dataKey:"date",tick:Lt,tickLine:!1,axisLine:{stroke:Ht},tickFormatter:fa}),e.jsx(qs,{tick:Lt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Os,{...gs,labelFormatter:Ln,formatter:(F,Ce)=>{const de=typeof F=="number"?F.toLocaleString():String(F??0),ve=String(Ce??"");return ve==="_totalSessions"?[de,"Total Sessions"]:ve==="_organicSessions"?[de,"Organic Sessions"]:[de,ve]}}),e.jsx(mi,{wrapperStyle:{fontSize:11,color:gt.text},formatter:F=>F==="_totalSessions"?"Total Sessions":F==="_organicSessions"?"Organic Sessions":F}),e.jsx(ks,{type:"monotone",dataKey:"_totalSessions",stroke:gt.textFaint,fill:gt.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),O.map((F,Ce)=>e.jsx(ks,{type:"monotone",dataKey:F,stackId:"ai",stroke:es[Ce%es.length],fill:es[Ce%es.length],fillOpacity:.4,strokeWidth:1.5},F))]})})})]}),e.jsxs(me,{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(Dt,{label:"Organic",value:Ee,hint:`${Ue.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(Dt,{label:"Social",value:Ct,hint:`${Ot.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(Dt,{label:"Direct",value:St,hint:`${wt.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(Dt,{label:"Known AI referrers (lower bound)",value:bt,hint:ke>0?`${Nt.toLocaleString()} sessions · ${ke.toLocaleString()} paid`:`${Nt.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(Dt,{label:"Other channels",value:Ae,hint:`${Re.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."})]}),tt&&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:tt.source})," via ",tt.medium,", accounting for ",tt.sessions.toLocaleString()," sessions.",ke>0&&e.jsxs("span",{children:[" Paid AI: ",ke.toLocaleString()," sessions (",Fe,")."]})]})]}),e.jsxs(me,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Detail"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Known AI referrers by source"})]}),e.jsx("p",{className:"text-xs text-muted",children:r.aiReferrals.length>0?`${qt} unique sources, ${r.aiReferrals.length} rows`:"No source rows"})]}),r.aiReferrals.length>0?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(vt,{label:"Source",sortKey:"source",current:$,dir:v,onSort:we,align:"left"}),e.jsx(vt,{label:"Medium",sortKey:"medium",current:$,dir:v,onSort:we,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(vt,{label:"Sessions",sortKey:"sessions",current:$,dir:v,onSort:we,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:ge.map(F=>e.jsx(Qd,{referral:F,totalSessions:Ve},`${F.source}:${F.medium}:${F.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(me,{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:Be})]}),r.aiReferralLandingPages.length>0?e.jsxs(e.Fragment,{children:[e.jsx(As,{value:je.query,onChange:je.setQuery,label:"Filter landing page URLs or query parameters",placeholder:"Filter URL or query parameters",className:"mb-4 max-w-md"}),je.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(vt,{label:"Landing Page",sortKey:"landingPage",current:D,dir:V,onSort:et,align:"left"}),e.jsx(vt,{label:"Source",sortKey:"source",current:D,dir:V,onSort:et,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(vt,{label:"Sessions",sortKey:"sessions",current:D,dir:V,onSort:et,align:"right"})]})}),e.jsx("tbody",{children:je.rows.map(F=>e.jsx(Hd,{row:F},`${F.landingPage}:${F.source}:${F.medium}:${F.sourceDimension}`))})]})}),e.jsx(fs,{page:je.page,pageSize:je.pageSize,visibleRows:je.rows.length,totalRows:je.totalRows,onPageChange:je.setPage,itemLabel:je.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:()=>je.setQuery(""),className:"mt-2 text-xs text-link hover:underline focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",children:"Clear filter"})]})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No AI landing pages detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"Known-AI landing pages appear after a GA4 sync records visits from AI referrers."})]})]})]})]}),r&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Social Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Social Media Traffic",e.jsx(Ze,{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."})]})]}),J.length>0&&e.jsxs(me,{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"})]}),xe>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",De.length-1," sources · ",xe," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(Ts,{width:"100%",height:"100%",children:e.jsxs(Ds,{data:J,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Es,{dataKey:"date",tick:Lt,tickLine:!1,axisLine:{stroke:Ht},tickFormatter:fa}),e.jsx(qs,{tick:Lt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Os,{...gs,labelFormatter:Ln,formatter:(F,Ce)=>{const de=typeof F=="number"?F.toLocaleString():String(F??0),ve=String(Ce??"");if(ve===Rs)return[de,"Total Social"];if(ve===Fs){const Ke=`Other (${xe} source${xe===1?"":"s"})`;return[de,Ke]}return[de,$s(ve)]}}),e.jsx(ks,{type:"monotone",dataKey:Rs,stroke:wi,fill:gt.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),De.map((F,Ce)=>{const ve=F===Fs?ya:es[Ce%es.length];return e.jsx(ks,{type:"monotone",dataKey:F,stackId:"social",stroke:ve,fill:ve,fillOpacity:.4,strokeWidth:1.5},F)})]})})}),e.jsx(Yd,{sources:De,otherCount:xe})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.5fr)]",children:[e.jsxs(me,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Summary"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social media visits"})]}),r.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(Dt,{label:"Social Sessions",value:jn(lt),hint:`${lt.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(Dt,{label:"Share of Traffic",value:Ge,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(Dt,{label:"Platforms",value:String(Je),hint:`${r.socialReferrals.length} source rows`,tone:"neutral",tooltip:"Number of distinct social media platforms detected. Each unique source/medium combination counts as one source row."})]}),He&&e.jsxs("div",{className:"mt-4 rounded-lg border border-info-800/40 bg-info-500/6 px-4 py-3 text-sm text-info-100",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-info-300/70 mb-1",children:"Top social source"}),e.jsx("p",{className:"font-medium truncate",title:`${He.source} via ${He.medium}`,children:Ni($s(He.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:He.medium,children:["via ",$s(He.medium)," · ",He.sessions.toLocaleString()," sessions"]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(Dt,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(Dt,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(Dt,{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(me,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Breakdown"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Source / medium"})]}),e.jsx("p",{className:"text-xs text-muted",children:r.socialReferrals.length>0?Me.length>Vs&&!P?`Top ${Vs} of ${Me.length}`:`${Me.length} rows`:"No source rows"})]}),r.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm table-fixed",children:[e.jsxs("colgroup",{children:[e.jsx("col",{className:"w-[32%]"}),e.jsx("col",{className:"w-[22%]"}),e.jsx("col",{className:"w-[12%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[12%]"})]}),e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(vt,{label:"Source",sortKey:"source",current:ee,dir:A,onSort:Oe,align:"left"}),e.jsx(vt,{label:"Medium",sortKey:"medium",current:ee,dir:A,onSort:Oe,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(vt,{label:"Sessions",sortKey:"sessions",current:ee,dir:A,onSort:Oe,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(vt,{label:"Users",sortKey:"users",current:ee,dir:A,onSort:Oe,align:"right"})]})}),e.jsx("tbody",{children:(P?Me:Me.slice(0,Vs)).map(F=>e.jsx(Wd,{referral:F,totalSessions:lt},`${F.source}:${F.medium}:${F.channelGroup}`))})]})}),Me.length>Vs&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>re(F=>!F),className:"rounded-md border border-base px-3 py-1.5 text-xs text-secondary transition-colors hover:border-strong hover:text-strong",children:P?`Show top ${Vs}`:`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."})]})]})]})]})]}),r&&r.topPages.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Page Performance"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Top Landing Pages",e.jsx(Ze,{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(vt,{label:"Landing Page",sortKey:"landingPage",current:p,dir:E,onSort:z,align:"left"}),e.jsx(vt,{label:"Sessions",sortKey:"sessions",current:p,dir:E,onSort:z,align:"right"}),e.jsx(vt,{label:"Organic",sortKey:"organicSessions",current:p,dir:E,onSort:z,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"})]})}),e.jsx("tbody",{children:K.map(F=>e.jsx(Kd,{page:F},F.landingPage))})]})})]})]}),e.jsxs("div",{className:"mt-6 flex items-center justify-between text-xs text-muted",children:[e.jsx("span",{children:r?.lastSyncedAt?`Last synced ${Si(r.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:r?`${r.topPages.length} pages · ${r.aiReferrals.length} AI rows · ${r.socialReferrals.length} social rows`:""})]})]})}function Vd({projectName:t,onConnected:s}){const[n,a]=l.useState(""),[r,i]=l.useState(null),[o,u]=l.useState(null),[d,h]=l.useState(!1),[x,c]=l.useState(null),y=l.useRef(null),N=l.useCallback(b=>{const p=b.target.files?.[0];if(!p)return;c(null),i(p.name);const L=new FileReader;L.onload=()=>{const E=L.result;try{const q=JSON.parse(E);if(!q.client_email||!q.private_key){c("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(E)}catch{c("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),u(null)}},L.onerror=()=>{c("Failed to read file."),u(null)},L.readAsText(p)},[]);async function f(){if(c(null),!n.trim()){c("Property ID is required.");return}if(!o){c("Please upload a service account key file.");return}h(!0);try{await Nl(t,{propertyId:n.trim(),keyJson:o});try{await Jr(t)}catch{}s()}catch(b){c(b instanceof Error?b.message:"Failed to connect GA4")}finally{h(!1)}}return e.jsxs(me,{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."}),x&&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:x}),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:b=>a(b.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:y,type:"file",accept:".json,application/json",onChange:N,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>y.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(gd,{className:"w-4 h-4 shrink-0"}),r?e.jsx("span",{className:"text-strong truncate",children:r}):e.jsx("span",{children:"Upload .json key file"})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Download from Google Cloud Console → IAM & Admin → Service Accounts → Keys → Add Key → JSON. The service account must have ",e.jsx("span",{className:"text-secondary",children:"Viewer"})," access on the GA4 property."]})]}),e.jsx(k,{variant:"default",size:"sm",disabled:d||!n.trim()||!o,onClick:Ie(f),children:d?"Connecting & syncing…":"Connect GA4"})]})}function vt({label:t,sortKey:s,current:n,dir:a,onSort:r,align:i}){const o=n===s;return e.jsx("th",{className:`py-1 ${i==="right"?"text-right":"text-left"}`,children:e.jsxs("button",{type:"button",className:"font-medium cursor-pointer select-none hover:text-neutral transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-400 rounded",onClick:()=>r(s),"aria-label":`Sort by ${t}${o?` (currently ${a==="asc"?"ascending":"descending"})`:""}`,children:[t,o&&e.jsx("span",{className:"ml-0.5",children:a==="asc"?"↑":"↓"})]})})}const Ci={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function Yn({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 ${Ci[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Dt({value:t,label:s,hint:n,tone:a,tooltip:r}){return e.jsxs("div",{className:"rounded-lg border border-default bg-bg/40 px-4 py-3 flex flex-col",children:[e.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1 flex items-center gap-1",children:[s,r&&e.jsx(Ze,{text:r})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${Ci[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Kd({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 ki={session:"Session",first_user:"First Visit",manual_utm:"UTM"},Pi={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 Qd({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=ki[t.sourceDimension]??t.sourceDimension,r=Pi[t.sourceDimension]??"",i=t.trafficClass==="paid"?"Paid":"Organic",o=t.trafficClass==="paid"?"Paid AI traffic inferred from paid/cpc/sponsored UTM values or a GA4 paid channel group":"AI traffic without a paid attribution signal";return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 text-strong max-w-[220px] truncate",title:t.source,children:t.source}),e.jsx("td",{className:"py-1.5 text-muted max-w-[180px] truncate",title:t.medium,children:t.medium}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:`inline-block text-[10px] px-1.5 py-0.5 rounded-full border ${t.trafficClass==="paid"?"border-caution-700 text-caution-300":"border-strong text-secondary"}`,title:o,children:i})}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:r,children:a})}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[n,"%"]})]})}function Hd({row:t}){const s=ki[t.sourceDimension]??t.sourceDimension,n=Pi[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(Xs,{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 Wd({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=t.channelGroup==="Paid Social"?"Paid":"Organic",r=$s(t.source),i=$s(t.medium);return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 pr-3 text-strong truncate",title:t.source,children:r}),e.jsx("td",{className:"py-1.5 pr-3 text-muted truncate",title:t.medium,children:i}),e.jsx("td",{className:"py-1.5 pr-3",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:`GA4 channel group: ${t.channelGroup}`,children:a})}),e.jsx("td",{className:"py-1.5 text-right text-info-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[n,"%"]}),e.jsx("td",{className:"py-1.5 text-right text-strong tabular-nums",children:t.users.toLocaleString()})]})}function Yd({sources:t,otherCount:s}){const n=[{key:Rs,color:wi,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const r=t[a];if(r===Fs)n.push({key:Fs,color:ya,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const i=$s(r);n.push({key:r,color:es[a%es.length]??ya,label:Ni(i,32),tooltip:i})}}return e.jsx("div",{className:"mt-3 flex flex-wrap gap-x-4 gap-y-1.5 text-[11px] text-secondary",children:n.map(a=>e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 max-w-[260px]",title:a.tooltip,children:[e.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-sm shrink-0",style:{backgroundColor:a.color},"aria-hidden":"true"}),e.jsx("span",{className:"truncate",children:a.label})]},a.key))})}function Jd(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 Xd=["7d","30d","90d","all"],yn=500,Xt=25,Zd="canonry:google-oauth-complete";function gr(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function fr(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 br(t){return t.isPending?"Processing":Number(t.errors??0)>0?"Errors":Number(t.warnings??0)>0?"Warnings":"Success"}function eu({projectName:t,refreshNonce:s}){const n=as(),[a,r]=l.useState(!1),[i,o]=l.useState([]),[u,d]=l.useState([]),[h,x]=l.useState([]),[c,y]=l.useState(null),[N,f]=l.useState([]),[b,p]=l.useState([]),[L,E]=l.useState(null),[q,$]=l.useState(""),[g,v]=l.useState(""),[w,ee]=l.useState("30"),[W,A]=l.useState(!1),[j,D]=l.useState("30d"),[S,V]=l.useState({startDate:"",endDate:"",query:"",page:""}),[pe,ne]=l.useState(0),[X,te]=l.useState(!1),[ce,B]=l.useState(0),[G,P]=l.useState(!1),[re,le]=l.useState(""),[C,U]=l.useState(!0),[se,M]=l.useState(!1),[z,we]=l.useState(!1),[Oe,K]=l.useState(!1),[ge,Te]=l.useState(!1),[je,Be]=l.useState(!1),[et,Me]=l.useState(!1),[J,De]=l.useState(null),[xe,Qe]=l.useState(!1),[O,_]=l.useState(!1),[fe,Ee]=l.useState(null),[Ue,Ve]=l.useState(null),[Nt,bt]=l.useState([]),[ke,Fe]=l.useState(new Set),[qt,tt]=l.useState({}),[dt,Ye]=l.useState(new Set),[wt,St]=l.useState(""),[Re,Ae]=l.useState(null),[lt,Ge]=l.useState(""),[Ot,Ct]=l.useState(!1),[Je,He]=l.useState(!1),[F,Ce]=l.useState(!1),[de,ve]=l.useState(!1),[Ke,Wt]=l.useState("indexed"),[st,kt]=l.useState(null),rs=!!(S.query.trim()||S.page.trim()||st),R=st!==null,be=l.useMemo(()=>{if(!st)return h;const{key:m,dir:T}=st;return[...h].sort((ae,ue)=>{const $e=m===xs.CTR?Number.isFinite(ae.ctr)?ae.ctr:0:ae[m],qe=m===xs.CTR?Number.isFinite(ue.ctr)?ue.ctr:0:ue[m];return T==="asc"?$e-qe:qe-$e})},[h,st]),ye=nn({rows:be,pageSize:Et}),Pt=G?ye.rows:be,nt=nn({rows:(fe??[]).filter(m=>m.path.toLowerCase().includes(wt.trim().toLowerCase())),pageSize:Et}),[At,dn]=l.useState([]),[jt,is]=l.useState(null),[En,un]=l.useState(1),ls=l.useMemo(()=>{if(At.length<2)return null;const m=At[At.length-1],T=At[At.length-2];return{indexed:m.indexed-T.indexed,notIndexed:m.notIndexed-T.notIndexed}},[At]);l.useEffect(()=>{un(1)},[J,Ke,jt]);const js=l.useMemo(()=>jt?(J?.reasonGroups??[]).find(m=>m.reason===jt):void 0,[J,jt]),Us=l.useMemo(()=>J?Ke==="indexed"?J.indexed:Ke==="deindexed"?J.deindexed:Ke==="notIndexed"?jt?js?.urls??[]:(J.reasonGroups??[]).length===0?J.notIndexed:[]:[]:[],[J,Ke,jt,js]),qn=Math.max(1,Math.ceil(Us.length/Xt)),mn=Math.min(Math.max(1,En),qn),ut=(mn-1)*Xt,ys=l.useMemo(()=>J?.indexed.slice(ut,ut+Xt)??[],[J,ut]),On=l.useMemo(()=>J?.notIndexed.slice(ut,ut+Xt)??[],[J,ut]),Fn=l.useMemo(()=>J?.deindexed.slice(ut,ut+Xt)??[],[J,ut]),I=l.useMemo(()=>(js?.urls??[]).slice(ut,ut+Xt),[js,ut]),[Y,he]=l.useState(!1),[ie,H]=l.useState(null),[Se,Mt]=l.useState(null),[ot,yt]=l.useState(null);function Yt(m,T){const ae=Zc(m),ue=Jd(ae);ue?(Mt(ue),H(null)):(Mt(null),H(ae.message||T))}const at=i.find(m=>m.connectionType==="gsc"),os=(at?.scopes??[]).includes("https://www.googleapis.com/auth/webmasters"),_n=Nt.length>0?Nt:(fe??[]).map(m=>m.path),Va=_n.filter(m=>fe?.some(T=>T.path===m&&T.isSitemapsIndex)).length,Qi=Va===1?"Resubmit sitemap index":Va>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",Hi=h.length>0||N.length>0||b.length>0,Un=wl(),Gn=Sl();async function Ka(m,T=!1){if(!m){d([]),$("");return}we(!0);try{const{sites:ae}=await n.fetchQuery({...ql({client:Q,path:{name:t}}),staleTime:T?0:ct});d(ae),$(m.propertyId??ae[0]?.siteUrl??""),Mt(null)}catch(ae){d([]),Yt(ae,"Failed to load Search Console properties")}finally{we(!1)}}async function Gs(m){Te(!0);const T=m??pe;try{const ae=rs?yn:Et,ue=rs?0:T,$e={limit:String(ae)};S.startDate&&($e.startDate=S.startDate),S.endDate&&($e.endDate=S.endDate),S.query&&($e.query=S.query),S.page&&($e.page=S.page),ue>0&&($e.offset=String(ue)),j&&j!=="all"&&!S.startDate&&($e.window=j);const qe=await n.fetchQuery({...kl({client:Q,path:{name:t},query:$e}),staleTime:ct}),_e=qe.rows;rs?(te(!1),x(_e),B(_e.length),P(!0)):(te(ue+_e.length<qe.totalMatching),x(_e),B(0),P(!1))}catch(ae){x([]),te(!1),B(0),H(ae instanceof Error?ae.message:"Failed to load GSC performance data")}finally{Te(!1)}}async function Bn(){try{const m={};S.startDate&&(m.startDate=S.startDate),S.endDate&&(m.endDate=S.endDate),j&&j!=="all"&&!S.startDate&&(m.window=j);const T=await n.fetchQuery({...Pl({client:Q,path:{name:t},query:m}),staleTime:ct});y(T)}catch{y(null)}}async function hn(m=!1){Be(!0);try{const T=re.trim()||void 0,ae={limit:"20"};T&&(ae.url=T);const[ue,$e]=await Promise.all([n.fetchQuery({...Dl({client:Q,path:{name:t},query:ae}),staleTime:m?0:ct}),n.fetchQuery({...El({client:Q,path:{name:t}}),staleTime:m?0:ct})]);f(ue),p($e)}catch(T){f([]),p([]),H(T instanceof Error?T.message:"Failed to load GSC inspection history")}finally{Be(!1)}}async function Qa(m=!1){Qe(!0);try{const[T,ae]=await Promise.all([n.fetchQuery({...Zr({client:Q,path:{name:t}}),staleTime:m?0:ct}),n.fetchQuery({...$l({client:Q,path:{name:t}}),staleTime:m?0:ct}).catch(()=>[])]);De(T),dn(ae)}catch(T){De(null),dn([]),H(T instanceof Error?T.message:"Failed to load coverage data")}finally{Qe(!1)}}async function Ha(m){he(!0),H(null);try{const T=await sr(t,{urls:m}),{succeeded:ae,failed:ue,total:$e}=T.summary;Ne({title:"Indexing requested",detail:ue===0?`${ae} URL${ae!==1?"s":""} submitted for indexing.`:`${ae}/${$e} submitted successfully, ${ue} failed.`,tone:ue===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(T){H(T instanceof Error?T.message:"Failed to request indexing")}finally{he(!1)}}async function Wi(){he(!0),H(null);try{const m=await sr(t,{urls:[],allUnindexed:!0}),{succeeded:T,failed:ae,total:ue}=m.summary;Ne({title:"Indexing requested",detail:ae===0?`${T} unindexed URL${T!==1?"s":""} submitted for indexing.`:`${T}/${ue} submitted successfully, ${ae} failed.`,tone:ae===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(m){H(m instanceof Error?m.message:"Failed to request indexing")}finally{he(!1)}}async function zn(){_(!0),H(null);try{const m=await Vn(t);n.setQueryData(Il({client:Q,path:{name:t}}),m),Ee(m.sitemaps),Ve(m.summary),bt(m.preferredSubmissionUrls),Fe(new Set),tt({}),m.sitemaps.length===0&&yt("No sitemaps found in this GSC property. Submit one here to start Google processing it.")}catch(m){H(m instanceof Error?m.message:"Failed to list sitemaps")}finally{_(!1)}}async function Yi(m){const T=ke.has(m);if(Fe(ae=>{const ue=new Set(ae);return T?ue.delete(m):ue.add(m),ue}),!(T||qt[m])){Ye(ae=>new Set(ae).add(m));try{const ae=await Vn(t,m);tt(ue=>({...ue,[m]:ae.sitemaps}))}catch(ae){H(ae instanceof Error?ae.message:"Failed to load sitemap files")}finally{Ye(ae=>{const ue=new Set(ae);return ue.delete(m),ue})}}}async function vs(m){if(!os||m.length===0)return;const T=[...new Set(m)];He(!0),H(null),Ae({completed:0,total:T.length});let ae=0,ue=0,$e=0,qe=null;try{for(let Xe=0;Xe<T.length;Xe+=50){const Pe=T.slice(Xe,Xe+50);try{const mt=await Ll(t,Pe);ae+=mt.summary.accepted,ue+=mt.summary.failed,$e+=Pe.length,Ae({completed:$e,total:T.length})}catch(mt){$e+=Pe.length;const Tt=Pe.length,cs=T.length-$e,Ns=mt instanceof Error?mt.message:"The batch request failed",Bs=`${ae} accepted, ${ue} failed, ${Tt} unconfirmed, ${cs} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;qe=`Sitemap submission stopped after a batch request failed. ${Bs} ${Ns}`,H(qe),Ne({title:"Sitemap resubmission partially completed",detail:Bs,tone:"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"});return}}const _e=T.length;Ne({title:ue===0?"Sitemap submitted to Google":"Some sitemap submissions need attention",detail:ue===0?"Google accepted the sitemap submission/refetch request; indexing is not guaranteed.":`Google accepted ${ae}/${_e} sitemap submissions; ${ue} failed. Indexing is not guaranteed.`,tone:ue===0?"positive":"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"}),Ge("")}catch(_e){H(_e instanceof Error?_e.message:"Failed to submit sitemap to Google")}finally{He(!1),Ae(null),await zn(),qe&&H(qe)}}async function Ji(){He(!0);const m=fe??[];try{const T=m.filter(ue=>ue.isSitemapsIndex),ae=[];for(let ue=0;ue<T.length;ue+=4)(await Promise.all(T.slice(ue,ue+4).map(async qe=>{const _e=qt[qe.path];if(_e)return _e;const Xe=await Vn(t,qe.path);return tt(Pe=>({...Pe,[qe.path]:Xe.sitemaps})),Xe.sitemaps}))).forEach((qe,_e)=>{ae.push(...qe.length>0?qe.map(Xe=>Xe.path):[T[ue+_e].path])});await vs([...m.filter(ue=>!ue.isSitemapsIndex).map(ue=>ue.path),...ae])}catch(T){H(T instanceof Error?T.message:"Failed to load sitemap files"),He(!1)}}async function Wa(m){Ct(!0),H(null);try{await Ml(t,"gsc",m),await it(n,"google"),o(T=>T.map(ae=>ae.connectionType==="gsc"?{...ae,sitemapUrl:m}:ae)),Ne({title:"Default sitemap updated",detail:m,tone:"positive",dedupeKey:`gsc:sitemap-default:${t}`,dedupeMode:"replace"})}catch(T){H(T instanceof Error?T.message:"Failed to set the default sitemap")}finally{Ct(!1)}}async function Ya(m){try{await Gn.mutateAsync({projectName:t,projectLabel:t,opts:m?{sitemapUrl:m}:void 0})}catch{}}async function Ja(){U(!0),H(null);try{const[m,T]=await Promise.all([Xr().catch(()=>null),n.fetchQuery({...Ra({client:Q,path:{name:t}}),staleTime:ct}).catch(()=>[])]);r(!!m?.google?.configured),o(T);const ae=T.find(ue=>ue.connectionType==="gsc");await Promise.all([Ka(ae),Gs(),Bn(),hn(),Qa(),ae?.propertyId?zn():Promise.resolve()])}finally{U(!1)}}l.useEffect(()=>{Ja()},[t,s]),l.useEffect(()=>{ne(0),Gs(0),Bn()},[j]);const Xa=l.useRef(!1);l.useEffect(()=>{if(!Xa.current){Xa.current=!0;return}ne(0),Gs(0)},[R]);async function Za(){if(!a){H("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}M(!0),H(null),yt(null);try{let m=function(mt){if(mt.source!==ue||mt.origin!==$e||!mt.data||typeof mt.data!="object")return;const Tt=mt.data;Tt.type!==Zd||Tt.connectionType!=="gsc"||Pe(!0)};const{authUrl:T,redirectUri:ae}=await Rl(t,"gsc");if(!T.startsWith("https://accounts.google.com/")){H("Unexpected OAuth redirect URL. Please try again.");return}const ue=window.open(T,"_blank","width=600,height=700");if(!ue){window.location.assign(T);return}const $e=ae?new URL(ae).origin:window.location.origin;let qe=!1,_e=null;const Xe=()=>{_e!==null&&window.clearInterval(_e),window.removeEventListener("message",m)},Pe=async mt=>{if(!qe){qe=!0,Xe(),yt(mt?"Google connected. Refreshing access…":"Refreshing Google connection…");try{await it(n,"google"),await Ja()}finally{yt(null)}}};window.addEventListener("message",m),yt("Finish the Google consent flow in the popup. This page will refresh automatically."),_e=window.setInterval(()=>{ue.closed&&Pe(!1)},1e3)}catch(m){H(m instanceof Error?m.message:"Failed to start OAuth flow")}finally{M(!1)}}async function Xi(){H(null),yt(null);try{await Al(t,"gsc"),await it(n,"google"),o(m=>m.filter(T=>T.connectionType!=="gsc")),d([]),$("")}catch(m){H(m instanceof Error?m.message:"Failed to disconnect")}}async function Zi(){if(q){K(!0),H(null);try{await Ol(t,"gsc",q),await it(n,"google"),o(m=>m.map(T=>T.connectionType==="gsc"?{...T,propertyId:q}:T)),Ne({title:"GSC property updated",detail:`${t} is now linked to ${q}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(m){H(m instanceof Error?m.message:"Failed to save GSC property")}finally{K(!1)}}}async function el(){H(null),yt(null);try{await Un.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(w,10)||void 0,full:W||void 0}}),await it(n,"gsc")}catch{}}async function er(){if(g.trim()){Me(!0),H(null),yt(null);try{const m=await Tl(t,g.trim());await it(n,"gsc"),E(m),v(""),await hn()}catch(m){H(m instanceof Error?m.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"})]})}),Se&&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:Se.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:Se.message}),(ms(Se.enableUrl)||ms(Se.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[ms(Se.enableUrl)&&e.jsx("a",{href:ms(Se.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 ↗"}),ms(Se.indexingApiUrl)&&e.jsx("a",{href:ms(Se.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:()=>Mt(null),children:"×"})]})}),ie&&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:[ie,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>H(null),children:"×"})]}),ot&&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:[ot,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>yt(null),children:"×"})]}),C?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[at?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:at.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Last updated ",_t(at.updatedAt)]}),e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:Ie(Xi),children:"Disconnect"})]}):e.jsxs(me,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(oe,{tone:a?"caution":"negative",children:a?"Ready to connect":"App credentials missing"})]}),e.jsxs("div",{className:"mt-3 rounded-lg border border-default bg-surface px-4 py-5",children:[e.jsx("p",{className:"text-sm text-neutral",children:a?"Generate a Google OAuth link for this project and have the client sign in with a Google account that already has access to the correct Search Console property.":"Set Google OAuth client credentials first. Once configured, you can generate a consent link for this project domain."}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[a?e.jsx(k,{type:"button",variant:"outline",size:"sm",disabled:se,onClick:Ie(Za),children:se?"Opening…":"Connect Google Search Console"}):e.jsx(k,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(Ut,{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."})]})]})]}),(at||Hi)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs(me,{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:Xd.map(m=>e.jsx("button",{type:"button","aria-pressed":j===m,className:`segmented-option ${j===m?"segmented-option-active":""}`,onClick:()=>{D(m),ne(0),ye.setPage(1)},children:m==="all"?"All":m},m))}),e.jsx(k,{type:"button",variant:"outline",size:"sm",disabled:ge,onClick:()=>{ne(0),ye.setPage(1),Gs(0),Bn()},children:ge?"Loading…":"Apply filters"})]})]}),c&&c.daily.length>0&&(()=>{const m=c.daily,T=Math.max(...m.map(ze=>ze.impressions),1),{clicks:ae,impressions:ue,ctr:$e}=c.totals,qe=($e*100).toFixed(1),_e=700,Xe=220,Pe={top:12,bottom:36,left:48,right:12},mt=_e-Pe.left-Pe.right,Tt=Xe-Pe.top-Pe.bottom,cs=mt/m.length,Ns=Math.max(Math.min(cs*.35,24),4),Bs=Math.max(Ns*.15,1),tl=ze=>{if(ze<=0)return 1;const Bt=Math.pow(10,Math.floor(Math.log10(ze))),Rt=ze/Bt,Jt=Rt<=1.5?1.5:Rt<=3?3:Rt<=5?5:10;return Math.ceil(Jt*Bt)},xn=4,pn=Math.ceil(tl(T)/xn)*xn,sl=Array.from({length:xn+1},(ze,Bt)=>pn/xn*Bt),nl=ze=>ze>=1e3?`${(ze/1e3).toFixed(ze>=1e4?0:1)}k`:String(ze);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:ae.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:ue.toLocaleString()})]})]}),e.jsxs("span",{className:"text-xs text-muted",children:["CTR ",e.jsxs("span",{className:"text-caution-400 tabular-nums font-medium",children:[qe,"%"]})]})]}),e.jsx("div",{className:"relative w-full",style:{aspectRatio:`${_e} / ${Xe}`},children:e.jsxs("svg",{viewBox:`0 0 ${_e} ${Xe}`,className:"h-full w-full",children:[sl.map((ze,Bt)=>{const Rt=Pe.top+Tt-ze/pn*Tt;return e.jsxs("g",{children:[e.jsx("line",{x1:Pe.left,y1:Rt,x2:_e-Pe.right,y2:Rt,stroke:gt.gridLine,strokeWidth:"1"}),e.jsx("text",{x:Pe.left-6,y:Rt+3.5,textAnchor:"end",fill:gt.text,fontSize:"10",fontFamily:"inherit",children:nl(ze)})]},`t-${Bt}`)}),m.map((ze,Bt)=>{const Rt=Pe.left+cs*Bt+cs/2,Jt=ze.impressions/pn*Tt,gn=ze.clicks/pn*Tt;return e.jsxs("g",{children:[e.jsx("title",{children:`${ze.date}
2
2
  Clicks: ${ze.clicks}
3
3
  Impressions: ${ze.impressions}
4
4
  CTR: ${(ze.ctr*100).toFixed(1)}%`}),e.jsx("rect",{x:Rt-Ns-Bs/2,y:Pe.top+Tt-Jt,width:Ns,height:Math.max(Jt,1),rx:2,fill:pt[1],opacity:.85}),e.jsx("rect",{x:Rt+Bs/2,y:Pe.top+Tt-gn,width:Ns,height:Math.max(gn,1),rx:2,fill:Qt.positiveDeep,opacity:.85})]},ze.date)}),(()=>{const ze=Math.min(m.length,7);return Array.from({length:ze},(Bt,Rt)=>{const Jt=m.length===1?0:Math.round(Rt/(ze-1)*(m.length-1)),gn=Pe.left+cs*Jt+cs/2;return e.jsx("text",{x:gn,y:Xe-8,textAnchor:"middle",fill:gt.textDim,fontSize:"10",fontFamily:"inherit",children:m[Jt].date.slice(5)},`xl-${Jt}`)})})()]})})]})})(),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:S.startDate,onChange:m=>V(T=>({...T,startDate:m.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:S.endDate,onChange:m=>V(T=>({...T,endDate:m.target.value}))}),e.jsx(As,{value:S.query,onChange:m=>V(T=>({...T,query:m})),label:"Filter search queries",placeholder:"Contains query…"}),e.jsx(As,{value:S.page,onChange:m=>V(T=>({...T,page:m})),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 ",yn.toLocaleString()," matching rows while the table stays at ",Et," rows per page."]}),h.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Date"}),e.jsx("th",{className:"text-left",children:"Query"}),e.jsx("th",{className:"text-left",children:"Page"}),Object.values(xs).map(m=>e.jsx("th",{className:"text-right","aria-sort":st?.key===m?st.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:()=>{ye.setPage(1),kt(T=>T?.key===m?T.dir==="desc"?{key:m,dir:"asc"}:null:{key:m,dir:"desc"})},children:[Cl[m],st?.key===m?st.dir==="desc"?" ↓":" ↑":""]})},m))]})}),e.jsx("tbody",{children:Pt.map((m,T)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:m.date}),e.jsx("td",{className:"max-w-xs truncate text-strong",children:m.query}),e.jsx("td",{className:"max-w-xs text-secondary",children:e.jsx(Xs,{value:m.page})}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:m.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:m.impressions.toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[(Number.isFinite(m.ctr)?m.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:m.position.toFixed(1)})]},`${m.date}:${m.query}:${m.page}:${T}`))})]})}),e.jsx(fs,{page:G?ye.page:Math.floor(pe/Et)+1,pageSize:Et,visibleRows:Pt.length,totalRows:G?ce:void 0,hasNextPage:G?void 0:X,disabled:ge,itemLabel:G?"matches":"rows",onPageChange:m=>{if(G){ye.setPage(m);return}const T=(m-1)*Et;ne(T),Gs(T)}}),G&&ce>=yn?e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Results are capped at ",yn.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(me,{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:[J&&J.notIndexed.length>0&&e.jsx(k,{type:"button",variant:"outline",size:"sm",disabled:Y,onClick:()=>{Wi()},children:Y?"Requesting…":`Request indexing (${J.notIndexed.length})`}),e.jsx(k,{type:"button",variant:"outline",size:"sm",disabled:xe,onClick:()=>{Qa(!0)},children:xe?"Loading…":"Reload saved coverage"})]})]}),J&&J.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const m=J.summary.indexed+J.summary.notIndexed,T=m>0?J.summary.indexed/m:0,ae=m>0?J.summary.notIndexed/m:0,ue=54,$e=2*Math.PI*ue,qe=$e*(1-T),_e=$e*ae,Xe=$e*T;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:ue,fill:"none",stroke:gt.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:ue,fill:"none",stroke:Qt.positiveDeep,strokeWidth:"14",strokeDasharray:$e,strokeDashoffset:qe,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),J.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:ue,fill:"none",stroke:gt.textFaint,strokeWidth:"14",strokeDasharray:`${_e} ${$e-_e}`,strokeDashoffset:-Xe,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:[(T*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:J.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:J.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:["Not indexed",(J.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-faint",children:["· ",(J.reasonGroups??[]).length," ",(J.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),J.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:J.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(m=>{const T=m==="indexed"?J.indexed.length:m==="notIndexed"?J.notIndexed.length:J.deindexed.length,ae=m==="indexed"?"Indexed":m==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",role:"tab","aria-selected":Ke===m,className:`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${Ke===m?"border-accent text-heading":"border-transparent text-secondary hover:border-mono-600 hover:text-strong"}`,onClick:()=>{Wt(m),is(null)},children:[ae," (",T,")"]},m)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[Ke==="indexed"&&J.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:ys.map(m=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:m.url}),e.jsx("td",{className:"text-secondary",children:m.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:m.crawlTime?m.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:m.isMobileFriendly===!0?"Yes":m.isMobileFriendly===!1?"No":"—"})]},m.id))})]}),Ke==="notIndexed"&&!jt&&(J.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:(J.reasonGroups??[]).map(m=>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:()=>is(m.reason),onKeyDown:T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),is(m.reason))},tabIndex:0,role:"button","aria-label":`View ${m.reason} pages`,children:[e.jsx("td",{className:"text-strong",children:m.reason}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:m.count})]},m.reason))})]}),Ke==="notIndexed"&&!jt&&(J.reasonGroups??[]).length===0&&J.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:On.map(m=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:m.url}),e.jsx("td",{className:"text-secondary",children:m.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:m.coverageState??"Unknown"})]},m.id))})]}),Ke==="notIndexed"&&jt&&(()=>{const m=(J.reasonGroups??[]).find(T=>T.reason===jt);return m?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:()=>is(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:m.reason}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[m.count," affected page",m.count!==1?"s":""]})]}),e.jsx(k,{type:"button",variant:"outline",size:"sm",disabled:Y,onClick:()=>{Ha(m.urls.map(T=>T.url))},children:Y?"Requesting…":`Request indexing (${m.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:I.map(T=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:T.url}),e.jsx("td",{className:"text-secondary",children:T.crawlTime?T.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-strong transition-colors",disabled:Y,onClick:()=>{Ha([T.url])},title:"Request indexing",children:"Index"})})]},T.id))})]})]}):null})(),Ke==="deindexed"&&J.deindexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Previous"}),e.jsx("th",{className:"text-left",children:"Current"}),e.jsx("th",{className:"text-left",children:"Detected"})]})}),e.jsx("tbody",{children:Fn.map((m,T)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:m.url}),e.jsx("td",{className:"text-secondary",children:m.previousState}),e.jsx("td",{className:"text-secondary",children:m.currentState}),e.jsx("td",{className:"text-secondary",children:m.transitionDate.split("T")[0]})]},`${m.url}-${T}`))})]}),(Ke==="indexed"&&J.indexed.length===0||Ke==="notIndexed"&&!jt&&J.notIndexed.length===0||Ke==="deindexed"&&J.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),e.jsx(fs,{page:mn,pageSize:Xt,visibleRows:Math.min(Xt,Us.length-ut),totalRows:Us.length,onPageChange:un,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":de,onClick:()=>ve(m=>!m),children:[e.jsx("span",{children:"Coverage history"}),e.jsx("span",{children:de?"Hide snapshots":At.length>0?`View ${At.length} snapshots`:"View history"})]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["Current: ",J.summary.indexed.toLocaleString()," indexed, ",J.summary.notIndexed.toLocaleString()," not indexed.",ls&&e.jsxs(e.Fragment,{children:[" Since the last snapshot: ",ls.indexed>=0?"+":"",ls.indexed.toLocaleString()," indexed, ",ls.notIndexed>=0?"+":"",ls.notIndexed.toLocaleString()," not indexed."]})]}),de&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:At.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:At.map(m=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:m.date}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:m.indexed.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:m.notIndexed.toLocaleString()})]},m.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:xe?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),e.jsxs(me,{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(k,{type:"button",variant:"outline",size:"sm",disabled:O||!at?.propertyId,onClick:()=>{zn()},children:O?"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:lt,onChange:m=>Ge(m.target.value),onKeyDown:m=>m.key==="Enter"&&void vs([lt.trim()])}),e.jsx(k,{type:"button",size:"sm",disabled:!os||Je||!lt.trim(),onClick:()=>{vs([lt.trim()])},children:Je?"Submitting…":"Submit sitemap to Google"})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(k,{type:"button",size:"sm",variant:"outline",disabled:!os||Je||_n.length===0,onClick:()=>{vs(_n)},children:Je?"Resubmitting…":Qi}),e.jsx(k,{type:"button",size:"sm",variant:"outline",disabled:!os||Je||!fe?.length,onClick:()=>{Ji()},children:"Resubmit all files"}),Ue&&e.jsxs("span",{className:"text-xs text-muted",children:["Top level: ",Ue.indexes," index",Ue.indexes===1?"":"es",", ",Ue.files," file",Ue.files===1?"":"s"]}),Re&&e.jsxs("span",{className:"text-xs text-secondary",children:["Submitting ",Re.completed,"/",Re.total]})]}),e.jsx("p",{className:"mt-2 text-xs text-muted",children:"Google is asked to refetch these sitemaps. Indexing is not guaranteed."}),!os&&at&&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:Ie(Za),children:"Reconnect"})]}),fe&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:fe.length>0?e.jsxs(e.Fragment,{children:[e.jsx(As,{value:wt,onChange:m=>{St(m),nt.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:nt.rows.flatMap(m=>{const T=gr(m),ae=fr(m),ue=br(m),$e=qt[m.path]??[],qe=ke.has(m.path),_e=e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs text-strong",children:e.jsx(Xs,{value:m.path})}),e.jsx("td",{className:"text-secondary",children:m.isSitemapsIndex?e.jsx("button",{type:"button",className:"text-secondary hover:text-strong","aria-expanded":qe,"aria-label":`${qe?"Collapse":"Expand"} files in ${m.path}`,onClick:()=>{Yi(m.path)},children:dt.has(m.path)?"Loading…":`${qe?"▾":"▸"} Index${qt[m.path]?` (${$e.length})`:""}`}):"Sitemap"}),e.jsx("td",{className:"text-secondary",children:ue}),e.jsx("td",{className:"text-secondary",children:m.lastSubmitted?m.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:m.lastDownloaded?m.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:T.toLocaleString()}),e.jsx("td",{className:"max-w-48 text-secondary",children:ae||"—"}),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:!os||Je,onClick:()=>{vs([m.path])},children:m.lastSubmitted?"Resubmit to Google":"Submit to Google"}),at?.sitemapUrl===m.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:Ot,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{Wa(m.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Gn.isPending,onClick:()=>{Ya(m.path)},children:"Inspect URLs"})]})})]},m.path),Xe=m.isSitemapsIndex&&qe?$e.map(Pe=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs pl-6 text-secondary",children:e.jsx(Xs,{value:Pe.path})}),e.jsx("td",{className:"text-secondary",children:"File"}),e.jsx("td",{className:"text-secondary",children:br(Pe)}),e.jsx("td",{className:"text-secondary",children:Pe.lastSubmitted?Pe.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:Pe.lastDownloaded?Pe.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:gr(Pe).toLocaleString()}),e.jsx("td",{className:"text-secondary",children:fr(Pe)||"—"}),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:!os||Je,onClick:()=>{vs([Pe.path])},children:"Resubmit"}),at?.sitemapUrl===Pe.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:Ot,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{Wa(Pe.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Gn.isPending,onClick:()=>{Ya(Pe.path)},children:"Inspect URLs"})]})})]},`${m.path}:${Pe.path}`)):[];return[_e,...Xe]})})]}),e.jsx(fs,{page:nt.page,pageSize:Et,visibleRows:nt.rows.length,totalRows:nt.totalRows,onPageChange:nt.setPage,itemLabel:"sitemaps"})]}):e.jsx("p",{className:"text-sm text-muted",children:"No sitemaps found for this property."})})]}),e.jsxs(me,{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:g,onChange:m=>v(m.target.value),onKeyDown:m=>m.key==="Enter"&&void er()}),e.jsx(k,{type:"button",size:"sm",disabled:et||!at?.propertyId||!g.trim(),onClick:Ie(er),children:et?"Inspecting…":"Inspect URL"})]}),L&&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:L.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:L.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:tr(L.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:_t(L.crawlTime)})]})]})]}),e.jsxs(me,{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(k,{type:"button",variant:"outline",size:"sm",disabled:je,onClick:()=>{hn(!0)},children:je?"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:re,onChange:m=>le(m.target.value)}),e.jsx(k,{type:"button",size:"sm",variant:"outline",disabled:je,onClick:()=>{hn(!0)},children:"Apply filter"})]}),N.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:N.map(m=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:m.url}),e.jsx("td",{className:"text-neutral",children:m.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:m.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:m.coverageState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:tr(m.isMobileFriendly??null)}),e.jsx("td",{className:"text-secondary",children:_t(m.inspectedAt)})]},m.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No inspection history yet."})]}),e.jsxs(me,{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"})]})}),b.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Previous"}),e.jsx("th",{className:"text-left",children:"Current"}),e.jsx("th",{className:"text-left",children:"Changed at"})]})}),e.jsx("tbody",{children:b.map(m=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:m.url}),e.jsx("td",{className:"text-secondary",children:m.previousState??"Unknown"}),e.jsx("td",{className:"text-neutral",children:m.currentState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:_t(m.transitionDate)})]},`${m.url}:${m.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No deindexed transitions recorded."})]})]}),at&&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:()=>Ce(m=>!m),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 ${F?"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"})]})}),F&&e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(me,{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:q,disabled:z||u.length===0,onChange:m=>$(m.target.value),children:u.length===0?e.jsx("option",{value:"",children:z?"Loading properties…":"No properties available"}):u.map(m=>e.jsxs("option",{value:m.siteUrl,children:[m.siteUrl," · ",m.permissionLevel]},m.siteUrl))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(k,{type:"button",size:"sm",variant:"outline",disabled:z,onClick:()=>{Ka(at,!0)},children:z?"Refreshing…":"Refresh properties"}),e.jsx(k,{type:"button",size:"sm",disabled:!q||Oe,onClick:Ie(Zi),children:Oe?"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(me,{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:w,onChange:m=>ee(m.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:W,onChange:m=>A(m.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(k,{type:"button",size:"sm",disabled:Un.isPending||!at.propertyId,onClick:Ie(el),children:Un.isPending?"Queueing…":"Queue sync"}),!at.propertyId&&e.jsx("p",{className:"text-xs text-caution-400",children:"Select a Search Console property before queueing a sync."})]})]})]})})]})]})]})}const tu=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function su({projectName:t,projectId:s}){const n=as(),[a,r]=l.useState(null),[i,o]=l.useState(null),[u,d]=l.useState(!1),h=Le(Ra({client:Q,path:{name:t}})),x=h.data?.find(M=>M.connectionType==="gbp"),c=!!x,y=a?{locationName:a}:void 0,N=Le({...Fl({client:Q,path:{name:t}}),enabled:c}),f=Le({..._l({client:Q,path:{name:t},query:y}),enabled:c}),b=Le({...Ul({client:Q,path:{name:t},query:y}),enabled:c}),p=Le({...Gl({client:Q,path:{name:t},query:y}),enabled:c}),L=Le({...Bl({client:Q,path:{name:t},query:y}),enabled:c}),E=Le({...zl({client:Q,path:{name:t},query:y}),enabled:c}),q=Le({queryKey:["gbp-section-insights",t],queryFn:()=>Vl(t),enabled:c});function $(){it(n,"gbp")}const g=tn({...Ql(),onSuccess:M=>{Kl({id:M.runId,projectId:s,kind:bs["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),Ne({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),v=l.useSyncExternalStore(ei,$n,$n),w=Object.values(v.runs).some(M=>M.kind===bs["gbp-sync"]&&M.projectId===s),ee=g.isPending||w,W=tn({...Hl(),onSuccess:()=>$()});if(l.useEffect(()=>{if(!a||!N.data)return;const M=N.data.locations.filter(z=>z.selected);(M.length<=1||!M.some(z=>z.locationName===a))&&r(null)},[a,N.data]),l.useEffect(()=>{if(!i||!N.data)return;(a?[a]:N.data.locations.filter(z=>z.selected).map(z=>z.locationName)).includes(i)||o(null)},[i,N.data,a]),h.isLoading)return null;if(!x){const M=[{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(me,{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:M.map((z,we)=>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:we+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:z.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:z.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:z.note})]})]},z.title))})]})})}const A=f.data,j=N.data?.locations??[],D=j.filter(M=>M.selected),S=b.data?.keywords??[],V=p.data?.lodging??[],pe=L.data?.placeActions??[],ne=E.data?.places??[],X=j.length>0?j[0].accountName:x.domain,te=a?j.find(M=>M.locationName===a)?.displayName??null:null,ce=a?j.filter(M=>M.locationName===a):D,B=new Set(ce.map(M=>M.locationName)),G=V.filter(M=>B.has(M.locationName)),P=pe.filter(M=>B.has(M.locationName)),re=ne.filter(M=>B.has(M.locationName)),le=new Set(D.map(M=>M.locationName)),C=a?S:S.filter(M=>le.has(M.locationName)),U=!a&&D.length>1,se=(q.data??[]).filter(M=>!M.dismissed&&tu.has(M.type)&&(!te||M.query===te||M.query===a||M.title.startsWith(te)));return e.jsx("section",{className:"page-section-divider",children:e.jsxs(me,{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(Ze,{text:"How AI answer engines and Maps surface this business: performance, search terms, and how your public listing compares to the profile you control."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oe,{tone:"positive",children:"Connected"}),!Z()&&e.jsx(k,{type:"button",variant:"outline",size:"sm",disabled:ee,onClick:()=>g.mutate({client:Q,path:{name:t},body:{}}),children:ee?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-muted",children:[X?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-secondary",children:X})," · "]}):null,N.data?`${N.data.totalSelected} of ${N.data.totalDiscovered} locations tracked`:"Loading locations…"]}),D.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:M=>r(M.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"}),D.map(M=>e.jsx("option",{value:M.locationName,children:M.displayName},M.id))]})]}),D.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:[se.length>0&&e.jsxs("div",{className:"mb-6 grid gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Needs attention"}),se.map(M=>e.jsx("div",{className:["insight-card",pu(M.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:[M.title,M.recommendation?.reason&&e.jsx(Ze,{text:M.recommendation.reason})]})},M.id))]}),A&&e.jsx(ju,{performance:A.performance,freshness:A.freshness,timeseries:A.timeseries}),A?.profileCompleteness&&e.jsx(nu,{summary:A.profileCompleteness}),ce.length>0&&e.jsx(au,{locations:ce,lodging:G,places:re,placeActions:P,expandedLocation:i,onToggleExpanded:M=>{o(z=>z===M?null:M)}}),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"}),b.data&&b.data.total>0&&e.jsxs("span",{className:"text-[11px] text-faint",children:[b.data.thresholdedPct,"% privacy-thresholded"]})]}),C.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"}),U&&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:C.slice(0,25).map(M=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-neutral",children:M.keyword}),U&&e.jsx("td",{className:"text-muted",children:j.find(z=>z.locationName===M.locationName)?.displayName??M.locationName}),e.jsx("td",{className:"text-right font-mono text-strong",children:M.valueCount!==null?M.valueCount.toLocaleString():e.jsxs("span",{className:"text-muted",title:"Privacy floor — Google withheld the exact count",children:["<",M.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-faint",children:[M.periodStart,"–",M.periodEnd]})]},`${M.locationName}:${M.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:()=>d(M=>!M),"aria-expanded":u,children:[e.jsx("span",{"aria-hidden":"true",children:u?"▾":"▸"})," Manage locations (",j.length,")"]}),u&&e.jsx("div",{className:"mt-3",children:j.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"}),!Z()&&e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:j.map(M=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:M.displayName}),e.jsx("td",{className:"text-muted",children:M.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(oe,{tone:M.selected?"positive":"neutral",children:M.selected?"Tracked":"Not tracked"})}),!Z()&&e.jsx("td",{className:"text-right",children:e.jsx(k,{type:"button",variant:"outline",size:"sm",disabled:W.isPending,onClick:()=>W.mutate({client:Q,path:{name:t,locationName:M.locationName},body:{selected:!M.selected}}),children:M.selected?"Untrack":"Track"})})]},M.id))})]})})]})]})})}function nu({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:Ks(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:Ks(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:Ks(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:Ks(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:Ks(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(Ze,{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 ${xu(a.tone)}`,children:a.value}),a.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-faint",children:a.detail})]},a.label))})]})}function au({locations:t,lodging:s,places:n,placeActions:a,expandedLocation:r,onToggleExpanded:i}){const o=new Map(s.map(h=>[h.locationName,h])),u=new Map(n.map(h=>[h.locationName,h])),d=new Map;for(const h of a){const x=d.get(h.locationName)??[];x.push(h),d.set(h.locationName,x)}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(Ze,{text:Z()?"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest sync, not that every Google product lacks the information.":"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest Canonry sync, not that every Google product lacks the information."})]}),e.jsxs("span",{className:"text-[11px] text-faint",children:[t.length," location",t.length===1?"":"s"]})]}),e.jsx("div",{className:"data-table-wrapper",children:e.jsxs("table",{className:"data-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"min-w-[14rem]",children:"Location"}),e.jsx("th",{className:"min-w-[15rem]",children:"Owner profile"}),e.jsx("th",{className:"min-w-[11rem]",children:"Hotel data"}),e.jsx("th",{className:"min-w-[11rem]",children:"Public Maps"}),e.jsx("th",{className:"min-w-[10rem]",children:"CTAs"}),e.jsx("th",{className:"text-right",children:"Detail"})]})}),e.jsx("tbody",{children:t.map(h=>{const x=o.get(h.locationName)??null,c=u.get(h.locationName)??null,y=d.get(h.locationName)??[],N=r===h.locationName;return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-strong",children:h.displayName}),e.jsx("p",{className:"mt-1 text-xs text-faint",children:h.primaryCategoryDisplayName??"Primary category not returned"}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[e.jsx(oe,{tone:h.selected?"positive":"neutral",children:h.selected?"Tracked":"Not tracked"}),h.openStatus&&h.openStatus!=="OPEN"&&e.jsx(oe,{tone:h.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:Ai(h.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(iu,{location:h})}),e.jsx("td",{children:e.jsx(lu,{lodging:x})}),e.jsx("td",{children:e.jsx(cu,{place:c,mapsUri:h.mapsUri})}),e.jsx("td",{children:e.jsx(uu,{actions:y})}),e.jsx("td",{className:"text-right",children:e.jsx(k,{type:"button",variant:"outline",size:"sm",onClick:()=>i(h.locationName),children:N?"Hide":"Details"})})]}),N&&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(hu,{location:h,lodging:x,place:c,placeActions:y})})})]},h.id)})})]})})]})}function ru(t){return[{label:"Description",tone:hs(t.description)?"positive":"neutral",value:hs(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:hs(t.primaryPhone)?"positive":"neutral",value:hs(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:hs(t.websiteUri)?"positive":"neutral",value:hs(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 iu({location:t}){const s=ru(t);return e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>e.jsxs(oe,{tone:n.tone,children:[n.label," ",n.value]},n.label))})}function lu({lodging:t}){return e.jsx(Da,{...ou(t)})}function ou(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 cu({place:t,mapsUri:s}){return e.jsx(Da,{...du(t,s)})}function du(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 uu({actions:t}){return e.jsx(Da,{...mu(t)})}function mu(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 Da({tone:t,label:s,detail:n}){return e.jsxs("div",{children:[e.jsx(oe,{tone:t,children:s}),e.jsx("p",{className:"mt-1.5 text-xs leading-5 text-faint",children:n})]})}function hu({location:t,lodging:s,place:n,placeActions:a}){const r=s?fu(s.attributes):[];return e.jsxs("div",{className:"grid gap-5 text-xs lg:grid-cols-3",children:[e.jsxs(Jn,{title:"Owner profile · Business Information",children:[e.jsx(ht,{label:"Primary category",value:t.primaryCategoryDisplayName??"Not returned"}),e.jsx(ht,{label:"Secondary categories",value:t.additionalCategories.length>0?t.additionalCategories.join(", "):"Not returned"}),e.jsx(ht,{label:"Description",value:hs(t.description)?t.description:"Not returned"}),e.jsx(ht,{label:"Hours",value:t.regularHours?"Returned by Google":"Not returned"}),e.jsx(ht,{label:"Service area",value:t.serviceArea?"Returned by Google":"Not returned"}),e.jsx(ht,{label:"Phone",value:t.primaryPhone??"Not returned"}),e.jsx(ht,{label:"Website",value:t.websiteUri??"Not returned"}),e.jsx(ht,{label:"Open status",value:Ai(t.openStatus)}),e.jsx(ht,{label:"Opening date",value:t.openingDate??"Not returned"})]}),e.jsx(Jn,{title:"Hotel data · Lodging API",children:s?e.jsxs(e.Fragment,{children:[e.jsx(ht,{label:"Last checked",value:jr(s.syncedAt)}),e.jsx(ht,{label:"Groups returned",value:String(s.populatedGroupCount)}),e.jsx(ht,{label:"Populated groups",value:r.length>0?r.join(", "):"None returned"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Lodging API snapshot was stored for this location."})}),e.jsxs(Jn,{title:"Public listing + CTAs",children:[n?e.jsxs(e.Fragment,{children:[e.jsx(ht,{label:"Places tier",value:n.tier}),e.jsx(ht,{label:"Last checked",value:jr(n.syncedAt)}),e.jsx(ht,{label:"Public signals",value:n.amenities.length>0?n.amenities.join(", "):"No supported signals detected"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Places Details snapshot was stored for this location."}),t.mapsUri&&e.jsx("a",{href:t.mapsUri,target:"_blank",rel:"noopener noreferrer",className:"inline-block text-muted hover:text-neutral",children:"View on Google Maps →"}),e.jsx("div",{className:"mt-3 border-t border-default pt-3",children:a.length===0?e.jsx("p",{className:"leading-5 text-muted",children:"No placeActionLinks returned."}):e.jsx("div",{className:"grid gap-2",children:a.map(i=>e.jsxs("div",{className:"grid gap-0.5",children:[e.jsxs("span",{className:"font-medium text-neutral",children:[Mn(i.placeActionType),i.isPreferred?" · preferred":""]}),e.jsxs("span",{className:"text-faint",children:[Mn(i.providerType),i.uri?` · ${gu(i.uri)}`:""]})]},i.placeActionLinkName))})})]})]})}function Jn({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 ht({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 Ks(t,s,n){return t===s?"positive":t===0?n:"caution"}function xu(t){switch(t){case"positive":return"text-positive";case"caution":return"text-caution";case"negative":return"text-negative";case"neutral":return"text-neutral"}}function pu(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function hs(t){return typeof t=="string"&&t.trim().length>0}function Ai(t){return t?Mn(t):"Not returned"}function Mn(t){return t?t.toLowerCase().split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"Unknown"}function gu(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function jr(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function fu(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&bu(n)).map(([s])=>Mn(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function bu(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function ju({performance:t,freshness:s,timeseries:n}){const a=t.totals,r=Wl.filter(f=>(a[f]??0)>0),i=Yl.filter(f=>(a[f]??0)>0),o=Object.keys(a).filter(f=>(a[f]??0)>0&&Jl(f)==="other").sort((f,b)=>(a[b]??0)-(a[f]??0)),u=Object.keys(a).filter(f=>(a[f]??0)===0).sort(),d=n.map(f=>{const b={date:f.date};for(const[p,L]of Object.entries(f.metrics))b[p]=L;return b}),h=n.find(f=>f.pending)?.date,x=n.length>0?n[n.length-1].date:void 0,c=d.length>0,y=s.dataThroughDate?`Data through ${Ln(s.dataThroughDate)}${s.pendingDays>0?` · ${s.pendingDays}d pending`:""}`:null,N=[...r,...o];return e.jsxs("div",{className:"mb-6 grid gap-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Profile actions · daily"}),y&&e.jsx("span",{className:"text-[11px] text-muted",children:y})]}),!c||r.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No profile action activity yet — run a sync."}):e.jsxs(e.Fragment,{children:[e.jsx(yr,{data:d,metrics:r,kind:"line",firstPending:h,lastDate:x}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-x-5 gap-y-1",children:N.map(f=>e.jsxs("span",{className:"text-sm text-secondary",children:[In(f)," ",e.jsx("span",{className:"font-mono text-heading",children:(a[f]??0).toLocaleString()})]},f))})]})]}),c&&i.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(yr,{data:d,metrics:i,kind:"area",firstPending:h,lastDate:x})]}),u.length>0&&e.jsxs("p",{className:"text-xs text-faint",children:["Not active: ",u.map(f=>In(f)).join(", ")]})]})}function yr({data:t,metrics:s,kind:n,firstPending:a,lastDate:r}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(Ts,{width:"100%",height:"100%",children:e.jsxs(Ds,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Ma,{stroke:Ia,vertical:!1}),e.jsx(Es,{dataKey:"date",tick:Lt,tickLine:!1,axisLine:{stroke:Ht},tickFormatter:fa,minTickGap:24}),e.jsx(qs,{tick:Lt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Os,{...gs,labelFormatter:Ln,formatter:(i,o)=>[typeof i=="number"?i.toLocaleString():String(i??0),In(String(o??""))]}),e.jsx(mi,{wrapperStyle:{fontSize:11,color:gt.text},formatter:i=>In(i)}),a&&r&&e.jsx(ed,{x1:a,x2:r,fill:gt.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:gt.textDim,fontSize:10}}),s.map((i,o)=>n==="line"?e.jsx(Ta,{type:"monotone",dataKey:i,stroke:pt[o%pt.length],strokeWidth:2,dot:!1,isAnimationActive:!1},i):e.jsx(ks,{type:"monotone",dataKey:i,stackId:"reach",stroke:pt[o%pt.length],fill:pt[o%pt.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},i))]})})})}function yu(t){return La(Gt(String(t)))}function vu(t){return ns(Gt(String(t)))}function Xn({children:t,label:s="More info",placement:n="top",className:a}){const r=l.useId(),[i,o]=l.useState(!1);return e.jsxs("span",{className:`relative inline-flex ${a??""}`,children:[e.jsx("button",{type:"button","aria-label":s,"aria-describedby":i?r:void 0,className:"inline-flex h-4 w-4 items-center justify-center rounded-full text-muted hover:text-strong focus:text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),onFocus:()=>o(!0),onBlur:()=>o(!1),children:e.jsx(sd,{className:"h-3.5 w-3.5","aria-hidden":!0})}),i&&e.jsx("span",{id:r,role:"tooltip",className:`absolute z-50 w-64 rounded border border-strong bg-bg-elevated px-3 py-2 text-xs font-normal leading-relaxed text-strong shadow-lg ${n==="top"?"bottom-full mb-2":"top-full mt-2"} left-1/2 -translate-x-1/2 whitespace-normal`,children:t})]})}const vn=Et;function ws(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function Zn(t){return t.toLocaleString()}function Nu(t){const s=Number(t);return Number.isFinite(s)?`${(s*100).toFixed(1)}%`:"—"}function wu(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 Su(t){const s=t.filter(n=>n.kind===bs["backlink-extract"]&&!ti(n.status));return s.length===0?null:s.reduce((n,a)=>n.createdAt>a.createdAt?n:a)}function Cu(t,s){const n=new Date(t??s).getTime(),a=Math.max(0,Math.floor((Date.now()-n)/1e3));if(a<60)return`${a}s`;const r=Math.floor(a/60),i=a%60;return i===0?`${r}m`:`${r}m ${i}s`}function ku({projectName:t}){const[s,n]=l.useState(null),[a,r]=l.useState(null),[i,o]=l.useState([]),[u,d]=l.useState(null),[h,x]=l.useState(null),[c,y]=l.useState(null),[N,f]=l.useState(Date.now()),[b,p]=l.useState(0),[L,E]=l.useState(!0),[q,$]=l.useState(!1),[g,v]=l.useState(null),w=l.useCallback(async()=>{E(!0),v(null);try{const[X,te,ce,B,G]=await Promise.all([Xl().catch(()=>null),Zl(t,{excludeCrawlers:!0}).catch(()=>null),eo(t,{limit:vn,offset:b,excludeCrawlers:!0}).catch(re=>{if(re instanceof Ls&&re.code==="NOT_FOUND")return null;throw re}),to(t).catch(()=>[]),so(t).catch(()=>[])]);d(X),n(te),r(ce),o(B);const P=Su(G);x(P)}catch(X){v(X instanceof Error?X.message:"Failed to load backlinks")}finally{E(!1)}},[t,b]);l.useEffect(()=>{w()},[w]),l.useEffect(()=>{if(!h)return;const X=h.id;let te=!1;const ce=async()=>{try{const G=await si(X);if(te)return;ti(G.status)?(x(null),y(G),await w()):x(P=>P?.id===G.id?{...P,...G}:P)}catch{}},B=window.setInterval(()=>{ce()},3e3);return()=>{te=!0,window.clearInterval(B)}},[h,w]),l.useEffect(()=>{if(!h)return;const X=window.setInterval(()=>f(Date.now()),1e3);return()=>window.clearInterval(X)},[h]),l.useEffect(()=>{if(!c||c.status==="failed")return;const X=window.setTimeout(()=>y(null),1e4);return()=>window.clearTimeout(X)},[c]);async function ee(){$(!0),v(null);try{const X=await ro(t);x(X)}catch(X){X instanceof Ls&&X.code==="MISSING_DEPENDENCY"?v("DuckDB is not installed. Visit the Backlinks admin page to install it."):v(X instanceof Error?X.message:"Failed to trigger extract")}finally{$(!1)}}const W=l.useMemo(()=>i.slice().sort((X,te)=>X.queriedAt.localeCompare(te.queriedAt)).map(X=>({date:X.queriedAt,linkingDomains:X.totalLinkingDomains})),[i]),A=a?.rows??[],j=a?.total??0,D=s?.excludedLinkingDomains??0,S=Math.floor(b/vn)+1;return l.useEffect(()=>{b>0&&b>=j&&p(0)},[b,j]),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"})]})}),g&&e.jsx(me,{className:"surface-card p-4 mb-4 border-negative-800/60",children:e.jsx("p",{className:"text-sm text-negative",children:g})}),h&&e.jsx(me,{className:"surface-card p-4 mb-4 border-info-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ga,{className:"h-5 w-5 text-info-400 animate-spin shrink-0 mt-0.5","aria-hidden":!0}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"Extract running"}),e.jsx(oe,{tone:"neutral",children:h.status}),e.jsxs("span",{className:"text-sm text-secondary tabular-nums",children:[Cu(h.startedAt??null,h.createdAt)," elapsed · refreshing every 3s"]}),e.jsxs("span",{className:"sr-only",children:["now=",N]})]}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Refreshing this project from the current Common Crawl release."})]})]})}),c&&!h&&e.jsx(me,{className:`surface-card p-4 mb-4 ${c.status==="failed"?"border-negative-800/60":"border-positive-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[c.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(xi,{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 ${c.status==="failed"?"text-negative":"text-positive"}`,children:c.status==="failed"?"Extract failed":"Extract complete"}),c.error?e.jsx("p",{className:"text-sm text-secondary mt-1",children:no(c.error)}):c.status!=="failed"?e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),V()]});function V(){return L?e.jsx(me,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading backlinks…"})}):pe()}function pe(){const X=s!==null&&s.totalLinkingDomains>0,te=c?.status==="failed",ce=s!==null&&s.totalLinkingDomains===0&&!te,B=u?.status==="ready",G=u?.status==="failed",P=u&&(u.status==="downloading"||u.status==="querying"||u.status==="queued");return X?ne(e.jsxs(e.Fragment,{children:[!Z()&&e.jsxs(e.Fragment,{children:[e.jsxs(k,{type:"button",variant:"outline",size:"sm",disabled:q||h!==null,onClick:Ie(ee),children:[e.jsx(hi,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":q?"Queuing…":"Re-run extract"]}),e.jsx(Xn,{label:"About re-running",children:"Re-queries the current release for this project without downloading it again."})]}),!Z()&&e.jsx(k,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:ws("/backlinks"),children:"Open admin"})})]})):e.jsx(me,{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(ao,{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."}),!Z()&&e.jsx("div",{className:"mt-4",children:e.jsx(k,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:ws("/backlinks"),children:"Set up backlinks"})})})]}),P&&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."]}),!Z()&&e.jsx("div",{className:"mt-4",children:e.jsx(k,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:ws("/backlinks"),children:"View sync status"})})})]}),G&&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."}),!Z()&&e.jsx("div",{className:"mt-4",children:e.jsx(k,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:ws("/backlinks"),children:"Go to Backlinks admin"})})})]}),B&&!P&&!ce&&!te&&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."]}),!Z()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(k,{type:"button",size:"sm",disabled:q||h!==null,onClick:Ie(ee),children:[e.jsx(Ms,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":q?"Queuing…":"Run extract"]}),e.jsx(Xn,{label:"About extraction",children:"Queries the current release for this project without downloading it again."})]})]}),te&&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."}),!Z()&&e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(k,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:ws("/backlinks"),children:"Go to Backlinks admin"})})})]}),ce&&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."]}),!Z()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(k,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:ws("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(k,{type:"button",variant:"outline",size:"sm",disabled:q||h!==null,onClick:Ie(ee),children:[e.jsx(Ms,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":q?"Queuing…":"Re-run extract"]}),e.jsxs(Xn,{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 ne(X){if(!s)return null;const te="Linking hosts",ce="linking hosts",B="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:Zn(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 ",ce]}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:Zn(s.totalHosts)})}),e.jsxs("p",{className:"metric-card-sub",children:["aggregate ",ce," 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:Nu(s.top10HostsShare)})}),e.jsxs("p",{className:"metric-card-sub",children:["share of ",ce," 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"})," · ",B," ",e.jsx("code",{className:"text-secondary",children:s.release})," · queried ",wu(s.queriedAt),D>0&&e.jsxs(e.Fragment,{children:[" · ",D," excluded domain",D===1?"":"s"]})]}),W.length>=2&&e.jsxs(me,{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(Ts,{width:"100%",height:"100%",children:e.jsxs(Ds,{data:W,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:pt[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:pt[0],stopOpacity:0})]})}),e.jsx(Es,{dataKey:"date",tick:Lt,stroke:Ht,tickFormatter:yu}),e.jsx(qs,{tick:Lt,stroke:Ht,allowDecimals:!1}),e.jsx(Os,{contentStyle:gs.contentStyle,labelStyle:gs.labelStyle,itemStyle:gs.itemStyle,labelFormatter:vu}),e.jsx(ks,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:pt[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(me,{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:te})]})}),e.jsxs("tbody",{children:[A.map(G=>e.jsxs("tr",{className:"border-b border-mono-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-strong",children:G.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-secondary tabular-nums",children:Zn(G.numHosts)})]},G.linkingDomain)),A.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-muted",colSpan:2,children:D>0&&j===0?`Every referring domain in this ${B} was a crawler/proxy host (${D} hidden).`:`No referring domains in this ${B}.`})})]})]})}),e.jsx(fs,{page:S,pageSize:vn,visibleRows:A.length,totalRows:j,onPageChange:G=>p((G-1)*vn)})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:X})]})}}function Pu({projectName:t}){const s=Le({...io({client:Q,path:{name:t}}),staleTime:ni}),n=s.data??null,a=s.error;if(s.isLoading&&!n)return null;if(a)return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsx("h2",{children:"Citation + answer-mention coverage"})]})}),e.jsx("p",{className:"text-sm text-negative-400",children:a instanceof Error?a.message:String(a)})]});if(!n)return null;if(n.status==="no-data")return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsx("h2",{children:"Citation + answer-mention coverage"})]})}),e.jsx("p",{className:"text-sm text-muted",children:n.reason==="no-queries"?"Add queries to start tracking AI citations.":"Run a sweep to see which engines cite this project."})]});const{providersCiting:r,providersMentioning:i,providersConfigured:o}=n.summary;return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsxs("h2",{className:"flex items-center gap-2",children:["Cited by ",r," of ",o," engines",e.jsx(Ze,{text:"An engine is ‘citing’ when our domain appears in its grounding source list (the structured citation/search-result attribution it returns alongside the answer). Counts each configured engine that cites the project on at least one tracked query in the latest snapshot per (query × provider)."})]}),e.jsxs("p",{className:"text-base text-neutral flex items-center gap-2",children:["Mentioned in ",i," of ",o," engine answers",e.jsx(Ze,{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(Au,{data:n}),e.jsx(Ru,{data:n}),n.competitorGaps.length>0&&e.jsx(Mu,{data:n})]})}function Au({data:t}){const{totalQueries:s,queriesCitedAndMentioned:n,queriesCitedOnly:a,queriesMentionedOnly:r,queriesInvisible:i}=t.summary;return e.jsxs("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4 mb-4",children:[e.jsx(Nn,{label:"Cited + mentioned",value:`${n} / ${s}`,helper:"In sources AND named in answer",tone:n>0?"positive":"neutral"}),e.jsx(Nn,{label:"Cited only",value:`${a} / ${s}`,helper:"In sources, not named in answer",tone:a>0?"positive-dim":"neutral"}),e.jsx(Nn,{label:"Mentioned only",value:`${r} / ${s}`,helper:"Named in answer, no source link",tone:r>0?"caution":"neutral"}),e.jsx(Nn,{label:"Invisible",value:`${i} / ${s}`,helper:"No engine cites or mentions",tone:i>0?"negative":"neutral"})]})}function Nn({label:t,value:s,helper:n,tone:a}){const r=a==="positive"?"text-positive":a==="positive-dim"?"text-positive-400/70":a==="caution"?"text-caution":a==="negative"?"text-negative":"text-heading";return e.jsxs("div",{className:"rounded-md border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:t}),e.jsx("p",{className:`mt-1 text-2xl font-semibold tabular-nums ${r}`,children:s}),e.jsx("p",{className:"text-[11px] text-muted",children:n})]})}function Ru({data:t}){const s=l.useMemo(()=>{const n=new Set;for(const a of t.byQuery)for(const r of a.providers)n.add(r.provider);return Array.from(n).sort()},[t.byQuery]);return t.byQuery.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No query coverage rows."}):e.jsxs("div",{children:[e.jsx($u,{}),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(Is,{provider:n})},n)),e.jsx("th",{className:"text-right",children:"Cite"}),e.jsx("th",{className:"text-right",children:"Ment"})]})}),e.jsx("tbody",{children:t.byQuery.map(n=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:n.query}),s.map(a=>{const r=n.providers.find(i=>i.provider===a);return e.jsx("td",{className:"text-center",children:r==null?e.jsx(dd,{className:"inline h-3.5 w-3.5 text-mono-700","aria-label":"no data"}):e.jsx(Iu,{provider:r})},a)}),e.jsx("td",{className:"text-right tabular-nums",children:e.jsxs("span",{className:n.totalProviders>0&&n.citedCount===n.totalProviders?"text-positive":n.citedCount>0?"text-positive-400/70":"text-muted",children:[n.citedCount,"/",n.totalProviders]})}),e.jsx("td",{className:"text-right tabular-nums",children:e.jsxs("span",{className:n.totalProviders>0&&n.mentionedCount===n.totalProviders?"text-info-300":n.mentionedCount>0?"text-info-400/70":"text-muted",children:[n.mentionedCount,"/",n.totalProviders]})})]},n.queryId))})]})})]})}function $u(){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(Ps,{active:!0,tone:"cited"}),e.jsx("span",{children:"cited (in sources)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ps,{active:!0,tone:"mentioned"}),e.jsx("span",{children:"mentioned (in answer)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ps,{active:!1,tone:"cited"}),e.jsx(Ps,{active:!1,tone:"mentioned"}),e.jsx("span",{children:"neither"})]})]})}function Iu({provider:t}){const s=Lu(t);return e.jsxs("span",{className:"inline-flex items-center justify-center gap-1",title:s,children:[e.jsx(Ps,{active:t.cited,tone:"cited"}),e.jsx(Ps,{active:t.mentioned,tone:"mentioned"})]})}function Lu(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 Ps({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 Mu({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(Ze,{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(Is,{provider:s.provider})}),e.jsx("td",{className:"text-neutral",children:s.citingCompetitors.join(", ")})]},`${s.queryId}::${s.provider}`))})]})})]})}const on="__cited__",cn="__mentioned__",It="__mentionShare__";function Ri(t){const s=t,{dataStartDate:n,dataEndDate:a}=s;return typeof n!="string"||typeof a!="string"?null:{start:Gt(n),end:Gt(a),sweepCount:s.sweepCount??1}}function Tn(t){const s=Ri(t);if(!s)return"Sweep date unavailable";const n=ns(s.start),a=ns(s.end);return n===a?n:`${n} – ${a} · ${s.sweepCount} sweeps combined`}function Tu(t){const s=Ri(t);return s?La(s.start):""}function _s(t){return t.trim().toLowerCase()}function va(t){return Math.round(t*1e3)/10}function Na(t){return t.byProvider??{}}function Du(t,s,n){const a=t.buckets.length>0,r=t.buckets.length===1;if(n==="overall"){const d=s==="cited"?on:cn,h=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(c=>({date:c.startDate,[d]:va(c[h])})),series:[d],hasData:a,singleBucket:r}}const i=s==="mentioned"?"mentionRate":"citationRate",o=[...new Set(t.buckets.flatMap(d=>Object.keys(Na(d))))].sort();return{rows:t.buckets.map(d=>{const h={date:d.startDate},x=Na(d);for(const c of o){const y=x[c];h[c]=y?va(y[i]):null}return h}),series:o,hasData:a,singleBucket:r}}function $i(t){const s=t;return Object.hasOwn(s,"modelEvidenceByProvider")?s.modelEvidenceByProvider??{}:null}function Eu(t){const s=t;return Object.hasOwn(s,"modelAttribution")?s.modelAttribution??{}:null}function qu(t){return t.servedModelAttribution??{}}function Ou(t){return t.modelServiceMismatch??{}}function Fu(t){return t.modelPointerChanges??{}}function _u(t){return t.length>0?t.join(", "):null}function vr(t,s){const n=_s(s);return Object.entries(t).find(([a])=>_s(a)===n)?.[1]}function zt(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 Uu(t,s){for(let n=t.length-1;n>=0;n-=1){const a=t[n];if(!vr(Na(a),s))continue;const r=$i(a);return r?vr(r,s)??null:null}return null}function Gu(t){const s=new Map;for(const[n,a]of Object.entries(t))for(const r of a.events){const i=s.get(r.bucketStartDate)??[];i.push({provider:n,event:r}),s.set(r.bucketStartDate,i)}return[...s.entries()].sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>({bucketStartDate:n,events:[...a].sort((r,i)=>r.provider.localeCompare(i.provider)||r.event.observedAt.localeCompare(i.event.observedAt))}))}function Bu(t){const s={},n=[];for(const[a,r]of Object.entries(t)){const i=r.events.filter(o=>!o.fromPreWindowAnchor);for(const o of r.events)o.fromPreWindowAnchor&&n.push({provider:a,event:o});i.length>0&&(s[a]={...r,events:i})}return{buckets:Gu(s),beforeWindow:n.sort((a,r)=>a.event.observedAt.localeCompare(r.event.observedAt)||a.provider.localeCompare(r.provider))}}function zu(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 Vu(t){const s=[];for(const[n,a]of Object.entries(t)){const r=a.eventTotal??a.events.length;r>a.events.length&&s.push({provider:n,shown:a.events.length,total:r})}return s.sort((n,a)=>n.provider.localeCompare(a.provider))}function Ku(t){const s=t.buckets.map(a=>{const r=a.mentionShare;return{date:a.startDate,[It]:r?.rate==null?null:va(r.rate)}}),n=s.map(a=>a[It]).filter(a=>typeof a=="number"&&Number.isFinite(a));return{rows:s,series:[It],hasData:n.length>0,singleBucket:n.length===1}}function Qu(t,s,n){return s==="mentionShare"?Ku(t):Du(t,s,n)}function Nr(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 wr(t){const[,s,n]=t.slice(0,10).split("-");return!s||!n?t:`${s}/${n}`}function Sr(t){return t>0?`+${t}`:`${t}`}function Hu(t){if(t.length===0)return null;if(t.length<=2)return`Query set changed: ${t.map(n=>`${Sr(n.delta)} on ${wr(n.date)}`).join(", ")}`;const s=[...t].sort((n,a)=>a.date.localeCompare(n.date))[0];return`Query set changed ${t.length} times (latest ${Sr(s.delta)} on ${wr(s.date)})`}const Wu=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],Yu=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],Ju=[{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."}],Ea=pt[2],Xu="var(--chart-tooltip-bg)",Zu={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",local:"Local"};function Kt(t){const s=_s(t);return Zu[s]??t.charAt(0).toUpperCase()+t.slice(1)}function ts(t){return Math.round(t*10)/10}function em(t){return t===on||t===cn||t===It}function Ii(t){return t===on?"Cited":t===cn?"Mentioned":t===It?"Mention share":Kt(t)}function Ws(t,s){return t===on?Qt.positive:t===cn?pt[1]:t===It?Ea:Yc(_s(t),s)}function tm(t,s){for(const n of t){const a=n[s];if(typeof a=="number"&&Number.isFinite(a))return a}return null}function sm(t){return t.map(s=>s.trim().toLowerCase()).filter(Boolean).sort().join(`