@canonry/canonry 4.169.0 → 4.170.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/assets/{AuditHistoryPanel-B3APGWB4.js → AuditHistoryPanel-BpIn6E7p.js} +1 -1
  2. package/assets/assets/{BacklinksPage-C-7KAx5g.js → BacklinksPage-BvOWgx1l.js} +1 -1
  3. package/assets/assets/{HistoryPage-Cf-dJuPA.js → HistoryPage-BXaQyur8.js} +1 -1
  4. package/assets/assets/{MeasurementPropertyPage-C1W-BG81.js → MeasurementPropertyPage-Buj708lc.js} +1 -1
  5. package/assets/assets/{ProjectPage-CnZC8AA7.js → ProjectPage-BwC29w2_.js} +1 -1
  6. package/assets/assets/{RunRow-DJQ4Up9f.js → RunRow-C9hp5yEp.js} +1 -1
  7. package/assets/assets/{RunsPage-BbtbYLgP.js → RunsPage-DmkRH1iu.js} +1 -1
  8. package/assets/assets/{SettingsPage-DG-6IuO1.js → SettingsPage-BIyuj-gL.js} +1 -1
  9. package/assets/assets/{SiteHealthSection-rCrAk98W.js → SiteHealthSection-ZlYR3JtG.js} +3 -3
  10. package/assets/assets/{TrafficPage-CpS4K8eT.js → TrafficPage-PxIetTWH.js} +1 -1
  11. package/assets/assets/{TrafficSourceDetailPage-D_zPmdUz.js → TrafficSourceDetailPage-BhF_leby.js} +1 -1
  12. package/assets/assets/{extract-error-message-40mUXcbq.js → extract-error-message-Dd2su-BK.js} +1 -1
  13. package/assets/assets/{index-Nk2MzD2d.js → index-DyjfMyum.js} +21 -21
  14. package/assets/assets/{react-sigma_core.esm.min-BOZ1RPZp.js → react-sigma_core.esm.min-CsNemdas.js} +1 -1
  15. package/assets/index.html +1 -1
  16. package/dist/{chunk-HVBAGSQC.js → chunk-BMW3AURU.js} +567 -5
  17. package/dist/{chunk-U2X42SKN.js → chunk-CCZNCH7Y.js} +3641 -1154
  18. package/dist/{chunk-K7XXDKYY.js → chunk-HJ7W2LXI.js} +165 -1
  19. package/dist/{chunk-ANA3GJSC.js → chunk-HTUI6BSK.js} +2 -2
  20. package/dist/{chunk-T2UJAYTX.js → chunk-NMCLLN5X.js} +3376 -137
  21. package/dist/cli.js +5 -5
  22. package/dist/index.d.ts +132 -2
  23. package/dist/index.js +10 -4
  24. package/dist/{intelligence-service-6ZYTEFXX.js → intelligence-service-64IPZ4NU.js} +2 -2
  25. package/dist/mcp.js +3 -3
  26. package/package.json +10 -10
@@ -1,4 +1,4 @@
1
- import{j as e,r as l,L as _t,n as rs,u as _e,o as Zs,B as zr,C as tl,h as sl,k as nl,D as al}from"./vendor-tanstack-Dock0eH1.js";import{T as ue,t as rl,a as il,u as Qr,C as ll,P as Is,B as A,h as ol,b as cl,c as dl,d as he,i as Y,e as at,f as Ie,I as ze,g as Us,j as ul,k as V,l as ml,m as hl,n as xl,o as pl,p as Hr,q as gl,r as fl,S as hs,s as bl,v as yl,w as us,x as Ot,y as jl,z as Qa,A as Wr,G as ut,D as Na,E as vl,F as Nl,H as wl,J as Sl,K as Ha,L as we,M as Yr,N as Cl,O as Bn,Q as kl,R as Pl,U as Al,V as Rl,W as $l,X as Il,Y as Ll,Z as Tl,_ as Ml,$ as Dl,a0 as El,a1 as ql,a2 as Ol,a3 as Fl,a4 as _l,a5 as Ul,a6 as en,a7 as Gl,a8 as Bl,a9 as Wa,aa as Kl,ab as et,ac as Vl,ad as zl,ae as Ql,af as An,ag as Hl,ah as Wl,ai as Yl,aj as Ls,ak as Xl,al as Jl,am as Zl,an as Xr,ao as ua,ap as eo,aq as Jr,ar as to,as as wa,at as so,au as no,av as ao,aw as Zr,ax as ro,ay as io,az as lo,aA as Ws,aB as xs,aC as oo,aD as co,aE as uo,aF as mo,aG as ei,aH as ho,aI as xo,aJ as po,aK as go,aL as fo,aM as Qe,aN as bo,aO as yo,aP as jo,aQ as vo,aR as No,aS as wo,aT as So,aU as Co,aV as ko,aW as Po,aX as Ao,aY as Ro,aZ as $o,a_ as Io,a$ as Lo,b0 as To,b1 as Mo,b2 as Do,b3 as Eo,b4 as qo,b5 as Oo,b6 as Fo,b7 as _o,b8 as Uo,b9 as Go,ba as Bo,bb as Ko,bc as Vo,bd as zo,be as Qo,bf as Ho,bg as Wo,bh as Yo,bi as Xo,bj as Jo,bk as Zo,bl as ec,bm as tc,bn as Kn,bo as sc,bp as nc,bq as Ya,br as ac,bs as rc,bt as ic,bu as lc,bv as oc,bw as cc,bx as dc,by as uc,bz as mc,bA as hc,bB as xc,bC as pc,bD as gc,bE as ti,bF as fc,bG as bc,bH as yc,bI as jc,bJ as vc,bK as Nc,bL as wc,bM as Xa,bN as Sc,bO as Vn,bP as Cc,bQ as kc,bR as Pc,bS as Ac,bT as Rc,bU as $c,bV as Ic,bW as Lc,bX as si,bY as ni,bZ as Tc,b_ as Mc,b$ as Dc,c0 as Ec,c1 as qc,c2 as pn,c3 as Oc,c4 as Fc,c5 as _c,c6 as Ja,c7 as Uc}from"./index-Nk2MzD2d.js";import{R as Gc}from"./RunRow-DJQ4Up9f.js";import{u as Rn,D as Ys,a as Ps,b as Bc,M as Cn,c as Bt,S as Kc}from"./SiteHealthSection-rCrAk98W.js";import{e as Vc,q as $n,U as zc,r as Qc,L as Hc,s as ai,i as Wc,P as In,D as ri,t as Yc,u as Xc,E as Jc,C as Ln,v as Zc}from"./vendor-lucide-nYKv-BB7.js";import{f as Tn,C as bs,a as Ft,b as ps,c as As,d as It,e as mt,g as gs,M as ed,h as ii,i as li,o as as,j as fs,p as td}from"./ChartPrimitives-BoYe2M-i.js";import{u as sd,t as nd,e as ad,a as Za}from"./extract-error-message-40mUXcbq.js";import{R as tn,C as sn,X as nn,Y as an,T as rn,L as oi,A as Cs,a as ci,b as rd,d as di,e as id}from"./vendor-recharts-D8rt5lKn.js";import{A as ld}from"./AuditHistoryPanel-B3APGWB4.js";import{a as od,b as cd}from"./v2-overview-adapter-COMP5UGt.js";import"./vendor-radix-4UOaVWza.js";import"./vendor-markdown-Bn7fRwrx.js";import"./vendor-yaml-GWJz5H2G.js";function kn(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 dd(t,s,n=800){const a=[];if(!/^\d{4}-\d{2}-\d{2}$/.test(t)||!/^\d{4}-\d{2}-\d{2}$/.test(s))return a;for(let r=t;r<=s&&(a.push(r),!(a.length>=n));r=ud(r,1));return a}function ud(t,s){if(!Number.isFinite(s))return t;const n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t);if(!n?.[1]||!n[2]||!n[3])return t;const a=new Date(Date.UTC(Number(n[1]),Number(n[2])-1,Number(n[3])+Math.trunc(s)));if(Number.isNaN(a.getTime()))return t;const r=a.getUTCFullYear(),i=String(a.getUTCMonth()+1).padStart(2,"0"),o=String(a.getUTCDate()).padStart(2,"0");return`${r}-${i}-${o}`}function ui(t,s){if(!Number.isFinite(t)||!Number.isFinite(s)||s<=0)return null;const n=(t-s)/s;return Number.isFinite(n)?n:null}function md(t,s){const n=ui(t,s);return n===null?null:Math.round(n*100)}function zn(t,s,n="vs prior 7 days"){return t.deltaPct===null?t.prior===0?"First baseline week":"":t.deltaPct>0?`Up ${t.deltaPct}% ${n} (${kn(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${kn(t.prior)} ${s})`:`Flat ${n} (${kn(t.prior)} ${s})`}const mi=30;function er(t){return Math.round(t*10)/10}function hd(t){return t.prior>=mi&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% vs prior`:`${t.deltaAbs>0?"+":""}${er(t.deltaAbs)} vs ${er(t.prior)}`}function xd(t,s,n){return t.prior>=mi&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% ${n}`:`${t.deltaAbs>0?"+":""}${kn(Math.round(t.deltaAbs))} ${s} ${n}`}const pd=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function hi(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function xi(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 pi(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(hi).map(xi).filter(Boolean)):new Set}function gi(t,s){const n=hi(t).map(xi).filter(Boolean).filter(a=>!pd.has(a)).filter(a=>!s.has(a));return[...new Set(n)].sort().join(" ")}function gd(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function fd(t,s){const n=pi(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=gi(gd(i),n);!o||a.has(o)||(a.add(o),r.push(i))}return r}function bd(t){const s=pi(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const a=new Set;return n.filter(r=>{const i=gi(r.query,s);return!i||a.has(i)?!1:(a.add(i),!0)})}const fi={queryClass:"all"},yd=["all","non-brand","branded"];function jd(t){return typeof t=="string"&&yd.includes(t)}function vd(t){const s=jd(t.class)?t.class:fi.queryClass,n=t.scope;if(typeof n!="string"||n==="all"||n.length===0)return{scope:"all",queryClass:s};const a=n.startsWith("group:")?n.slice(6):"";return a?{scope:"group",groupKey:a,queryClass:s}:{scope:"all",queryClass:s}}function Nd(t,s){return s===null||t===null?!1:t!==s}function wd(t){return{scope:t.scope==="group"&&t.groupKey?`group:${t.groupKey}`:void 0,class:t.queryClass===fi.queryClass?void 0:t.queryClass}}function ma({state:t,label:s}){return e.jsx(ue,{tone:il(t),children:s??rl(t)})}function tr({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"}),m=new Date(n[i].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),u=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. ${u}`,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:[m," ",e.jsx("span",{className:"text-faint",children:"latest"})]})]})}function ha(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 Sd=320;function Cd(t){return[t.phrase,t.location??"",...t.rawItems.map(s=>s.provider)].join(" ")}function sr(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 nr(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 ar(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 m=t.length-1;m>=0&&t[m].citationState===r;m--)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 kd(t,s){return t.map(n=>bi(n,s))}function bi(t,s){return s==="citations"?t:{...t,citationState:sr(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:sr(n,s)}))}}function rr(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",m=i==="cited"||i==="emerging";return r==="lost"||i!==null&&m&&!o?{key:s,label:`Lost ${n}`,tone:"negative"}:r==="emerging"||i!==null&&!m&&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 Pd(t){const s=ha(kd(t,"mentions")),n=ha(t);return[rr(s,"mentions"),rr(n,"citations")]}function Ad({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 ir({items:t}){return e.jsx("div",{className:"mt-1 flex flex-wrap gap-1","aria-label":"Latest run mention and citation signals",children:Pd(t).map(s=>e.jsx(Ad,{signal:s},s.key))})}function Rd({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:a}=Qr(),[r,i]=l.useState(new Set),[o,m]=l.useState("mentions"),[u,h]=l.useState(n),x=l.useMemo(()=>{const _=new Map;for(const O of t){const $=O.query,g=s?O.location??null:null,v=s?JSON.stringify([$,g]):$,C=_.get(v)??{key:v,phrase:$,location:g,items:[],rawItems:[]};C.items.push(bi(O,o)),C.rawItems.push(O),_.set(v,C)}return[..._.values()]},[t,o,s]),c=Rn({rows:x,getSearchText:Cd}),y=c.rows.map(_=>_.key),N=y.length>0&&y.every(_=>r.has(_)),f=_=>{i(O=>{const $=new Set(O);return $.has(_)?$.delete(_):$.add(_),$})},b=o==="mentions"?"mentioned":"cited",p=o==="mentions"?"Mention History":"Citation History",T=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:()=>m("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:()=>m("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(_=>{const O=new Set(_);for(const $ of y)N?O.delete($):O.add($);return O})},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":u==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${u==="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":u==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${u==="detailed"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>h("detailed"),children:"Detailed"})]})]})]})]}),x.length>0?e.jsx(Ys,{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:_,phrase:O,location:$,items:g,rawItems:v})=>{const C=r.has(_),J=g.map(M=>M.citationState),z=J.includes("cited")?"cited":J.includes("emerging")?"emerging":J.includes("lost")?"lost":J.every(M=>M==="pending")?"pending":"not-cited",P=ha(g),k=g.filter(M=>M.citationState===ll.cited||M.citationState==="emerging").length,U=ar(P,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(_),onKeyDown:M=>{(M.key==="Enter"||M.key===" ")&&(M.preventDefault(),f(_))},tabIndex:0,role:"button","aria-expanded":C,children:[e.jsx("td",{children:e.jsx(Vc,{size:14,className:`transition-transform duration-150 text-muted ${C?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-heading",children:O}),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(M=>e.jsx(Is,{provider:M.provider},M.id))})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ma,{state:z,label:nr(z,o)}),e.jsxs("span",{className:"text-[11px] text-muted",title:`${k} of ${g.length} engines ${T}`,children:[k,"/",g.length]})]})}),e.jsx("td",{children:e.jsx(tr,{history:P})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:U}),e.jsx(ir,{items:v})]}),e.jsx("td",{})]}),C&&g.map((M,te)=>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:M.provider})}),e.jsx("td",{children:e.jsx(ma,{state:M.citationState,label:nr(M.citationState,o)})}),e.jsx("td",{children:e.jsx(tr,{history:M.runHistory})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:ar(M.runHistory,o)}),e.jsx(ir,{items:[v[te]??M]})]}),e.jsx("td",{children:e.jsx(A,{variant:"ghost",size:"sm",type:"button",onClick:je=>{je.stopPropagation(),a(M.id)},children:"View"})})]}),u==="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(Ld,{item:M,onViewFull:()=>a(M.id)})})]})]},M.id))]},_)})})]})}),c.totalRows===0&&c.hasQuery?e.jsx("p",{className:"supporting-copy mt-3",children:"No tracked queries match this filter."}):null,e.jsx(Ps,{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 $d(t){const s=(t.matchedTerms??[]).filter(r=>r.trim().length>2),n=[...t.competitorDomains.flatMap(r=>{const i=cl(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 Id(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 Ld({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}=Id(t.answerSnippet,Sd),i=$d(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:ol(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 Td({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 m=a!=null&&a.toLowerCase()===o.domain.toLowerCase(),u=[r?"cursor-pointer hover:bg-mono-800/30 transition-colors":"",m?"bg-negative-950/20":""].filter(Boolean).join(" ");return e.jsxs("tr",{className:u,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(ue,{tone:dl(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 gn({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 Md=6,Ts="__other__",Rs="_socialTotal";function Dd(t,s=Md){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),m=new Map;for(const x of t){let c=m.get(x.date);c||(c={date:x.date,[Rs]:0},m.set(x.date,c));const y=i.has(x.source)?x.source:Ts;c[y]=(c[y]??0)+x.sessions,c[Rs]=(c[Rs]??0)+x.sessions}const u=[...m.values()].sort((x,c)=>String(x.date).localeCompare(String(c.date))),h=r.map(([x])=>x);return o>0&&h.push(Ts),{data:u,sources:h,otherCount:o}}function $s(t){return t.replace(/\+/g," ")}function yi(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const lr="_totalSessions",or="_organicSessions";function Ed(t,s){const n=new Map;for(const o of s)n.set(o.date,{[lr]:o.sessions,[or]:o.organicSessions});for(const o of t.days){let m=n.get(o.date);m||(m={[lr]:0,[or]:0},n.set(o.date,m));for(const u of o.bySource)m[u.source]=(m[u.source]??0)+u.sessions}const a=[...n.entries()].sort(([o],[m])=>o.localeCompare(m)).map(([o,m])=>({date:o,...m})),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 qd=["7d","30d","90d","all"],ts=mt,xa=It.textDim,ji=It.textFaint,Gs=25;function Od(t){return Bc(t.landingPage)}const Fd=25,Qn={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0};function fn(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function vi(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 _d({projectName:t}){const{data:s,isLoading:n,isError:a}=sd(t);if(n)return e.jsx(he,{className:"p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading server activity…"})});if(a)return e.jsx(he,{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."," ",!Y()&&e.jsx(_t,{to:"/traffic",className:"text-link hover:underline",children:"Manage sources →"})]})]})}),r.length===0?e.jsx(he,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-secondary",children:["No server traffic source connected yet."," ",!Y()&&e.jsxs(e.Fragment,{children:[e.jsx(_t,{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(he,{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(ue,{tone:nd(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?vi(i.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:Y()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(_t,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:i.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},i.id))})]})})]})}function Ud({projectName:t}){return e.jsxs("div",{className:"space-y-10",children:[e.jsx(_d,{projectName:t}),e.jsx(Gd,{projectName:t})]})}function Gd({projectName:t}){const s=rs(),[n,a]=l.useState(null),[r,i]=l.useState(null),[o,m]=l.useState(!0),[u,h]=l.useState(!1),[x,c]=l.useState(!1),[y,N]=l.useState(null),[f,b]=l.useState(null),[p,T]=l.useState("sessions"),[_,O]=l.useState("desc"),[$,g]=l.useState("sessions"),[v,C]=l.useState("desc"),[J,z]=l.useState("sessions"),[P,k]=l.useState("desc"),[U,M]=l.useState("sessions"),[te,je]=l.useState("desc"),[le,Q]=l.useState(Qn),[de,oe]=l.useState([]),[G,F]=l.useState([]),[w,Z]=l.useState(!1),[re,ce]=l.useState("30d");async function K(E){m(!0),N(null);try{const Ne=await s.fetchQuery({...ul({client:V,path:{name:t}}),staleTime:Us});if(E.current)return;if(a(Ne),!Ne.connected){i(null),Q(Qn),oe([]),F([]),m(!1);return}const me=re==="all"?void 0:re,[fe,kt,Mt,tt]=await Promise.all([s.fetchQuery({...ml({client:V,path:{name:t},query:me?{window:me}:void 0}),staleTime:Us}).then(Pt=>Pt),s.fetchQuery({...hl({client:V,path:{name:t},query:me?{window:me}:void 0}),staleTime:Us}).catch(()=>Qn),s.fetchQuery({...xl({client:V,path:{name:t},query:me?{window:me}:void 0}),staleTime:Us}).catch(()=>[]),s.fetchQuery({...pl({client:V,path:{name:t},query:me?{window:me}:void 0}),staleTime:Us}).catch(()=>[])]);if(E.current)return;i(fe),Q(kt),oe(Mt),F(tt),m(!1)}catch(Ne){if(E.current)return;N(Ne instanceof Error?Ne.message:"Failed to load GA4 data"),m(!1)}}l.useEffect(()=>{const E={current:!1};return K(E),()=>{E.current=!0}},[t,re,s]);async function xe(){h(!0),N(null),b(null);try{const E=await Hr(t);b(`Synced ${E.rowCount.toLocaleString()} page rows, ${E.aiReferralCount.toLocaleString()} AI and ${E.socialReferralCount.toLocaleString()} social referral rows (${E.days} days)`),await at(s,"ga"),await K({current:!1})}catch(E){N(E instanceof Error?E.message:"Sync failed")}finally{h(!1)}}async function q(){c(!0),N(null),b(null);try{await gl(t),await at(s,"ga"),a({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),i(null),b("GA4 disconnected")}catch(E){N(E instanceof Error?E.message:"Disconnect failed")}finally{c(!1)}}function ie(E){p===E?O(Ne=>Ne==="desc"?"asc":"desc"):(T(E),O("desc"))}function Se(E){$===E?C(Ne=>Ne==="desc"?"asc":"desc"):(g(E),C("desc"))}function Xe(E){J===E?k(Ne=>Ne==="desc"?"asc":"desc"):(z(E),k("desc"))}const rt=l.useMemo(()=>r?.topPages?[...r.topPages].sort((E,Ne)=>{const me=E[p],fe=Ne[p];return typeof me=="string"&&typeof fe=="string"?_==="asc"?me.localeCompare(fe):fe.localeCompare(me):_==="asc"?me-fe:fe-me}):[],[r?.topPages,p,_]),it=l.useMemo(()=>r?.aiReferrals?[...r.aiReferrals].sort((E,Ne)=>{const me=E[$],fe=Ne[$];return typeof me=="string"&&typeof fe=="string"?v==="asc"?me.localeCompare(fe):fe.localeCompare(me):v==="asc"?me-fe:fe-me}):[],[r?.aiReferrals,$,v]),Ge=l.useMemo(()=>r?.aiReferralLandingPages?[...r.aiReferralLandingPages].sort((E,Ne)=>{const me=E[U],fe=Ne[U];return typeof me=="string"&&typeof fe=="string"?te==="asc"?me.localeCompare(fe):fe.localeCompare(me):te==="asc"?me-fe:fe-me}):[],[r?.aiReferralLandingPages,U,te]),X=Rn({rows:Ge,getSearchText:Od,pageSize:Fd}),Be=X.totalRows>0?`${X.totalRows.toLocaleString()} ${X.hasQuery?X.totalRows===1?"match":"matches":X.totalRows===1?"row":"rows"}`:X.hasQuery&&(r?.aiReferralLandingPages.length??0)>0?"0 matches":"No landing-page rows";function Ve(E){X.setPage(1),U===E?je(Ne=>Ne==="desc"?"asc":"desc"):(M(E),je("desc"))}const Pe=l.useMemo(()=>r?.socialReferrals?[...r.socialReferrals].sort((E,Ne)=>{const me=E[J],fe=Ne[J];return typeof me=="string"&&typeof fe=="string"?P==="asc"?me.localeCompare(fe):fe.localeCompare(me):P==="asc"?me-fe:fe-me}):[],[r?.socialReferrals,J,P]),{socialChartData:He,socialChartSources:Ce,socialOtherCount:ve}=l.useMemo(()=>{const E=Dd(G);return{socialChartData:E.data,socialChartSources:E.sources,socialOtherCount:E.otherCount}},[G]),{chartData:D,chartSources:R,dateRange:I}=l.useMemo(()=>{const E=Ed(le,de);return{chartData:E.data,chartSources:E.sources,dateRange:E.dateRange}},[le,de]);if(o&&!n)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!n?.connected)return Y()?e.jsx(he,{className:"p-5",children:e.jsx("div",{className:"text-sm text-secondary",children:"No Google Analytics 4 property connected yet."})}):e.jsx(Bd,{projectName:t,onConnected:()=>{(async()=>(await at(s,"ga"),await K({current:!1})))()}});const be=r?.organicSharePctDisplay??"0%",De=r?.channelBreakdown?.organic.sharePctDisplay??be,H=r?.channelBreakdown?.organic.sessions??r?.totalOrganicSessions??0,Ee=r?.aiSessionsDeduped??0,lt=r?.channelBreakdown?.ai.sessions??r?.aiSessionsBySession??0,bt=r?.channelBreakdown?.ai.sharePctDisplay??r?.aiSharePctBySessionDisplay??"0%",ke=r?.paidAiSessionsBySession??0,Oe=r?.paidAiSharePctBySessionDisplay??"0%",ht=r?new Set(r.aiReferrals.map(E=>E.source.toLowerCase())).size:0,Ue=it[0]??null,We=r?.totalDirectSessions??0,Ae=r?.directSharePctDisplay??"0%",jt=r?.channelBreakdown?.direct.sessions??We,Ct=r?.channelBreakdown?.direct.sharePctDisplay??Ae,Le=r?.channelBreakdown?.other.sessions??r?.otherSessions??0,Te=r?.channelBreakdown?.other.sharePctDisplay??r?.otherSharePctDisplay??"0%",ot=r?.socialSessions??0,Fe=r?.socialSharePctDisplay??"0%",Tt=r?.channelBreakdown?.social.sessions??ot,vt=r?.channelBreakdown?.social.sharePctDisplay??Fe,pt=r?new Set(r.socialReferrals.map(E=>E.source.toLowerCase())).size:0,Je=Pe[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})]})]})]}),!Y()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(A,{variant:"outline",size:"sm",disabled:u,onClick:Ie(xe),children:[e.jsx($n,{className:`w-3.5 h-3.5 mr-1.5 ${u?"animate-spin":""}`}),u?"Syncing…":"Sync"]}),e.jsxs(A,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:x,onClick:Ie(q),children:[e.jsx(zc,{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:qd.map(E=>e.jsx("button",{type:"button","aria-pressed":re===E,className:`segmented-option ${re===E?"segmented-option-active":""}`,onClick:()=>ce(E),children:E==="all"?"All":E},E))})]}),r?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(Hn,{value:fn(r.totalSessions),label:"Total Sessions",subtitle:r.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(Hn,{value:fn(r.totalOrganicSessions),label:"Organic Sessions",subtitle:`${be} of total`,tone:"positive"}),e.jsx(Hn,{value:fn(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."}),!Y()&&e.jsxs(A,{variant:"outline",size:"sm",disabled:u,onClick:Ie(xe),children:[e.jsx($n,{className:`w-3.5 h-3.5 mr-1.5 ${u?"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."})]})]}),I&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(I.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(I.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),D.length>0&&e.jsxs(he,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:R.length>0?"AI vs. total sessions":"All sessions (baseline)"}),R.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),R.length===0&&e.jsx("p",{className:"text-xs text-muted",children:"No AI referrals detected yet"})]}),e.jsx("div",{className:"h-64",children:e.jsx(tn,{width:"100%",height:"100%",children:e.jsxs(sn,{data:D,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(nn,{dataKey:"date",tick:Ft,tickLine:!1,axisLine:{stroke:bs},tickFormatter:Tn}),e.jsx(an,{tick:Ft,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(rn,{...As,labelFormatter:ps,formatter:(E,Ne)=>{const me=typeof E=="number"?E.toLocaleString():String(E??0),fe=String(Ne??"");return fe==="_totalSessions"?[me,"Total Sessions"]:fe==="_organicSessions"?[me,"Organic Sessions"]:[me,fe]}}),e.jsx(oi,{wrapperStyle:{fontSize:11,color:It.text},formatter:E=>E==="_totalSessions"?"Total Sessions":E==="_organicSessions"?"Organic Sessions":E}),e.jsx(Cs,{type:"monotone",dataKey:"_totalSessions",stroke:It.textFaint,fill:It.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),R.map((E,Ne)=>e.jsx(Cs,{type:"monotone",dataKey:E,stackId:"ai",stroke:ts[Ne%ts.length],fill:ts[Ne%ts.length],fillOpacity:.4,strokeWidth:1.5},E))]})})})]}),e.jsxs(he,{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(Lt,{label:"Organic",value:De,hint:`${H.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(Lt,{label:"Social",value:vt,hint:`${Tt.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(Lt,{label:"Direct",value:Ct,hint:`${jt.toLocaleString()} sessions`,tone:"neutral",tooltip:"Sessions with no source — bookmarks, typed URLs, untagged email, in-app browsers, and AI-driven traffic whose referrer header was stripped. Known AI referrers are removed if GA4 classified them as Direct."}),e.jsx(Lt,{label:"Known AI referrers (lower bound)",value:bt,hint:ke>0?`${lt.toLocaleString()} sessions · ${ke.toLocaleString()} paid`:`${lt.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(Lt,{label:"Other channels",value:Te,hint:`${Le.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."})]}),Ue&&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:Ue.source})," via ",Ue.medium,", accounting for ",Ue.sessions.toLocaleString()," sessions.",ke>0&&e.jsxs("span",{children:[" Paid AI: ",ke.toLocaleString()," sessions (",Oe,")."]})]})]}),e.jsxs(he,{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?`${ht} 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(St,{label:"Source",sortKey:"source",current:$,dir:v,onSort:Se,align:"left"}),e.jsx(St,{label:"Medium",sortKey:"medium",current:$,dir:v,onSort:Se,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(St,{label:"Sessions",sortKey:"sessions",current:$,dir:v,onSort:Se,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:it.map(E=>e.jsx(Vd,{referral:E,totalSessions:Ee},`${E.source}:${E.medium}:${E.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(he,{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(Ys,{value:X.query,onChange:X.setQuery,label:"Filter landing page URLs or query parameters",placeholder:"Filter URL or query parameters",className:"mb-4 max-w-md"}),X.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(St,{label:"Landing Page",sortKey:"landingPage",current:U,dir:te,onSort:Ve,align:"left"}),e.jsx(St,{label:"Source",sortKey:"source",current:U,dir:te,onSort:Ve,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(St,{label:"Sessions",sortKey:"sessions",current:U,dir:te,onSort:Ve,align:"right"})]})}),e.jsx("tbody",{children:X.rows.map(E=>e.jsx(zd,{row:E},`${E.landingPage}:${E.source}:${E.medium}:${E.sourceDimension}`))})]})}),e.jsx(Ps,{page:X.page,pageSize:X.pageSize,visibleRows:X.rows.length,totalRows:X.totalRows,onPageChange:X.setPage,itemLabel:X.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:()=>X.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."})]})]}),He.length>0&&e.jsxs(he,{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"})]}),ve>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",Ce.length-1," sources · ",ve," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(tn,{width:"100%",height:"100%",children:e.jsxs(sn,{data:He,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(nn,{dataKey:"date",tick:Ft,tickLine:!1,axisLine:{stroke:bs},tickFormatter:Tn}),e.jsx(an,{tick:Ft,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(rn,{...As,labelFormatter:ps,formatter:(E,Ne)=>{const me=typeof E=="number"?E.toLocaleString():String(E??0),fe=String(Ne??"");if(fe===Rs)return[me,"Total Social"];if(fe===Ts){const kt=`Other (${ve} source${ve===1?"":"s"})`;return[me,kt]}return[me,$s(fe)]}}),e.jsx(Cs,{type:"monotone",dataKey:Rs,stroke:ji,fill:It.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),Ce.map((E,Ne)=>{const fe=E===Ts?xa:ts[Ne%ts.length];return e.jsx(Cs,{type:"monotone",dataKey:E,stackId:"social",stroke:fe,fill:fe,fillOpacity:.4,strokeWidth:1.5},E)})]})})}),e.jsx(Hd,{sources:Ce,otherCount:ve})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.5fr)]",children:[e.jsxs(he,{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(Lt,{label:"Social Sessions",value:fn(ot),hint:`${ot.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(Lt,{label:"Share of Traffic",value:Fe,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(Lt,{label:"Platforms",value:String(pt),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."})]}),Je&&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:`${Je.source} via ${Je.medium}`,children:yi($s(Je.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:Je.medium,children:["via ",$s(Je.medium)," · ",Je.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(Lt,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(Lt,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(Lt,{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(he,{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?Pe.length>Gs&&!w?`Top ${Gs} of ${Pe.length}`:`${Pe.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(St,{label:"Source",sortKey:"source",current:J,dir:P,onSort:Xe,align:"left"}),e.jsx(St,{label:"Medium",sortKey:"medium",current:J,dir:P,onSort:Xe,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(St,{label:"Sessions",sortKey:"sessions",current:J,dir:P,onSort:Xe,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(St,{label:"Users",sortKey:"users",current:J,dir:P,onSort:Xe,align:"right"})]})}),e.jsx("tbody",{children:(w?Pe:Pe.slice(0,Gs)).map(E=>e.jsx(Qd,{referral:E,totalSessions:ot},`${E.source}:${E.medium}:${E.channelGroup}`))})]})}),Pe.length>Gs&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>Z(E=>!E),className:"rounded-md border border-base px-3 py-1.5 text-xs text-secondary transition-colors hover:border-strong hover:text-strong",children:w?`Show top ${Gs}`:`Show all ${Pe.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(St,{label:"Landing Page",sortKey:"landingPage",current:p,dir:_,onSort:ie,align:"left"}),e.jsx(St,{label:"Sessions",sortKey:"sessions",current:p,dir:_,onSort:ie,align:"right"}),e.jsx(St,{label:"Organic",sortKey:"organicSessions",current:p,dir:_,onSort:ie,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"})]})}),e.jsx("tbody",{children:rt.map(E=>e.jsx(Kd,{page:E},E.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 ${vi(r.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:r?`${r.topPages.length} pages · ${r.aiReferrals.length} AI rows · ${r.socialReferrals.length} social rows`:""})]})]})}function Bd({projectName:t,onConnected:s}){const[n,a]=l.useState(""),[r,i]=l.useState(null),[o,m]=l.useState(null),[u,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 T=new FileReader;T.onload=()=>{const _=T.result;try{const O=JSON.parse(_);if(!O.client_email||!O.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)."),m(null);return}m(_)}catch{c("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),m(null)}},T.onerror=()=>{c("Failed to read file."),m(null)},T.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 fl(t,{propertyId:n.trim(),keyJson:o});try{await Hr(t)}catch{}s()}catch(b){c(b instanceof Error?b.message:"Failed to connect GA4")}finally{h(!1)}}return e.jsxs(he,{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(Qc,{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(A,{variant:"default",size:"sm",disabled:u||!n.trim()||!o,onClick:Ie(f),children:u?"Connecting & syncing…":"Connect GA4"})]})}function St({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 Ni={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function Hn({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 ${Ni[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Lt({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 ${Ni[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 wi={session:"Session",first_user:"First Visit",manual_utm:"UTM"},Si={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 Vd({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=wi[t.sourceDimension]??t.sourceDimension,r=Si[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 zd({row:t}){const s=wi[t.sourceDimension]??t.sourceDimension,n=Si[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(Cn,{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 Qd({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 Hd({sources:t,otherCount:s}){const n=[{key:Rs,color:ji,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const r=t[a];if(r===Ts)n.push({key:Ts,color:xa,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const i=$s(r);n.push({key:r,color:ts[a%ts.length]??xa,label:yi(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 Wd(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 Yd=["7d","30d","90d","all"],bn=500,cr=[{key:"clicks",label:"Clicks",color:mt[1],format:t=>t.toLocaleString()},{key:"impressions",label:"Impressions",color:mt[4],format:t=>t.toLocaleString()},{key:"ctr",label:"CTR",color:gs.caution,format:t=>`${(t*100).toFixed(1)}%`},{key:"position",label:"Avg position",color:mt[2],inverted:!0,format:t=>t.toFixed(1)}],Zt=25,Xd="canonry:google-oauth-complete",Jd=new Intl.NumberFormat(void 0,{maximumFractionDigits:1});function Zd(t,s,n){const{startIndex:a,endIndex:r}=t,i=a!==void 0&&r!==void 0&&Number.isInteger(a)&&Number.isInteger(r)&&a>=0&&r>=a?r-a+1:n;if(!Number.isFinite(t.start)||!Number.isFinite(t.end)||t.start<=0||t.end<0)return"— no percentage baseline";if(t.slope===0)return`→ 0% over ${i}d`;const o=ui(t.end,t.start);if(o===null)return"— no percentage baseline";const m=Math.abs(o*100),u=m<.1?"<0.1%":`${Jd.format(m)}%`;return`${(s?t.slope<0:t.slope>0)?"↑":"↓"} ${u} over ${i}d`}function dr(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function ur(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 mr(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=rs(),[a,r]=l.useState(!1),[i,o]=l.useState([]),[m,u]=l.useState([]),[h,x]=l.useState([]),[c,y]=l.useState(null),[N,f]=l.useState([]),[b,p]=l.useState([]),[T,_]=l.useState(null),[O,$]=l.useState(""),[g,v]=l.useState(""),[C,J]=l.useState("30"),[z,P]=l.useState(!1),[k,U]=l.useState("30d"),[M,te]=l.useState(["clicks","impressions"]),[je,le]=l.useState(!0),[Q,de]=l.useState(null),[oe,G]=l.useState(0),[F,w]=l.useState({startDate:"",endDate:"",query:"",page:""}),[Z,re]=l.useState(0),[ce,K]=l.useState(!1),[xe,q]=l.useState(0),[ie,Se]=l.useState(!1),[Xe,rt]=l.useState(""),[it,Ge]=l.useState(!0),[X,Be]=l.useState(!1),[Ve,Pe]=l.useState(!1),[He,Ce]=l.useState(!1),[ve,D]=l.useState(!1),[R,I]=l.useState(!1),[be,De]=l.useState(!1),[H,Ee]=l.useState(null),[lt,bt]=l.useState(!1),[ke,Oe]=l.useState(!1),[ht,Ue]=l.useState(null),[We,Ae]=l.useState(null),[jt,Ct]=l.useState([]),[Le,Te]=l.useState(new Set),[ot,Fe]=l.useState({}),[Tt,vt]=l.useState(new Set),[pt,Je]=l.useState(""),[E,Ne]=l.useState(null),[me,fe]=l.useState(""),[kt,Mt]=l.useState(!1),[tt,Pt]=l.useState(!1),[is,Ds]=l.useState(!1),[Dt,Es]=l.useState(!1),[Ze,qs]=l.useState("indexed"),[Nt,Os]=l.useState(null),Qt=!!(F.query.trim()||F.page.trim()||Nt),ys=Nt!==null,ls=l.useMemo(()=>{if(!Nt)return h;const{key:d,dir:L}=Nt;return[...h].sort((W,ae)=>{const $e=d===hs.CTR?Number.isFinite(W.ctr)?W.ctr:0:W[d],qe=d===hs.CTR?Number.isFinite(ae.ctr)?ae.ctr:0:ae[d];return L==="asc"?$e-qe:qe-$e})},[h,Nt]),Ye=Rn({rows:ls,pageSize:Bt}),js=ie?Ye.rows:ls,Et=Rn({rows:(ht??[]).filter(d=>d.path.toLowerCase().includes(pt.trim().toLowerCase())),pageSize:Bt}),[yt,vs]=l.useState([]),[st,Ht]=l.useState(null),[j,ge]=l.useState(1),ye=l.useMemo(()=>{if(yt.length<2)return null;const d=yt[yt.length-1],L=yt[yt.length-2];return{indexed:d.indexed-L.indexed,notIndexed:d.notIndexed-L.notIndexed}},[yt]);l.useEffect(()=>{ge(1)},[H,Ze,st]);const S=l.useMemo(()=>st?(H?.reasonGroups??[]).find(d=>d.reason===st):void 0,[H,st]),B=l.useMemo(()=>H?Ze==="indexed"?H.indexed:Ze==="deindexed"?H.deindexed:Ze==="notIndexed"?st?S?.urls??[]:(H.reasonGroups??[]).length===0?H.notIndexed:[]:[]:[],[H,Ze,st,S]),pe=Math.max(1,Math.ceil(B.length/Zt)),ee=Math.min(Math.max(1,j),pe),se=(ee-1)*Zt,Re=l.useMemo(()=>H?.indexed.slice(se,se+Zt)??[],[H,se]),Wt=l.useMemo(()=>H?.notIndexed.slice(se,se+Zt)??[],[H,se]),xt=l.useMemo(()=>H?.deindexed.slice(se,se+Zt)??[],[H,se]),Fs=l.useMemo(()=>(S?.urls??[]).slice(se,se+Zt),[S,se]),[At,Yt]=l.useState(!1),[Ma,Me]=l.useState(null),[Ut,un]=l.useState(null),[Da,Gt]=l.useState(null);function Vi(d,L){const W=ad(d),ae=Wd(W);ae?(un(ae),Me(null)):(un(null),Me(W.message||L))}const wt=i.find(d=>d.connectionType==="gsc"),os=(wt?.scopes??[]).includes("https://www.googleapis.com/auth/webmasters"),qn=jt.length>0?jt:(ht??[]).map(d=>d.path),Ea=qn.filter(d=>ht?.some(L=>L.path===d&&L.isSitemapsIndex)).length,zi=Ea===1?"Resubmit sitemap index":Ea>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",Qi=h.length>0||N.length>0||b.length>0,On=bl(),Fn=yl();async function qa(d,L=!1){if(!d){u([]),$("");return}Pe(!0);try{const{sites:W}=await n.fetchQuery({...Ll({client:V,path:{name:t}}),staleTime:L?0:ut});u(W),$(d.propertyId??W[0]?.siteUrl??""),un(null)}catch(W){u([]),Vi(W,"Failed to load Search Console properties")}finally{Pe(!1)}}async function _s(d){D(!0);const L=d??Z;try{const W=Qt?bn:Bt,ae=Qt?0:L,$e={limit:String(W)};F.startDate&&($e.startDate=F.startDate),F.endDate&&($e.endDate=F.endDate),F.query&&($e.query=F.query),F.page&&($e.page=F.page),ae>0&&($e.offset=String(ae)),k&&k!=="all"&&!F.startDate&&($e.window=k);const qe=await n.fetchQuery({...Nl({client:V,path:{name:t},query:$e}),staleTime:ut}),Ke=qe.rows;Qt?(K(!1),x(Ke),q(Ke.length),Se(!0)):(K(ae+Ke.length<qe.totalMatching),x(Ke),q(0),Se(!1))}catch(W){x([]),K(!1),q(0),Me(W instanceof Error?W.message:"Failed to load GSC performance data")}finally{D(!1)}}async function _n(){try{const d={};F.startDate&&(d.startDate=F.startDate),F.endDate&&(d.endDate=F.endDate),k&&k!=="all"&&!F.startDate&&(d.window=k);const L=await n.fetchQuery({...vl({client:V,path:{name:t},query:d}),staleTime:ut});y(L)}catch{y(null)}}async function mn(d=!1){I(!0);try{const L=Xe.trim()||void 0,W={limit:"20"};L&&(W.url=L);const[ae,$e]=await Promise.all([n.fetchQuery({...$l({client:V,path:{name:t},query:W}),staleTime:d?0:ut}),n.fetchQuery({...Il({client:V,path:{name:t}}),staleTime:d?0:ut})]);f(ae),p($e)}catch(L){f([]),p([]),Me(L instanceof Error?L.message:"Failed to load GSC inspection history")}finally{I(!1)}}async function Oa(d=!1){bt(!0);try{const[L,W]=await Promise.all([n.fetchQuery({...Yr({client:V,path:{name:t}}),staleTime:d?0:ut}),n.fetchQuery({...Cl({client:V,path:{name:t}}),staleTime:d?0:ut}).catch(()=>[])]);Ee(L),vs(W)}catch(L){Ee(null),vs([]),Me(L instanceof Error?L.message:"Failed to load coverage data")}finally{bt(!1)}}async function Fa(d){Yt(!0),Me(null);try{const L=await Ha(t,{urls:d}),{succeeded:W,failed:ae,total:$e}=L.summary;we({title:"Indexing requested",detail:ae===0?`${W} URL${W!==1?"s":""} submitted for indexing.`:`${W}/${$e} submitted successfully, ${ae} failed.`,tone:ae===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(L){Me(L instanceof Error?L.message:"Failed to request indexing")}finally{Yt(!1)}}async function Hi(){Yt(!0),Me(null);try{const d=await Ha(t,{urls:[],allUnindexed:!0}),{succeeded:L,failed:W,total:ae}=d.summary;we({title:"Indexing requested",detail:W===0?`${L} unindexed URL${L!==1?"s":""} submitted for indexing.`:`${L}/${ae} submitted successfully, ${W} failed.`,tone:W===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(d){Me(d instanceof Error?d.message:"Failed to request indexing")}finally{Yt(!1)}}async function Un(){Oe(!0),Me(null);try{const d=await Bn(t);n.setQueryData(kl({client:V,path:{name:t}}),d),Ue(d.sitemaps),Ae(d.summary),Ct(d.preferredSubmissionUrls),Te(new Set),Fe({}),d.sitemaps.length===0&&Gt("No sitemaps found in this GSC property. Submit one here to start Google processing it.")}catch(d){Me(d instanceof Error?d.message:"Failed to list sitemaps")}finally{Oe(!1)}}async function Wi(d){const L=Le.has(d);if(Te(W=>{const ae=new Set(W);return L?ae.delete(d):ae.add(d),ae}),!(L||ot[d])){vt(W=>new Set(W).add(d));try{const W=await Bn(t,d);Fe(ae=>({...ae,[d]:W.sitemaps}))}catch(W){Me(W instanceof Error?W.message:"Failed to load sitemap files")}finally{vt(W=>{const ae=new Set(W);return ae.delete(d),ae})}}}async function Ns(d){if(!os||d.length===0)return;const L=[...new Set(d)];Pt(!0),Me(null),Ne({completed:0,total:L.length});let W=0,ae=0,$e=0,qe=null;try{for(let ct=0;ct<L.length;ct+=50){const ne=L.slice(ct,ct+50);try{const dt=await Pl(t,ne);W+=dt.summary.accepted,ae+=dt.summary.failed,$e+=ne.length,Ne({completed:$e,total:L.length})}catch(dt){$e+=ne.length;const Xt=ne.length,hn=L.length-$e,xn=dt instanceof Error?dt.message:"The batch request failed",Jt=`${W} accepted, ${ae} failed, ${Xt} unconfirmed, ${hn} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;qe=`Sitemap submission stopped after a batch request failed. ${Jt} ${xn}`,Me(qe),we({title:"Sitemap resubmission partially completed",detail:Jt,tone:"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"});return}}const Ke=L.length;we({title:ae===0?"Sitemap submitted to Google":"Some sitemap submissions need attention",detail:ae===0?"Google accepted the sitemap submission/refetch request; indexing is not guaranteed.":`Google accepted ${W}/${Ke} sitemap submissions; ${ae} failed. Indexing is not guaranteed.`,tone:ae===0?"positive":"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"}),fe("")}catch(Ke){Me(Ke instanceof Error?Ke.message:"Failed to submit sitemap to Google")}finally{Pt(!1),Ne(null),await Un(),qe&&Me(qe)}}async function Yi(){Pt(!0);const d=ht??[];try{const L=d.filter(ae=>ae.isSitemapsIndex),W=[];for(let ae=0;ae<L.length;ae+=4)(await Promise.all(L.slice(ae,ae+4).map(async qe=>{const Ke=ot[qe.path];if(Ke)return Ke;const ct=await Bn(t,qe.path);return Fe(ne=>({...ne,[qe.path]:ct.sitemaps})),ct.sitemaps}))).forEach((qe,Ke)=>{W.push(...qe.length>0?qe.map(ct=>ct.path):[L[ae+Ke].path])});await Ns([...d.filter(ae=>!ae.isSitemapsIndex).map(ae=>ae.path),...W])}catch(L){Me(L instanceof Error?L.message:"Failed to load sitemap files"),Pt(!1)}}async function _a(d){Mt(!0),Me(null);try{await Al(t,"gsc",d),await at(n,"google"),o(L=>L.map(W=>W.connectionType==="gsc"?{...W,sitemapUrl:d}:W)),we({title:"Default sitemap updated",detail:d,tone:"positive",dedupeKey:`gsc:sitemap-default:${t}`,dedupeMode:"replace"})}catch(L){Me(L instanceof Error?L.message:"Failed to set the default sitemap")}finally{Mt(!1)}}async function Ua(d){try{await Fn.mutateAsync({projectName:t,projectLabel:t,opts:d?{sitemapUrl:d}:void 0})}catch{}}async function Ga(){Ge(!0),Me(null);try{const[d,L]=await Promise.all([Wr().catch(()=>null),n.fetchQuery({...Na({client:V,path:{name:t}}),staleTime:ut}).catch(()=>[])]);r(!!d?.google?.configured),o(L);const W=L.find(ae=>ae.connectionType==="gsc");await Promise.all([qa(W),_s(),_n(),mn(),Oa(),W?.propertyId?Un():Promise.resolve()])}finally{Ge(!1)}}l.useEffect(()=>{Ga()},[t,s]),l.useEffect(()=>{re(0),de(null),w(d=>d.startDate||d.endDate?{...d,startDate:"",endDate:""}:d),G(d=>d+1),_n()},[k]);const Ba=l.useRef(!1);l.useEffect(()=>{if(!Ba.current){Ba.current=!0;return}re(0),Ye.setPage(1),_s(0)},[oe]);function Gn(d){const L=Q===d?null:d;de(L),w(W=>({...W,startDate:L??"",endDate:L??""})),G(W=>W+1)}const Ka=l.useRef(!1);l.useEffect(()=>{if(!Ka.current){Ka.current=!0;return}re(0),_s(0)},[ys]);async function Va(){if(!a){Me("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}Be(!0),Me(null),Gt(null);try{let d=function(dt){if(dt.source!==ae||dt.origin!==$e||!dt.data||typeof dt.data!="object")return;const Xt=dt.data;Xt.type!==Xd||Xt.connectionType!=="gsc"||ne(!0)};const{authUrl:L,redirectUri:W}=await Sl(t,"gsc");if(!L.startsWith("https://accounts.google.com/")){Me("Unexpected OAuth redirect URL. Please try again.");return}const ae=window.open(L,"_blank","width=600,height=700");if(!ae){window.location.assign(L);return}const $e=W?new URL(W).origin:window.location.origin;let qe=!1,Ke=null;const ct=()=>{Ke!==null&&window.clearInterval(Ke),window.removeEventListener("message",d)},ne=async dt=>{if(!qe){qe=!0,ct(),Gt(dt?"Google connected. Refreshing access…":"Refreshing Google connection…");try{await at(n,"google"),await Ga()}finally{Gt(null)}}};window.addEventListener("message",d),Gt("Finish the Google consent flow in the popup. This page will refresh automatically."),Ke=window.setInterval(()=>{ae.closed&&ne(!1)},1e3)}catch(d){Me(d instanceof Error?d.message:"Failed to start OAuth flow")}finally{Be(!1)}}async function Xi(){Me(null),Gt(null);try{await wl(t,"gsc"),await at(n,"google"),o(d=>d.filter(L=>L.connectionType!=="gsc")),u([]),$("")}catch(d){Me(d instanceof Error?d.message:"Failed to disconnect")}}async function Ji(){if(O){Ce(!0),Me(null);try{await Tl(t,"gsc",O),await at(n,"google"),o(d=>d.map(L=>L.connectionType==="gsc"?{...L,propertyId:O}:L)),we({title:"GSC property updated",detail:`${t} is now linked to ${O}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(d){Me(d instanceof Error?d.message:"Failed to save GSC property")}finally{Ce(!1)}}}async function Zi(){Me(null),Gt(null);try{await On.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(C,10)||void 0,full:z||void 0}}),await at(n,"gsc")}catch{}}async function za(){if(g.trim()){De(!0),Me(null),Gt(null);try{const d=await Rl(t,g.trim());await at(n,"gsc"),_(d),v(""),await mn()}catch(d){Me(d instanceof Error?d.message:"Failed to inspect URL")}finally{De(!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"})]})}),Ut&&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:Ut.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:Ut.message}),(us(Ut.enableUrl)||us(Ut.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[us(Ut.enableUrl)&&e.jsx("a",{href:us(Ut.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 ↗"}),us(Ut.indexingApiUrl)&&e.jsx("a",{href:us(Ut.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:()=>un(null),children:"×"})]})}),Ma&&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:[Ma,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>Me(null),children:"×"})]}),Da&&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:[Da,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>Gt(null),children:"×"})]}),it?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[wt?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:wt.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Coverage measured"," ",H?.lastInspectedAt?Ot(H.lastInspectedAt):"never"]}),e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:Ie(Xi),children:"Disconnect"})]}):e.jsxs(he,{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(ue,{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(A,{type:"button",variant:"outline",size:"sm",disabled:X,onClick:Ie(Va),children:X?"Opening…":"Connect Google Search Console"}):e.jsx(A,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(_t,{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."})]})]})]}),(wt||Qi)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs(he,{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.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Search performance"}),e.jsx(ze,{text:`Tile percentages show the fitted trend's relative change from its first measured day to its last. Click any day to filter the table below to that date. Query and page filters match case-insensitive substrings and run on Apply filters. Filtering and sorting examine up to ${bn.toLocaleString()} matching rows while the table shows ${Bt} per page.`})]}),c?.window?.startDate&&c.window.endDate&&e.jsxs("p",{className:"text-xs text-muted",children:[c.window.startDate," to ",c.window.endDate,(c.window.daysSinceLatestData??0)>0&&` · latest data ${c.window.daysSinceLatestData} day${c.window.daysSinceLatestData===1?"":"s"} ago`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"segmented",role:"group","aria-label":"Performance time period",children:Yd.map(d=>e.jsx("button",{type:"button","aria-pressed":k===d,className:`segmented-option ${k===d?"segmented-option-active":""}`,onClick:()=>{U(d),re(0),Ye.setPage(1)},children:d==="all"?"All":d},d))}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:ve,onClick:()=>{re(0),Ye.setPage(1),_s(0),_n()},children:ve?"Loading…":"Apply filters"})]})]}),c&&c.daily.length>0&&(()=>{const{totals:d,daily:L,trends:W}=c,$e=cr.filter(ne=>M.includes(ne.key)).map(ne=>({dataKey:ne.key,label:ne.label,color:ne.color,axisId:ne.key,inverted:ne.inverted,formatValue:ne.format,trend:je?W?.[ne.key]??null:null})),qe=ne=>d[ne]??null,Ke=new Map(L.map(ne=>[ne.date,ne])),ct=L.length===0?[]:dd(L[0].date,L[L.length-1].date).map(ne=>Ke.get(ne)??{date:ne});return e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:cr.map(ne=>{const dt=M.includes(ne.key),Xt=qe(ne.key),hn=W?.[ne.key]??null,xn=Xt===null;return e.jsxs("button",{type:"button","aria-pressed":dt,disabled:xn,className:`rounded-md border px-3 py-2 text-left transition-colors ${dt?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${xn?"cursor-not-allowed opacity-50":""}`,onClick:()=>{te(Jt=>Jt.includes(ne.key)?Jt.length===1?Jt:Jt.filter(el=>el!==ne.key):[...Jt,ne.key])},children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2 w-2 rounded-full",style:{backgroundColor:dt?ne.color:"transparent",border:`1px solid ${ne.color}`}}),e.jsx("span",{className:"text-xs text-secondary",children:ne.label})]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:Xt===null?"—":ne.format(Xt)}),hn&&e.jsx("span",{className:"block text-[11px] tabular-nums text-muted",children:Zd(hn,ne.inverted,d.days)})]},ne.key)})}),e.jsx("div",{className:"mt-2 flex items-center justify-end",children:e.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5 text-xs text-secondary",children:[e.jsx("input",{type:"checkbox",className:"accent-mono-400",checked:je,onChange:ne=>le(ne.target.checked)}),"Trend line"]})}),e.jsx("div",{className:"mt-1",children:e.jsx(ed,{data:ct,xKey:"date",series:$e,xTickFormatter:Tn,labelFormatter:ps,onSelectX:Gn,selectedX:Q})}),e.jsx("div",{role:"group","aria-label":"Filter the table to a single day",children:L.map(ne=>e.jsxs("button",{type:"button",className:"sr-only focus:not-sr-only focus:inline-block focus:rounded focus:border focus:border-strong focus:bg-surface-active focus:px-2 focus:py-1 focus:text-xs focus:text-strong","aria-pressed":Q===ne.date,onClick:()=>Gn(ne.date),children:[ps(ne.date),": ",ne.clicks," clicks, ",ne.impressions," impressions"]},ne.date))}),Q&&e.jsxs("div",{className:"mt-1 flex items-center gap-2 text-xs",children:[e.jsxs("span",{className:"text-secondary",children:["Table showing ",ps(Q)]}),e.jsxs("button",{type:"button",className:"text-link hover:underline",onClick:()=>Gn(Q),children:["Show all ",d.days," days"]})]}),d.position!==null&&(d.positionDays??d.days)<d.days&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position covers ",d.positionDays," of ",d.days," days. The rest have no property-level position recorded."]}),(d.position===null||d.position===void 0)&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position needs a property-level sync. Run ",e.jsx("code",{children:"canonry google sync"})," to record it."]})]})})(),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:F.startDate,onChange:d=>w(L=>({...L,startDate:d.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:F.endDate,onChange:d=>w(L=>({...L,endDate:d.target.value}))}),e.jsx(Ys,{value:F.query,onChange:d=>w(L=>({...L,query:d})),label:"Filter search queries",placeholder:"Contains query…"}),e.jsx(Ys,{value:F.page,onChange:d=>w(L=>({...L,page:d})),label:"Filter page URLs",placeholder:"Contains page URL…"})]}),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(hs).map(d=>e.jsx("th",{className:"text-right","aria-sort":Nt?.key===d?Nt.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),Os(L=>L?.key===d?L.dir==="desc"?{key:d,dir:"asc"}:null:{key:d,dir:"desc"})},children:[jl[d],Nt?.key===d?Nt.dir==="desc"?" ↓":" ↑":""]})},d))]})}),e.jsx("tbody",{children:js.map((d,L)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:d.date}),e.jsx("td",{className:"max-w-xs truncate text-strong",children:d.query}),e.jsx("td",{className:"max-w-xs text-secondary",children:e.jsx(Cn,{value:d.page})}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:d.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:d.impressions.toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[(Number.isFinite(d.ctr)?d.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:d.position.toFixed(1)})]},`${d.date}:${d.query}:${d.page}:${L}`))})]})}),e.jsx(Ps,{page:ie?Ye.page:Math.floor(Z/Bt)+1,pageSize:Bt,visibleRows:js.length,totalRows:ie?xe:void 0,hasNextPage:ie?void 0:ce,disabled:ve,itemLabel:ie?"matches":"rows",onPageChange:d=>{if(ie){Ye.setPage(d);return}const L=(d-1)*Bt;re(L),_s(L)}}),ie&&xe>=bn?e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Results are capped at ",bn.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(he,{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.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Index coverage"}),e.jsx(ze,{text:"Google's Indexing API is intended for eligible JobPosting and BroadcastEvent pages. Sitemap resubmission is the general-site bulk path."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[H&&H.notIndexed.length>0&&e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:At,onClick:()=>{Hi()},children:At?"Requesting…":`Request indexing (${H.notIndexed.length})`}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:lt,onClick:()=>{Oa(!0)},children:lt?"Loading…":"Reload saved coverage"})]})]}),H&&H.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const d=H.summary.indexed+H.summary.notIndexed,L=d>0?H.summary.indexed/d:0,W=d>0?H.summary.notIndexed/d:0,ae=54,$e=2*Math.PI*ae,qe=$e*(1-L),Ke=$e*W,ct=$e*L;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:ae,fill:"none",stroke:It.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:ae,fill:"none",stroke:gs.positiveDeep,strokeWidth:"14",strokeDasharray:$e,strokeDashoffset:qe,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),H.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:ae,fill:"none",stroke:It.textFaint,strokeWidth:"14",strokeDasharray:`${Ke} ${$e-Ke}`,strokeDashoffset:-ct,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:[(L*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:H.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:H.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:["Not indexed",(H.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-faint",children:["· ",(H.reasonGroups??[]).length," ",(H.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),H.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:H.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(d=>{const L=d==="indexed"?H.indexed.length:d==="notIndexed"?H.notIndexed.length:H.deindexed.length,W=d==="indexed"?"Indexed":d==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",role:"tab","aria-selected":Ze===d,className:`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${Ze===d?"border-accent text-heading":"border-transparent text-secondary hover:border-mono-600 hover:text-strong"}`,onClick:()=>{qs(d),Ht(null)},children:[W," (",L,")"]},d)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[Ze==="indexed"&&H.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:Re.map(d=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:d.url}),e.jsx("td",{className:"text-secondary",children:d.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:d.crawlTime?d.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:d.isMobileFriendly===!0?"Yes":d.isMobileFriendly===!1?"No":"—"})]},d.id))})]}),Ze==="notIndexed"&&!st&&(H.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:(H.reasonGroups??[]).map(d=>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:()=>Ht(d.reason),onKeyDown:L=>{(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),Ht(d.reason))},tabIndex:0,role:"button","aria-label":`View ${d.reason} pages`,children:[e.jsx("td",{className:"text-strong",children:d.reason}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:d.count})]},d.reason))})]}),Ze==="notIndexed"&&!st&&(H.reasonGroups??[]).length===0&&H.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:Wt.map(d=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:d.url}),e.jsx("td",{className:"text-secondary",children:d.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:d.coverageState??"Unknown"})]},d.id))})]}),Ze==="notIndexed"&&st&&(()=>{const d=(H.reasonGroups??[]).find(L=>L.reason===st);return d?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:()=>Ht(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:d.reason}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[d.count," affected page",d.count!==1?"s":""]})]}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:At,onClick:()=>{Fa(d.urls.map(L=>L.url))},children:At?"Requesting…":`Request indexing (${d.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:Fs.map(L=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:L.url}),e.jsx("td",{className:"text-secondary",children:L.crawlTime?L.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-strong transition-colors",disabled:At,onClick:()=>{Fa([L.url])},title:"Request indexing",children:"Index"})})]},L.id))})]})]}):null})(),Ze==="deindexed"&&H.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:xt.map((d,L)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:d.url}),e.jsx("td",{className:"text-secondary",children:d.previousState}),e.jsx("td",{className:"text-secondary",children:d.currentState}),e.jsx("td",{className:"text-secondary",children:d.transitionDate.split("T")[0]})]},`${d.url}-${L}`))})]}),(Ze==="indexed"&&H.indexed.length===0||Ze==="notIndexed"&&!st&&H.notIndexed.length===0||Ze==="deindexed"&&H.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),e.jsx(Ps,{page:ee,pageSize:Zt,visibleRows:Math.min(Zt,B.length-se),totalRows:B.length,onPageChange:ge,itemLabel:"URLs"})]}),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":Dt,onClick:()=>Es(d=>!d),children:[e.jsx("span",{children:"Coverage history"}),e.jsx("span",{children:Dt?"Hide snapshots":yt.length>0?`View ${yt.length} snapshots`:"View history"})]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["Current: ",H.summary.indexed.toLocaleString()," indexed, ",H.summary.notIndexed.toLocaleString()," not indexed.",ye&&e.jsxs(e.Fragment,{children:[" Since the last snapshot: ",ye.indexed>=0?"+":"",ye.indexed.toLocaleString()," indexed, ",ye.notIndexed>=0?"+":"",ye.notIndexed.toLocaleString()," not indexed."]})]}),Dt&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:yt.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:yt.map(d=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:d.date}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:d.indexed.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:d.notIndexed.toLocaleString()})]},d.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:lt?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),e.jsxs(he,{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.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Sitemap operations"}),e.jsx(ze,{text:"Submitting asks Google to refetch these sitemaps. Indexing is not guaranteed."})]})]}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:ke||!wt?.propertyId,onClick:()=>{Un()},children:ke?"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:me,onChange:d=>fe(d.target.value),onKeyDown:d=>d.key==="Enter"&&void Ns([me.trim()])}),e.jsx(A,{type:"button",size:"sm",disabled:!os||tt||!me.trim(),onClick:()=>{Ns([me.trim()])},children:tt?"Submitting…":"Submit sitemap to Google"})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:!os||tt||qn.length===0,onClick:()=>{Ns(qn)},children:tt?"Resubmitting…":zi}),e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:!os||tt||!ht?.length,onClick:()=>{Yi()},children:"Resubmit all files"}),We&&e.jsxs("span",{className:"text-xs text-muted",children:["Top level: ",We.indexes," index",We.indexes===1?"":"es",", ",We.files," file",We.files===1?"":"s"]}),E&&e.jsxs("span",{className:"text-xs text-secondary",children:["Submitting ",E.completed,"/",E.total]})]}),!os&&wt&&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(Va),children:"Reconnect"})]}),ht&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:ht.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Ys,{value:pt,onChange:d=>{Je(d),Et.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:Et.rows.flatMap(d=>{const L=dr(d),W=ur(d),ae=mr(d),$e=ot[d.path]??[],qe=Le.has(d.path),Ke=e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs text-strong",children:e.jsx(Cn,{value:d.path})}),e.jsx("td",{className:"text-secondary",children:d.isSitemapsIndex?e.jsx("button",{type:"button",className:"text-secondary hover:text-strong","aria-expanded":qe,"aria-label":`${qe?"Collapse":"Expand"} files in ${d.path}`,onClick:()=>{Wi(d.path)},children:Tt.has(d.path)?"Loading…":`${qe?"▾":"▸"} Index${ot[d.path]?` (${$e.length})`:""}`}):"Sitemap"}),e.jsx("td",{className:"text-secondary",children:ae}),e.jsx("td",{className:"text-secondary",children:d.lastSubmitted?d.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:d.lastDownloaded?d.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:L.toLocaleString()}),e.jsx("td",{className:"max-w-48 text-secondary",children:W||"—"}),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||tt,onClick:()=>{Ns([d.path])},children:d.lastSubmitted?"Resubmit to Google":"Submit to Google"}),wt?.sitemapUrl===d.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:kt,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{_a(d.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Fn.isPending,onClick:()=>{Ua(d.path)},children:"Inspect URLs"})]})})]},d.path),ct=d.isSitemapsIndex&&qe?$e.map(ne=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs pl-6 text-secondary",children:e.jsx(Cn,{value:ne.path})}),e.jsx("td",{className:"text-secondary",children:"File"}),e.jsx("td",{className:"text-secondary",children:mr(ne)}),e.jsx("td",{className:"text-secondary",children:ne.lastSubmitted?ne.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:ne.lastDownloaded?ne.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:dr(ne).toLocaleString()}),e.jsx("td",{className:"text-secondary",children:ur(ne)||"—"}),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||tt,onClick:()=>{Ns([ne.path])},children:"Resubmit"}),wt?.sitemapUrl===ne.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:kt,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{_a(ne.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Fn.isPending,onClick:()=>{Ua(ne.path)},children:"Inspect URLs"})]})})]},`${d.path}:${ne.path}`)):[];return[Ke,...ct]})})]}),e.jsx(Ps,{page:Et.page,pageSize:Bt,visibleRows:Et.rows.length,totalRows:Et.totalRows,onPageChange:Et.setPage,itemLabel:"sitemaps"})]}):e.jsx("p",{className:"text-sm text-muted",children:"No sitemaps found for this property."})})]}),e.jsxs(he,{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:d=>v(d.target.value),onKeyDown:d=>d.key==="Enter"&&void za()}),e.jsx(A,{type:"button",size:"sm",disabled:be||!wt?.propertyId||!g.trim(),onClick:Ie(za),children:be?"Inspecting…":"Inspect URL"})]}),T&&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:T.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:T.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:Qa(T.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:Ot(T.crawlTime)})]})]})]}),e.jsxs(he,{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(A,{type:"button",variant:"outline",size:"sm",disabled:R,onClick:()=>{mn(!0)},children:R?"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:Xe,onChange:d=>rt(d.target.value)}),e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:R,onClick:()=>{mn(!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(d=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:d.url}),e.jsx("td",{className:"text-neutral",children:d.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:d.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:d.coverageState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:Qa(d.isMobileFriendly??null)}),e.jsx("td",{className:"text-secondary",children:Ot(d.inspectedAt)})]},d.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No inspection history yet."})]}),e.jsxs(he,{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(d=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:d.url}),e.jsx("td",{className:"text-secondary",children:d.previousState??"Unknown"}),e.jsx("td",{className:"text-neutral",children:d.currentState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:Ot(d.transitionDate)})]},`${d.url}:${d.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No deindexed transitions recorded."})]})]}),wt&&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:()=>Ds(d=>!d),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 ${is?"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"})]})}),is&&e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(he,{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.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Pick the Search Console property"}),e.jsx(ze,{text:"The selected property is used for future syncs and URL inspections for this project."})]})]})}),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:O,disabled:Ve||m.length===0,onChange:d=>$(d.target.value),children:m.length===0?e.jsx("option",{value:"",children:Ve?"Loading properties…":"No properties available"}):m.map(d=>e.jsxs("option",{value:d.siteUrl,children:[d.siteUrl," · ",d.permissionLevel]},d.siteUrl))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:Ve,onClick:()=>{qa(wt,!0)},children:Ve?"Refreshing…":"Refresh properties"}),e.jsx(A,{type:"button",size:"sm",disabled:!O||He,onClick:Ie(Ji),children:He?"Saving…":"Save property"})]})]})]}),e.jsxs(he,{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:C,onChange:d=>J(d.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:z,onChange:d=>P(d.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(A,{type:"button",size:"sm",disabled:On.isPending||!wt.propertyId,onClick:Ie(Zi),children:On.isPending?"Queueing…":"Queue sync"}),!wt.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=rs(),[a,r]=l.useState(null),[i,o]=l.useState(null),[m,u]=l.useState(!1),h=_e(Na({client:V,path:{name:t}})),x=h.data?.find(q=>q.connectionType==="gbp"),c=!!x,y=a?{locationName:a}:void 0,N=_e({...Ml({client:V,path:{name:t}}),enabled:c}),f=_e({...Dl({client:V,path:{name:t},query:y}),enabled:c}),b=_e({...El({client:V,path:{name:t},query:y}),enabled:c}),p=_e({...ql({client:V,path:{name:t},query:y}),enabled:c}),T=_e({...Ol({client:V,path:{name:t},query:y}),enabled:c}),_=_e({...Fl({client:V,path:{name:t},query:y}),enabled:c}),O=_e({queryKey:["gbp-section-insights",t],queryFn:()=>_l(t),enabled:c});function $(){at(n,"gbp")}const g=Zs({...Gl(),onSuccess:q=>{Ul({id:q.runId,projectId:s,kind:en["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),we({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),v=l.useSyncExternalStore(Bl,Wa,Wa),C=Object.values(v.runs).some(q=>q.kind===en["gbp-sync"]&&q.projectId===s),J=g.isPending||C,z=Zs({...Kl(),onSuccess:()=>$()});if(l.useEffect(()=>{if(!a||!N.data)return;const q=N.data.locations.filter(ie=>ie.selected);(q.length<=1||!q.some(ie=>ie.locationName===a))&&r(null)},[a,N.data]),l.useEffect(()=>{if(!i||!N.data)return;(a?[a]:N.data.locations.filter(ie=>ie.selected).map(ie=>ie.locationName)).includes(i)||o(null)},[i,N.data,a]),h.isLoading)return null;if(!x){const q=[{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(he,{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:q.map((ie,Se)=>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:Se+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:ie.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:ie.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:ie.note})]})]},ie.title))})]})})}const P=f.data,k=N.data?.locations??[],U=k.filter(q=>q.selected),M=b.data?.keywords??[],te=p.data?.lodging??[],je=T.data?.placeActions??[],le=_.data?.places??[],Q=k.length>0?k[0].accountName:x.domain,de=a?k.find(q=>q.locationName===a)?.displayName??null:null,oe=a?k.filter(q=>q.locationName===a):U,G=new Set(oe.map(q=>q.locationName)),F=te.filter(q=>G.has(q.locationName)),w=je.filter(q=>G.has(q.locationName)),Z=le.filter(q=>G.has(q.locationName)),re=new Set(U.map(q=>q.locationName)),ce=a?M:M.filter(q=>re.has(q.locationName)),K=!a&&U.length>1,xe=(O.data??[]).filter(q=>!q.dismissed&&tu.has(q.type)&&(!de||q.query===de||q.query===a||q.title.startsWith(de)));return e.jsx("section",{className:"page-section-divider",children:e.jsxs(he,{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(ue,{tone:"positive",children:"Connected"}),!Y()&&e.jsx(et,{type:"button",variant:"outline",size:"sm",disabled:J,onClick:()=>g.mutate({client:V,path:{name:t},body:{}}),children:J?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-muted",children:[Q?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-secondary",children:Q})," · "]}):null,N.data?`${N.data.totalSelected} of ${N.data.totalDiscovered} locations tracked`:"Loading locations…"]}),U.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:q=>r(q.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"}),U.map(q=>e.jsx("option",{value:q.locationName,children:q.displayName},q.id))]})]}),U.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:[xe.length>0&&e.jsxs("div",{className:"mb-6 grid gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Needs attention"}),xe.map(q=>e.jsx("div",{className:["insight-card",pu(q.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:[q.title,q.recommendation?.reason&&e.jsx(ze,{text:q.recommendation.reason})]})},q.id))]}),P&&e.jsx(yu,{performance:P.performance,freshness:P.freshness,timeseries:P.timeseries}),P?.profileCompleteness&&e.jsx(nu,{summary:P.profileCompleteness}),oe.length>0&&e.jsx(au,{locations:oe,lodging:F,places:Z,placeActions:w,expandedLocation:i,onToggleExpanded:q=>{o(ie=>ie===q?null:q)}}),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"]})]}),ce.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"}),K&&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:ce.slice(0,25).map(q=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-neutral",children:q.keyword}),K&&e.jsx("td",{className:"text-muted",children:k.find(ie=>ie.locationName===q.locationName)?.displayName??q.locationName}),e.jsx("td",{className:"text-right font-mono text-strong",children:q.valueCount!==null?q.valueCount.toLocaleString():e.jsxs("span",{className:"text-muted",title:"Privacy floor — Google withheld the exact count",children:["<",q.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-faint",children:[q.periodStart,"–",q.periodEnd]})]},`${q.locationName}:${q.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:()=>u(q=>!q),"aria-expanded":m,children:[e.jsx("span",{"aria-hidden":"true",children:m?"▾":"▸"})," Manage locations (",k.length,")"]}),m&&e.jsx("div",{className:"mt-3",children:k.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"}),!Y()&&e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:k.map(q=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:q.displayName}),e.jsx("td",{className:"text-muted",children:q.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(ue,{tone:q.selected?"positive":"neutral",children:q.selected?"Tracked":"Not tracked"})}),!Y()&&e.jsx("td",{className:"text-right",children:e.jsx(et,{type:"button",variant:"outline",size:"sm",disabled:z.isPending,onClick:()=>z.mutate({client:V,path:{name:t,locationName:q.locationName},body:{selected:!q.selected}}),children:q.selected?"Untrack":"Track"})})]},q.id))})]})})]})]})})}function nu({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:Bs(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:Bs(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:Bs(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:Bs(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:Bs(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])),m=new Map(n.map(h=>[h.locationName,h])),u=new Map;for(const h of a){const x=u.get(h.locationName)??[];x.push(h),u.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:Y()?"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=m.get(h.locationName)??null,y=u.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(ue,{tone:h.selected?"positive":"neutral",children:h.selected?"Tracked":"Not tracked"}),h.openStatus&&h.openStatus!=="OPEN"&&e.jsx(ue,{tone:h.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:Ci(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(A,{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:ms(t.description)?"positive":"neutral",value:ms(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:ms(t.primaryPhone)?"positive":"neutral",value:ms(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:ms(t.websiteUri)?"positive":"neutral",value:ms(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(ue,{tone:n.tone,children:[n.label," ",n.value]},n.label))})}function lu({lodging:t}){return e.jsx(Sa,{...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(Sa,{...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(Sa,{...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 Sa({tone:t,label:s,detail:n}){return e.jsxs("div",{children:[e.jsx(ue,{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(Wn,{title:"Owner profile · Business Information",children:[e.jsx(gt,{label:"Primary category",value:t.primaryCategoryDisplayName??"Not returned"}),e.jsx(gt,{label:"Secondary categories",value:t.additionalCategories.length>0?t.additionalCategories.join(", "):"Not returned"}),e.jsx(gt,{label:"Description",value:ms(t.description)?t.description:"Not returned"}),e.jsx(gt,{label:"Hours",value:t.regularHours?"Returned by Google":"Not returned"}),e.jsx(gt,{label:"Service area",value:t.serviceArea?"Returned by Google":"Not returned"}),e.jsx(gt,{label:"Phone",value:t.primaryPhone??"Not returned"}),e.jsx(gt,{label:"Website",value:t.websiteUri??"Not returned"}),e.jsx(gt,{label:"Open status",value:Ci(t.openStatus)}),e.jsx(gt,{label:"Opening date",value:t.openingDate??"Not returned"})]}),e.jsx(Wn,{title:"Hotel data · Lodging API",children:s?e.jsxs(e.Fragment,{children:[e.jsx(gt,{label:"Last checked",value:hr(s.syncedAt)}),e.jsx(gt,{label:"Groups returned",value:String(s.populatedGroupCount)}),e.jsx(gt,{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(Wn,{title:"Public listing + CTAs",children:[n?e.jsxs(e.Fragment,{children:[e.jsx(gt,{label:"Places tier",value:n.tier}),e.jsx(gt,{label:"Last checked",value:hr(n.syncedAt)}),e.jsx(gt,{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 Wn({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 gt({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 Bs(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 ms(t){return typeof t=="string"&&t.trim().length>0}function Ci(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 hr(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 yu({performance:t,freshness:s,timeseries:n}){const a=t.totals,r=Vl.filter(f=>(a[f]??0)>0),i=zl.filter(f=>(a[f]??0)>0),o=Object.keys(a).filter(f=>(a[f]??0)>0&&Ql(f)==="other").sort((f,b)=>(a[b]??0)-(a[f]??0)),m=Object.keys(a).filter(f=>(a[f]??0)===0).sort(),u=n.map(f=>{const b={date:f.date};for(const[p,T]of Object.entries(f.metrics))b[p]=T;return b}),h=n.find(f=>f.pending)?.date,x=n.length>0?n[n.length-1].date:void 0,c=u.length>0,y=s.dataThroughDate?`Data through ${ps(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(xr,{data:u,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:[An(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(xr,{data:u,metrics:i,kind:"area",firstPending:h,lastDate:x})]}),m.length>0&&e.jsxs("p",{className:"text-xs text-faint",children:["Not active: ",m.map(f=>An(f)).join(", ")]})]})}function xr({data:t,metrics:s,kind:n,firstPending:a,lastDate:r}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(tn,{width:"100%",height:"100%",children:e.jsxs(sn,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(ci,{stroke:ii,vertical:!1}),e.jsx(nn,{dataKey:"date",tick:Ft,tickLine:!1,axisLine:{stroke:bs},tickFormatter:Tn,minTickGap:24}),e.jsx(an,{tick:Ft,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(rn,{...As,labelFormatter:ps,formatter:(i,o)=>[typeof i=="number"?i.toLocaleString():String(i??0),An(String(o??""))]}),e.jsx(oi,{wrapperStyle:{fontSize:11,color:It.text},formatter:i=>An(i)}),a&&r&&e.jsx(rd,{x1:a,x2:r,fill:It.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:It.textDim,fontSize:10}}),s.map((i,o)=>n==="line"?e.jsx(di,{type:"monotone",dataKey:i,stroke:mt[o%mt.length],strokeWidth:2,dot:!1,isAnimationActive:!1},i):e.jsx(Cs,{type:"monotone",dataKey:i,stackId:"reach",stroke:mt[o%mt.length],fill:mt[o%mt.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},i))]})})})}function ju(t){return li(as(String(t)))}function vu(t){return fs(as(String(t)))}function Yn({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(Yc,{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 yn=Bt;function ws(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function Xn(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===en["backlink-extract"]&&!Xr(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([]),[m,u]=l.useState(null),[h,x]=l.useState(null),[c,y]=l.useState(null),[N,f]=l.useState(Date.now()),[b,p]=l.useState(0),[T,_]=l.useState(!0),[O,$]=l.useState(!1),[g,v]=l.useState(null),C=l.useCallback(async()=>{_(!0),v(null);try{const[Q,de,oe,G,F]=await Promise.all([Hl().catch(()=>null),Wl(t,{excludeCrawlers:!0}).catch(()=>null),Yl(t,{limit:yn,offset:b,excludeCrawlers:!0}).catch(Z=>{if(Z instanceof Ls&&Z.code==="NOT_FOUND")return null;throw Z}),Xl(t).catch(()=>[]),Jl(t).catch(()=>[])]);u(Q),n(de),r(oe),o(G);const w=Su(F);x(w)}catch(Q){v(Q instanceof Error?Q.message:"Failed to load backlinks")}finally{_(!1)}},[t,b]);l.useEffect(()=>{C()},[C]),l.useEffect(()=>{if(!h)return;const Q=h.id;let de=!1;const oe=async()=>{try{const F=await ua(Q);if(de)return;Xr(F.status)?(x(null),y(F),await C()):x(w=>w?.id===F.id?{...w,...F}:w)}catch{}},G=window.setInterval(()=>{oe()},3e3);return()=>{de=!0,window.clearInterval(G)}},[h,C]),l.useEffect(()=>{if(!h)return;const Q=window.setInterval(()=>f(Date.now()),1e3);return()=>window.clearInterval(Q)},[h]),l.useEffect(()=>{if(!c||c.status==="failed")return;const Q=window.setTimeout(()=>y(null),1e4);return()=>window.clearTimeout(Q)},[c]);async function J(){$(!0),v(null);try{const Q=await eo(t);x(Q)}catch(Q){Q instanceof Ls&&Q.code==="MISSING_DEPENDENCY"?v("DuckDB is not installed. Visit the Backlinks admin page to install it."):v(Q instanceof Error?Q.message:"Failed to trigger extract")}finally{$(!1)}}const z=l.useMemo(()=>i.slice().sort((Q,de)=>Q.queriedAt.localeCompare(de.queriedAt)).map(Q=>({date:Q.queriedAt,linkingDomains:Q.totalLinkingDomains})),[i]),P=a?.rows??[],k=a?.total??0,U=s?.excludedLinkingDomains??0,M=Math.floor(b/yn)+1;return l.useEffect(()=>{b>0&&b>=k&&p(0)},[b,k]),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(he,{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(he,{className:"surface-card p-4 mb-4 border-info-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Hc,{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(ue,{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(he,{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(ai,{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:Zl(c.error)}):c.status!=="failed"?e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),te()]});function te(){return T?e.jsx(he,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading backlinks…"})}):je()}function je(){const Q=s!==null&&s.totalLinkingDomains>0,de=c?.status==="failed",oe=s!==null&&s.totalLinkingDomains===0&&!de,G=m?.status==="ready",F=m?.status==="failed",w=m&&(m.status==="downloading"||m.status==="querying"||m.status==="queued");return Q?le(e.jsxs(e.Fragment,{children:[!Y()&&e.jsxs(e.Fragment,{children:[e.jsxs(A,{type:"button",variant:"outline",size:"sm",disabled:O||h!==null,onClick:Ie(J),children:[e.jsx(ri,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":O?"Queuing…":"Re-run extract"]}),e.jsx(Yn,{label:"About re-running",children:"Re-queries the current release for this project without downloading it again."})]}),!Y()&&e.jsx(A,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:ws("/backlinks"),children:"Open admin"})})]})):e.jsx(he,{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(Wc,{className:"h-5 w-5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1",children:[!m&&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."}),!Y()&&e.jsx("div",{className:"mt-4",children:e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:ws("/backlinks"),children:"Set up backlinks"})})})]}),w&&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 (",m.status,m.phaseDetail?` — ${m.phaseDetail}`:"","). Backlinks will appear here once it finishes."]}),!Y()&&e.jsx("div",{className:"mt-4",children:e.jsx(A,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:ws("/backlinks"),children:"View sync status"})})})]}),F&&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:m.error??"The workspace release sync failed. Retry from the Backlinks admin page."}),!Y()&&e.jsx("div",{className:"mt-4",children:e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:ws("/backlinks"),children:"Go to Backlinks admin"})})})]}),G&&!w&&!oe&&!de&&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:m.release})," is ready. Run an extract for this project."]}),!Y()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(A,{type:"button",size:"sm",disabled:O||h!==null,onClick:Ie(J),children:[e.jsx(In,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":O?"Queuing…":"Run extract"]}),e.jsx(Yn,{label:"About extraction",children:"Queries the current release for this project without downloading it again."})]})]}),de&&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."}),!Y()&&e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:ws("/backlinks"),children:"Go to Backlinks admin"})})})]}),oe&&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."]}),!Y()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:ws("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(A,{type:"button",variant:"outline",size:"sm",disabled:O||h!==null,onClick:Ie(J),children:[e.jsx(In,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":O?"Queuing…":"Re-run extract"]}),e.jsxs(Yn,{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 le(Q){if(!s)return null;const de="Linking hosts",oe="linking hosts",G="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:Xn(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 ",oe]}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:Xn(s.totalHosts)})}),e.jsxs("p",{className:"metric-card-sub",children:["aggregate ",oe," across referring domains"]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsx("p",{className:"metric-card-eyebrow",children:"Top-10 concentration"}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:Nu(s.top10HostsShare)})}),e.jsxs("p",{className:"metric-card-sub",children:["share of ",oe," from the 10 largest linking domains"]})]})]}),e.jsxs("p",{className:"text-xs text-muted mt-2",children:[e.jsx("span",{className:"text-secondary",children:"Common Crawl"})," · ",G," ",e.jsx("code",{className:"text-secondary",children:s.release})," · queried ",wu(s.queriedAt),U>0&&e.jsxs(e.Fragment,{children:[" · ",U," excluded domain",U===1?"":"s"]})]}),z.length>=2&&e.jsxs(he,{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(tn,{width:"100%",height:"100%",children:e.jsxs(sn,{data:z,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:mt[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:mt[0],stopOpacity:0})]})}),e.jsx(nn,{dataKey:"date",tick:Ft,stroke:bs,tickFormatter:ju}),e.jsx(an,{tick:Ft,stroke:bs,allowDecimals:!1}),e.jsx(rn,{contentStyle:As.contentStyle,labelStyle:As.labelStyle,itemStyle:As.itemStyle,labelFormatter:vu}),e.jsx(Cs,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:mt[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(he,{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:de})]})}),e.jsxs("tbody",{children:[P.map(F=>e.jsxs("tr",{className:"border-b border-mono-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-strong",children:F.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-secondary tabular-nums",children:Xn(F.numHosts)})]},F.linkingDomain)),P.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-muted",colSpan:2,children:U>0&&k===0?`Every referring domain in this ${G} was a crawler/proxy host (${U} hidden).`:`No referring domains in this ${G}.`})})]})]})}),e.jsx(Ps,{page:M,pageSize:yn,visibleRows:P.length,totalRows:k,onPageChange:F=>p((F-1)*yn)})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:Q})]})}}function Pu({projectName:t}){const s=_e({...to({client:V,path:{name:t}}),staleTime:Jr}),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:wa(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(Tu,{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(jn,{label:"Cited + mentioned",value:`${n} / ${s}`,helper:"In sources AND named in answer",tone:n>0?"positive":"neutral"}),e.jsx(jn,{label:"Cited only",value:`${a} / ${s}`,helper:"In sources, not named in answer",tone:a>0?"positive-dim":"neutral"}),e.jsx(jn,{label:"Mentioned only",value:`${r} / ${s}`,helper:"Named in answer, no source link",tone:r>0?"caution":"neutral"}),e.jsx(jn,{label:"Invisible",value:`${i} / ${s}`,helper:"No engine cites or mentions",tone:i>0?"negative":"neutral"})]})}function jn({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(Xc,{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(ks,{active:!0,tone:"cited"}),e.jsx("span",{children:"cited (in sources)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ks,{active:!0,tone:"mentioned"}),e.jsx("span",{children:"mentioned (in answer)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ks,{active:!1,tone:"cited"}),e.jsx(ks,{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(ks,{active:t.cited,tone:"cited"}),e.jsx(ks,{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 ks({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 Tu({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 cn="__cited__",dn="__mentioned__",$t="__mentionShare__";function ki(t){const s=t,{dataStartDate:n,dataEndDate:a}=s;return typeof n!="string"||typeof a!="string"?null:{start:as(n),end:as(a),sweepCount:s.sweepCount??1}}function Dn(t){const s=ki(t);if(!s)return"Sweep date unavailable";const n=fs(s.start),a=fs(s.end);return n===a?n:`${n} – ${a} · ${s.sweepCount} sweeps combined`}function Mu(t){const s=ki(t);return s?li(s.start):""}function Ms(t){return t.trim().toLowerCase()}function pa(t){return Math.round(t*1e3)/10}function ga(t){return t.byProvider??{}}function Du(t,s,n){const a=t.buckets.length>0,r=t.buckets.length===1;if(n==="overall"){const u=s==="cited"?cn:dn,h=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(c=>({date:c.startDate,[u]:pa(c[h])})),series:[u],hasData:a,singleBucket:r}}const i=s==="mentioned"?"mentionRate":"citationRate",o=[...new Set(t.buckets.flatMap(u=>Object.keys(ga(u))))].sort();return{rows:t.buckets.map(u=>{const h={date:u.startDate},x=ga(u);for(const c of o){const y=x[c];h[c]=y?pa(y[i]):null}return h}),series:o,hasData:a,singleBucket:r}}function Pi(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 pr(t,s){const n=Ms(s);return Object.entries(t).find(([a])=>Ms(a)===n)?.[1]}function Kt(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(!pr(ga(a),s))continue;const r=Pi(a);return r?pr(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 Ku(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 zu(t){const s=t.buckets.map(a=>{const r=a.mentionShare;return{date:a.startDate,[$t]:r?.rate==null?null:pa(r.rate)}}),n=s.map(a=>a[$t]).filter(a=>typeof a=="number"&&Number.isFinite(a));return{rows:s,series:[$t],hasData:n.length>0,singleBucket:n.length===1}}function Qu(t,s,n){return s==="mentionShare"?zu(t):Du(t,s,n)}function gr(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 fr(t){const[,s,n]=t.slice(0,10).split("-");return!s||!n?t:`${s}/${n}`}function br(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=>`${br(n.delta)} on ${fr(n.date)}`).join(", ")}`;const s=[...t].sort((n,a)=>a.date.localeCompare(n.date))[0];return`Query set changed ${t.length} times (latest ${br(s.delta)} on ${fr(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"}],Xu=[{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."}],Ca=mt[2],Ju="var(--chart-tooltip-bg)",Zu={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",local:"Local"};function zt(t){const s=Ms(t);return Zu[s]??t.charAt(0).toUpperCase()+t.slice(1)}function ss(t){return Math.round(t*10)/10}function em(t){return t===cn||t===dn||t===$t}function Ai(t){return t===cn?"Cited":t===dn?"Mentioned":t===$t?"Mention share":zt(t)}function zs(t,s){return t===cn?gs.positive:t===dn?mt[1]:t===$t?Ca:td(Ms(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(`
1
+ import{j as e,r as l,L as _t,n as rs,u as _e,o as Zs,B as zr,C as tl,h as sl,k as nl,D as al}from"./vendor-tanstack-Dock0eH1.js";import{T as ue,t as rl,a as il,u as Qr,C as ll,P as Is,B as A,h as ol,b as cl,c as dl,d as he,i as Y,e as at,f as Ie,I as ze,g as Us,j as ul,k as V,l as ml,m as hl,n as xl,o as pl,p as Hr,q as gl,r as fl,S as hs,s as bl,v as yl,w as us,x as Ot,y as jl,z as Qa,A as Wr,G as ut,D as Na,E as vl,F as Nl,H as wl,J as Sl,K as Ha,L as we,M as Yr,N as Cl,O as Bn,Q as kl,R as Pl,U as Al,V as Rl,W as $l,X as Il,Y as Ll,Z as Tl,_ as Ml,$ as Dl,a0 as El,a1 as ql,a2 as Ol,a3 as Fl,a4 as _l,a5 as Ul,a6 as en,a7 as Gl,a8 as Bl,a9 as Wa,aa as Kl,ab as et,ac as Vl,ad as zl,ae as Ql,af as An,ag as Hl,ah as Wl,ai as Yl,aj as Ls,ak as Xl,al as Jl,am as Zl,an as Xr,ao as ua,ap as eo,aq as Jr,ar as to,as as wa,at as so,au as no,av as ao,aw as Zr,ax as ro,ay as io,az as lo,aA as Ws,aB as xs,aC as oo,aD as co,aE as uo,aF as mo,aG as ei,aH as ho,aI as xo,aJ as po,aK as go,aL as fo,aM as Qe,aN as bo,aO as yo,aP as jo,aQ as vo,aR as No,aS as wo,aT as So,aU as Co,aV as ko,aW as Po,aX as Ao,aY as Ro,aZ as $o,a_ as Io,a$ as Lo,b0 as To,b1 as Mo,b2 as Do,b3 as Eo,b4 as qo,b5 as Oo,b6 as Fo,b7 as _o,b8 as Uo,b9 as Go,ba as Bo,bb as Ko,bc as Vo,bd as zo,be as Qo,bf as Ho,bg as Wo,bh as Yo,bi as Xo,bj as Jo,bk as Zo,bl as ec,bm as tc,bn as Kn,bo as sc,bp as nc,bq as Ya,br as ac,bs as rc,bt as ic,bu as lc,bv as oc,bw as cc,bx as dc,by as uc,bz as mc,bA as hc,bB as xc,bC as pc,bD as gc,bE as ti,bF as fc,bG as bc,bH as yc,bI as jc,bJ as vc,bK as Nc,bL as wc,bM as Xa,bN as Sc,bO as Vn,bP as Cc,bQ as kc,bR as Pc,bS as Ac,bT as Rc,bU as $c,bV as Ic,bW as Lc,bX as si,bY as ni,bZ as Tc,b_ as Mc,b$ as Dc,c0 as Ec,c1 as qc,c2 as pn,c3 as Oc,c4 as Fc,c5 as _c,c6 as Ja,c7 as Uc}from"./index-DyjfMyum.js";import{R as Gc}from"./RunRow-C9hp5yEp.js";import{u as Rn,D as Ys,a as Ps,b as Bc,M as Cn,c as Bt,S as Kc}from"./SiteHealthSection-ZlYR3JtG.js";import{e as Vc,q as $n,U as zc,r as Qc,L as Hc,s as ai,i as Wc,P as In,D as ri,t as Yc,u as Xc,E as Jc,C as Ln,v as Zc}from"./vendor-lucide-nYKv-BB7.js";import{f as Tn,C as bs,a as Ft,b as ps,c as As,d as It,e as mt,g as gs,M as ed,h as ii,i as li,o as as,j as fs,p as td}from"./ChartPrimitives-BoYe2M-i.js";import{u as sd,t as nd,e as ad,a as Za}from"./extract-error-message-Dd2su-BK.js";import{R as tn,C as sn,X as nn,Y as an,T as rn,L as oi,A as Cs,a as ci,b as rd,d as di,e as id}from"./vendor-recharts-D8rt5lKn.js";import{A as ld}from"./AuditHistoryPanel-BpIn6E7p.js";import{a as od,b as cd}from"./v2-overview-adapter-COMP5UGt.js";import"./vendor-radix-4UOaVWza.js";import"./vendor-markdown-Bn7fRwrx.js";import"./vendor-yaml-GWJz5H2G.js";function kn(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 dd(t,s,n=800){const a=[];if(!/^\d{4}-\d{2}-\d{2}$/.test(t)||!/^\d{4}-\d{2}-\d{2}$/.test(s))return a;for(let r=t;r<=s&&(a.push(r),!(a.length>=n));r=ud(r,1));return a}function ud(t,s){if(!Number.isFinite(s))return t;const n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t);if(!n?.[1]||!n[2]||!n[3])return t;const a=new Date(Date.UTC(Number(n[1]),Number(n[2])-1,Number(n[3])+Math.trunc(s)));if(Number.isNaN(a.getTime()))return t;const r=a.getUTCFullYear(),i=String(a.getUTCMonth()+1).padStart(2,"0"),o=String(a.getUTCDate()).padStart(2,"0");return`${r}-${i}-${o}`}function ui(t,s){if(!Number.isFinite(t)||!Number.isFinite(s)||s<=0)return null;const n=(t-s)/s;return Number.isFinite(n)?n:null}function md(t,s){const n=ui(t,s);return n===null?null:Math.round(n*100)}function zn(t,s,n="vs prior 7 days"){return t.deltaPct===null?t.prior===0?"First baseline week":"":t.deltaPct>0?`Up ${t.deltaPct}% ${n} (${kn(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${kn(t.prior)} ${s})`:`Flat ${n} (${kn(t.prior)} ${s})`}const mi=30;function er(t){return Math.round(t*10)/10}function hd(t){return t.prior>=mi&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% vs prior`:`${t.deltaAbs>0?"+":""}${er(t.deltaAbs)} vs ${er(t.prior)}`}function xd(t,s,n){return t.prior>=mi&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% ${n}`:`${t.deltaAbs>0?"+":""}${kn(Math.round(t.deltaAbs))} ${s} ${n}`}const pd=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function hi(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function xi(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 pi(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(hi).map(xi).filter(Boolean)):new Set}function gi(t,s){const n=hi(t).map(xi).filter(Boolean).filter(a=>!pd.has(a)).filter(a=>!s.has(a));return[...new Set(n)].sort().join(" ")}function gd(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function fd(t,s){const n=pi(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=gi(gd(i),n);!o||a.has(o)||(a.add(o),r.push(i))}return r}function bd(t){const s=pi(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const a=new Set;return n.filter(r=>{const i=gi(r.query,s);return!i||a.has(i)?!1:(a.add(i),!0)})}const fi={queryClass:"all"},yd=["all","non-brand","branded"];function jd(t){return typeof t=="string"&&yd.includes(t)}function vd(t){const s=jd(t.class)?t.class:fi.queryClass,n=t.scope;if(typeof n!="string"||n==="all"||n.length===0)return{scope:"all",queryClass:s};const a=n.startsWith("group:")?n.slice(6):"";return a?{scope:"group",groupKey:a,queryClass:s}:{scope:"all",queryClass:s}}function Nd(t,s){return s===null||t===null?!1:t!==s}function wd(t){return{scope:t.scope==="group"&&t.groupKey?`group:${t.groupKey}`:void 0,class:t.queryClass===fi.queryClass?void 0:t.queryClass}}function ma({state:t,label:s}){return e.jsx(ue,{tone:il(t),children:s??rl(t)})}function tr({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"}),m=new Date(n[i].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),u=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. ${u}`,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:[m," ",e.jsx("span",{className:"text-faint",children:"latest"})]})]})}function ha(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 Sd=320;function Cd(t){return[t.phrase,t.location??"",...t.rawItems.map(s=>s.provider)].join(" ")}function sr(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 nr(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 ar(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 m=t.length-1;m>=0&&t[m].citationState===r;m--)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 kd(t,s){return t.map(n=>bi(n,s))}function bi(t,s){return s==="citations"?t:{...t,citationState:sr(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:sr(n,s)}))}}function rr(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",m=i==="cited"||i==="emerging";return r==="lost"||i!==null&&m&&!o?{key:s,label:`Lost ${n}`,tone:"negative"}:r==="emerging"||i!==null&&!m&&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 Pd(t){const s=ha(kd(t,"mentions")),n=ha(t);return[rr(s,"mentions"),rr(n,"citations")]}function Ad({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 ir({items:t}){return e.jsx("div",{className:"mt-1 flex flex-wrap gap-1","aria-label":"Latest run mention and citation signals",children:Pd(t).map(s=>e.jsx(Ad,{signal:s},s.key))})}function Rd({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:a}=Qr(),[r,i]=l.useState(new Set),[o,m]=l.useState("mentions"),[u,h]=l.useState(n),x=l.useMemo(()=>{const _=new Map;for(const O of t){const $=O.query,g=s?O.location??null:null,v=s?JSON.stringify([$,g]):$,C=_.get(v)??{key:v,phrase:$,location:g,items:[],rawItems:[]};C.items.push(bi(O,o)),C.rawItems.push(O),_.set(v,C)}return[..._.values()]},[t,o,s]),c=Rn({rows:x,getSearchText:Cd}),y=c.rows.map(_=>_.key),N=y.length>0&&y.every(_=>r.has(_)),f=_=>{i(O=>{const $=new Set(O);return $.has(_)?$.delete(_):$.add(_),$})},b=o==="mentions"?"mentioned":"cited",p=o==="mentions"?"Mention History":"Citation History",T=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:()=>m("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:()=>m("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(_=>{const O=new Set(_);for(const $ of y)N?O.delete($):O.add($);return O})},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":u==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${u==="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":u==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${u==="detailed"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>h("detailed"),children:"Detailed"})]})]})]})]}),x.length>0?e.jsx(Ys,{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:_,phrase:O,location:$,items:g,rawItems:v})=>{const C=r.has(_),J=g.map(M=>M.citationState),z=J.includes("cited")?"cited":J.includes("emerging")?"emerging":J.includes("lost")?"lost":J.every(M=>M==="pending")?"pending":"not-cited",P=ha(g),k=g.filter(M=>M.citationState===ll.cited||M.citationState==="emerging").length,U=ar(P,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(_),onKeyDown:M=>{(M.key==="Enter"||M.key===" ")&&(M.preventDefault(),f(_))},tabIndex:0,role:"button","aria-expanded":C,children:[e.jsx("td",{children:e.jsx(Vc,{size:14,className:`transition-transform duration-150 text-muted ${C?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-heading",children:O}),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(M=>e.jsx(Is,{provider:M.provider},M.id))})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ma,{state:z,label:nr(z,o)}),e.jsxs("span",{className:"text-[11px] text-muted",title:`${k} of ${g.length} engines ${T}`,children:[k,"/",g.length]})]})}),e.jsx("td",{children:e.jsx(tr,{history:P})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:U}),e.jsx(ir,{items:v})]}),e.jsx("td",{})]}),C&&g.map((M,te)=>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:M.provider})}),e.jsx("td",{children:e.jsx(ma,{state:M.citationState,label:nr(M.citationState,o)})}),e.jsx("td",{children:e.jsx(tr,{history:M.runHistory})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:ar(M.runHistory,o)}),e.jsx(ir,{items:[v[te]??M]})]}),e.jsx("td",{children:e.jsx(A,{variant:"ghost",size:"sm",type:"button",onClick:je=>{je.stopPropagation(),a(M.id)},children:"View"})})]}),u==="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(Ld,{item:M,onViewFull:()=>a(M.id)})})]})]},M.id))]},_)})})]})}),c.totalRows===0&&c.hasQuery?e.jsx("p",{className:"supporting-copy mt-3",children:"No tracked queries match this filter."}):null,e.jsx(Ps,{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 $d(t){const s=(t.matchedTerms??[]).filter(r=>r.trim().length>2),n=[...t.competitorDomains.flatMap(r=>{const i=cl(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 Id(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 Ld({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}=Id(t.answerSnippet,Sd),i=$d(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:ol(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 Td({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 m=a!=null&&a.toLowerCase()===o.domain.toLowerCase(),u=[r?"cursor-pointer hover:bg-mono-800/30 transition-colors":"",m?"bg-negative-950/20":""].filter(Boolean).join(" ");return e.jsxs("tr",{className:u,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(ue,{tone:dl(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 gn({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 Md=6,Ts="__other__",Rs="_socialTotal";function Dd(t,s=Md){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),m=new Map;for(const x of t){let c=m.get(x.date);c||(c={date:x.date,[Rs]:0},m.set(x.date,c));const y=i.has(x.source)?x.source:Ts;c[y]=(c[y]??0)+x.sessions,c[Rs]=(c[Rs]??0)+x.sessions}const u=[...m.values()].sort((x,c)=>String(x.date).localeCompare(String(c.date))),h=r.map(([x])=>x);return o>0&&h.push(Ts),{data:u,sources:h,otherCount:o}}function $s(t){return t.replace(/\+/g," ")}function yi(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const lr="_totalSessions",or="_organicSessions";function Ed(t,s){const n=new Map;for(const o of s)n.set(o.date,{[lr]:o.sessions,[or]:o.organicSessions});for(const o of t.days){let m=n.get(o.date);m||(m={[lr]:0,[or]:0},n.set(o.date,m));for(const u of o.bySource)m[u.source]=(m[u.source]??0)+u.sessions}const a=[...n.entries()].sort(([o],[m])=>o.localeCompare(m)).map(([o,m])=>({date:o,...m})),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 qd=["7d","30d","90d","all"],ts=mt,xa=It.textDim,ji=It.textFaint,Gs=25;function Od(t){return Bc(t.landingPage)}const Fd=25,Qn={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0};function fn(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function vi(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 _d({projectName:t}){const{data:s,isLoading:n,isError:a}=sd(t);if(n)return e.jsx(he,{className:"p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading server activity…"})});if(a)return e.jsx(he,{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."," ",!Y()&&e.jsx(_t,{to:"/traffic",className:"text-link hover:underline",children:"Manage sources →"})]})]})}),r.length===0?e.jsx(he,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-secondary",children:["No server traffic source connected yet."," ",!Y()&&e.jsxs(e.Fragment,{children:[e.jsx(_t,{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(he,{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(ue,{tone:nd(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?vi(i.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:Y()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(_t,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:i.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},i.id))})]})})]})}function Ud({projectName:t}){return e.jsxs("div",{className:"space-y-10",children:[e.jsx(_d,{projectName:t}),e.jsx(Gd,{projectName:t})]})}function Gd({projectName:t}){const s=rs(),[n,a]=l.useState(null),[r,i]=l.useState(null),[o,m]=l.useState(!0),[u,h]=l.useState(!1),[x,c]=l.useState(!1),[y,N]=l.useState(null),[f,b]=l.useState(null),[p,T]=l.useState("sessions"),[_,O]=l.useState("desc"),[$,g]=l.useState("sessions"),[v,C]=l.useState("desc"),[J,z]=l.useState("sessions"),[P,k]=l.useState("desc"),[U,M]=l.useState("sessions"),[te,je]=l.useState("desc"),[le,Q]=l.useState(Qn),[de,oe]=l.useState([]),[G,F]=l.useState([]),[w,Z]=l.useState(!1),[re,ce]=l.useState("30d");async function K(E){m(!0),N(null);try{const Ne=await s.fetchQuery({...ul({client:V,path:{name:t}}),staleTime:Us});if(E.current)return;if(a(Ne),!Ne.connected){i(null),Q(Qn),oe([]),F([]),m(!1);return}const me=re==="all"?void 0:re,[fe,kt,Mt,tt]=await Promise.all([s.fetchQuery({...ml({client:V,path:{name:t},query:me?{window:me}:void 0}),staleTime:Us}).then(Pt=>Pt),s.fetchQuery({...hl({client:V,path:{name:t},query:me?{window:me}:void 0}),staleTime:Us}).catch(()=>Qn),s.fetchQuery({...xl({client:V,path:{name:t},query:me?{window:me}:void 0}),staleTime:Us}).catch(()=>[]),s.fetchQuery({...pl({client:V,path:{name:t},query:me?{window:me}:void 0}),staleTime:Us}).catch(()=>[])]);if(E.current)return;i(fe),Q(kt),oe(Mt),F(tt),m(!1)}catch(Ne){if(E.current)return;N(Ne instanceof Error?Ne.message:"Failed to load GA4 data"),m(!1)}}l.useEffect(()=>{const E={current:!1};return K(E),()=>{E.current=!0}},[t,re,s]);async function xe(){h(!0),N(null),b(null);try{const E=await Hr(t);b(`Synced ${E.rowCount.toLocaleString()} page rows, ${E.aiReferralCount.toLocaleString()} AI and ${E.socialReferralCount.toLocaleString()} social referral rows (${E.days} days)`),await at(s,"ga"),await K({current:!1})}catch(E){N(E instanceof Error?E.message:"Sync failed")}finally{h(!1)}}async function q(){c(!0),N(null),b(null);try{await gl(t),await at(s,"ga"),a({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),i(null),b("GA4 disconnected")}catch(E){N(E instanceof Error?E.message:"Disconnect failed")}finally{c(!1)}}function ie(E){p===E?O(Ne=>Ne==="desc"?"asc":"desc"):(T(E),O("desc"))}function Se(E){$===E?C(Ne=>Ne==="desc"?"asc":"desc"):(g(E),C("desc"))}function Xe(E){J===E?k(Ne=>Ne==="desc"?"asc":"desc"):(z(E),k("desc"))}const rt=l.useMemo(()=>r?.topPages?[...r.topPages].sort((E,Ne)=>{const me=E[p],fe=Ne[p];return typeof me=="string"&&typeof fe=="string"?_==="asc"?me.localeCompare(fe):fe.localeCompare(me):_==="asc"?me-fe:fe-me}):[],[r?.topPages,p,_]),it=l.useMemo(()=>r?.aiReferrals?[...r.aiReferrals].sort((E,Ne)=>{const me=E[$],fe=Ne[$];return typeof me=="string"&&typeof fe=="string"?v==="asc"?me.localeCompare(fe):fe.localeCompare(me):v==="asc"?me-fe:fe-me}):[],[r?.aiReferrals,$,v]),Ge=l.useMemo(()=>r?.aiReferralLandingPages?[...r.aiReferralLandingPages].sort((E,Ne)=>{const me=E[U],fe=Ne[U];return typeof me=="string"&&typeof fe=="string"?te==="asc"?me.localeCompare(fe):fe.localeCompare(me):te==="asc"?me-fe:fe-me}):[],[r?.aiReferralLandingPages,U,te]),X=Rn({rows:Ge,getSearchText:Od,pageSize:Fd}),Be=X.totalRows>0?`${X.totalRows.toLocaleString()} ${X.hasQuery?X.totalRows===1?"match":"matches":X.totalRows===1?"row":"rows"}`:X.hasQuery&&(r?.aiReferralLandingPages.length??0)>0?"0 matches":"No landing-page rows";function Ve(E){X.setPage(1),U===E?je(Ne=>Ne==="desc"?"asc":"desc"):(M(E),je("desc"))}const Pe=l.useMemo(()=>r?.socialReferrals?[...r.socialReferrals].sort((E,Ne)=>{const me=E[J],fe=Ne[J];return typeof me=="string"&&typeof fe=="string"?P==="asc"?me.localeCompare(fe):fe.localeCompare(me):P==="asc"?me-fe:fe-me}):[],[r?.socialReferrals,J,P]),{socialChartData:He,socialChartSources:Ce,socialOtherCount:ve}=l.useMemo(()=>{const E=Dd(G);return{socialChartData:E.data,socialChartSources:E.sources,socialOtherCount:E.otherCount}},[G]),{chartData:D,chartSources:R,dateRange:I}=l.useMemo(()=>{const E=Ed(le,de);return{chartData:E.data,chartSources:E.sources,dateRange:E.dateRange}},[le,de]);if(o&&!n)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!n?.connected)return Y()?e.jsx(he,{className:"p-5",children:e.jsx("div",{className:"text-sm text-secondary",children:"No Google Analytics 4 property connected yet."})}):e.jsx(Bd,{projectName:t,onConnected:()=>{(async()=>(await at(s,"ga"),await K({current:!1})))()}});const be=r?.organicSharePctDisplay??"0%",De=r?.channelBreakdown?.organic.sharePctDisplay??be,H=r?.channelBreakdown?.organic.sessions??r?.totalOrganicSessions??0,Ee=r?.aiSessionsDeduped??0,lt=r?.channelBreakdown?.ai.sessions??r?.aiSessionsBySession??0,bt=r?.channelBreakdown?.ai.sharePctDisplay??r?.aiSharePctBySessionDisplay??"0%",ke=r?.paidAiSessionsBySession??0,Oe=r?.paidAiSharePctBySessionDisplay??"0%",ht=r?new Set(r.aiReferrals.map(E=>E.source.toLowerCase())).size:0,Ue=it[0]??null,We=r?.totalDirectSessions??0,Ae=r?.directSharePctDisplay??"0%",jt=r?.channelBreakdown?.direct.sessions??We,Ct=r?.channelBreakdown?.direct.sharePctDisplay??Ae,Le=r?.channelBreakdown?.other.sessions??r?.otherSessions??0,Te=r?.channelBreakdown?.other.sharePctDisplay??r?.otherSharePctDisplay??"0%",ot=r?.socialSessions??0,Fe=r?.socialSharePctDisplay??"0%",Tt=r?.channelBreakdown?.social.sessions??ot,vt=r?.channelBreakdown?.social.sharePctDisplay??Fe,pt=r?new Set(r.socialReferrals.map(E=>E.source.toLowerCase())).size:0,Je=Pe[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})]})]})]}),!Y()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(A,{variant:"outline",size:"sm",disabled:u,onClick:Ie(xe),children:[e.jsx($n,{className:`w-3.5 h-3.5 mr-1.5 ${u?"animate-spin":""}`}),u?"Syncing…":"Sync"]}),e.jsxs(A,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:x,onClick:Ie(q),children:[e.jsx(zc,{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:qd.map(E=>e.jsx("button",{type:"button","aria-pressed":re===E,className:`segmented-option ${re===E?"segmented-option-active":""}`,onClick:()=>ce(E),children:E==="all"?"All":E},E))})]}),r?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(Hn,{value:fn(r.totalSessions),label:"Total Sessions",subtitle:r.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(Hn,{value:fn(r.totalOrganicSessions),label:"Organic Sessions",subtitle:`${be} of total`,tone:"positive"}),e.jsx(Hn,{value:fn(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."}),!Y()&&e.jsxs(A,{variant:"outline",size:"sm",disabled:u,onClick:Ie(xe),children:[e.jsx($n,{className:`w-3.5 h-3.5 mr-1.5 ${u?"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."})]})]}),I&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(I.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(I.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),D.length>0&&e.jsxs(he,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:R.length>0?"AI vs. total sessions":"All sessions (baseline)"}),R.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),R.length===0&&e.jsx("p",{className:"text-xs text-muted",children:"No AI referrals detected yet"})]}),e.jsx("div",{className:"h-64",children:e.jsx(tn,{width:"100%",height:"100%",children:e.jsxs(sn,{data:D,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(nn,{dataKey:"date",tick:Ft,tickLine:!1,axisLine:{stroke:bs},tickFormatter:Tn}),e.jsx(an,{tick:Ft,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(rn,{...As,labelFormatter:ps,formatter:(E,Ne)=>{const me=typeof E=="number"?E.toLocaleString():String(E??0),fe=String(Ne??"");return fe==="_totalSessions"?[me,"Total Sessions"]:fe==="_organicSessions"?[me,"Organic Sessions"]:[me,fe]}}),e.jsx(oi,{wrapperStyle:{fontSize:11,color:It.text},formatter:E=>E==="_totalSessions"?"Total Sessions":E==="_organicSessions"?"Organic Sessions":E}),e.jsx(Cs,{type:"monotone",dataKey:"_totalSessions",stroke:It.textFaint,fill:It.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),R.map((E,Ne)=>e.jsx(Cs,{type:"monotone",dataKey:E,stackId:"ai",stroke:ts[Ne%ts.length],fill:ts[Ne%ts.length],fillOpacity:.4,strokeWidth:1.5},E))]})})})]}),e.jsxs(he,{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(Lt,{label:"Organic",value:De,hint:`${H.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(Lt,{label:"Social",value:vt,hint:`${Tt.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(Lt,{label:"Direct",value:Ct,hint:`${jt.toLocaleString()} sessions`,tone:"neutral",tooltip:"Sessions with no source — bookmarks, typed URLs, untagged email, in-app browsers, and AI-driven traffic whose referrer header was stripped. Known AI referrers are removed if GA4 classified them as Direct."}),e.jsx(Lt,{label:"Known AI referrers (lower bound)",value:bt,hint:ke>0?`${lt.toLocaleString()} sessions · ${ke.toLocaleString()} paid`:`${lt.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(Lt,{label:"Other channels",value:Te,hint:`${Le.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."})]}),Ue&&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:Ue.source})," via ",Ue.medium,", accounting for ",Ue.sessions.toLocaleString()," sessions.",ke>0&&e.jsxs("span",{children:[" Paid AI: ",ke.toLocaleString()," sessions (",Oe,")."]})]})]}),e.jsxs(he,{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?`${ht} 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(St,{label:"Source",sortKey:"source",current:$,dir:v,onSort:Se,align:"left"}),e.jsx(St,{label:"Medium",sortKey:"medium",current:$,dir:v,onSort:Se,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(St,{label:"Sessions",sortKey:"sessions",current:$,dir:v,onSort:Se,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:it.map(E=>e.jsx(Vd,{referral:E,totalSessions:Ee},`${E.source}:${E.medium}:${E.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(he,{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(Ys,{value:X.query,onChange:X.setQuery,label:"Filter landing page URLs or query parameters",placeholder:"Filter URL or query parameters",className:"mb-4 max-w-md"}),X.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(St,{label:"Landing Page",sortKey:"landingPage",current:U,dir:te,onSort:Ve,align:"left"}),e.jsx(St,{label:"Source",sortKey:"source",current:U,dir:te,onSort:Ve,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(St,{label:"Sessions",sortKey:"sessions",current:U,dir:te,onSort:Ve,align:"right"})]})}),e.jsx("tbody",{children:X.rows.map(E=>e.jsx(zd,{row:E},`${E.landingPage}:${E.source}:${E.medium}:${E.sourceDimension}`))})]})}),e.jsx(Ps,{page:X.page,pageSize:X.pageSize,visibleRows:X.rows.length,totalRows:X.totalRows,onPageChange:X.setPage,itemLabel:X.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:()=>X.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."})]})]}),He.length>0&&e.jsxs(he,{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"})]}),ve>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",Ce.length-1," sources · ",ve," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(tn,{width:"100%",height:"100%",children:e.jsxs(sn,{data:He,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(nn,{dataKey:"date",tick:Ft,tickLine:!1,axisLine:{stroke:bs},tickFormatter:Tn}),e.jsx(an,{tick:Ft,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(rn,{...As,labelFormatter:ps,formatter:(E,Ne)=>{const me=typeof E=="number"?E.toLocaleString():String(E??0),fe=String(Ne??"");if(fe===Rs)return[me,"Total Social"];if(fe===Ts){const kt=`Other (${ve} source${ve===1?"":"s"})`;return[me,kt]}return[me,$s(fe)]}}),e.jsx(Cs,{type:"monotone",dataKey:Rs,stroke:ji,fill:It.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),Ce.map((E,Ne)=>{const fe=E===Ts?xa:ts[Ne%ts.length];return e.jsx(Cs,{type:"monotone",dataKey:E,stackId:"social",stroke:fe,fill:fe,fillOpacity:.4,strokeWidth:1.5},E)})]})})}),e.jsx(Hd,{sources:Ce,otherCount:ve})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.5fr)]",children:[e.jsxs(he,{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(Lt,{label:"Social Sessions",value:fn(ot),hint:`${ot.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(Lt,{label:"Share of Traffic",value:Fe,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(Lt,{label:"Platforms",value:String(pt),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."})]}),Je&&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:`${Je.source} via ${Je.medium}`,children:yi($s(Je.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:Je.medium,children:["via ",$s(Je.medium)," · ",Je.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(Lt,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(Lt,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(Lt,{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(he,{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?Pe.length>Gs&&!w?`Top ${Gs} of ${Pe.length}`:`${Pe.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(St,{label:"Source",sortKey:"source",current:J,dir:P,onSort:Xe,align:"left"}),e.jsx(St,{label:"Medium",sortKey:"medium",current:J,dir:P,onSort:Xe,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(St,{label:"Sessions",sortKey:"sessions",current:J,dir:P,onSort:Xe,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(St,{label:"Users",sortKey:"users",current:J,dir:P,onSort:Xe,align:"right"})]})}),e.jsx("tbody",{children:(w?Pe:Pe.slice(0,Gs)).map(E=>e.jsx(Qd,{referral:E,totalSessions:ot},`${E.source}:${E.medium}:${E.channelGroup}`))})]})}),Pe.length>Gs&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>Z(E=>!E),className:"rounded-md border border-base px-3 py-1.5 text-xs text-secondary transition-colors hover:border-strong hover:text-strong",children:w?`Show top ${Gs}`:`Show all ${Pe.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(St,{label:"Landing Page",sortKey:"landingPage",current:p,dir:_,onSort:ie,align:"left"}),e.jsx(St,{label:"Sessions",sortKey:"sessions",current:p,dir:_,onSort:ie,align:"right"}),e.jsx(St,{label:"Organic",sortKey:"organicSessions",current:p,dir:_,onSort:ie,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"})]})}),e.jsx("tbody",{children:rt.map(E=>e.jsx(Kd,{page:E},E.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 ${vi(r.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:r?`${r.topPages.length} pages · ${r.aiReferrals.length} AI rows · ${r.socialReferrals.length} social rows`:""})]})]})}function Bd({projectName:t,onConnected:s}){const[n,a]=l.useState(""),[r,i]=l.useState(null),[o,m]=l.useState(null),[u,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 T=new FileReader;T.onload=()=>{const _=T.result;try{const O=JSON.parse(_);if(!O.client_email||!O.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)."),m(null);return}m(_)}catch{c("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),m(null)}},T.onerror=()=>{c("Failed to read file."),m(null)},T.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 fl(t,{propertyId:n.trim(),keyJson:o});try{await Hr(t)}catch{}s()}catch(b){c(b instanceof Error?b.message:"Failed to connect GA4")}finally{h(!1)}}return e.jsxs(he,{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(Qc,{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(A,{variant:"default",size:"sm",disabled:u||!n.trim()||!o,onClick:Ie(f),children:u?"Connecting & syncing…":"Connect GA4"})]})}function St({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 Ni={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function Hn({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 ${Ni[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Lt({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 ${Ni[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 wi={session:"Session",first_user:"First Visit",manual_utm:"UTM"},Si={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 Vd({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=wi[t.sourceDimension]??t.sourceDimension,r=Si[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 zd({row:t}){const s=wi[t.sourceDimension]??t.sourceDimension,n=Si[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(Cn,{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 Qd({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 Hd({sources:t,otherCount:s}){const n=[{key:Rs,color:ji,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const r=t[a];if(r===Ts)n.push({key:Ts,color:xa,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const i=$s(r);n.push({key:r,color:ts[a%ts.length]??xa,label:yi(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 Wd(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 Yd=["7d","30d","90d","all"],bn=500,cr=[{key:"clicks",label:"Clicks",color:mt[1],format:t=>t.toLocaleString()},{key:"impressions",label:"Impressions",color:mt[4],format:t=>t.toLocaleString()},{key:"ctr",label:"CTR",color:gs.caution,format:t=>`${(t*100).toFixed(1)}%`},{key:"position",label:"Avg position",color:mt[2],inverted:!0,format:t=>t.toFixed(1)}],Zt=25,Xd="canonry:google-oauth-complete",Jd=new Intl.NumberFormat(void 0,{maximumFractionDigits:1});function Zd(t,s,n){const{startIndex:a,endIndex:r}=t,i=a!==void 0&&r!==void 0&&Number.isInteger(a)&&Number.isInteger(r)&&a>=0&&r>=a?r-a+1:n;if(!Number.isFinite(t.start)||!Number.isFinite(t.end)||t.start<=0||t.end<0)return"— no percentage baseline";if(t.slope===0)return`→ 0% over ${i}d`;const o=ui(t.end,t.start);if(o===null)return"— no percentage baseline";const m=Math.abs(o*100),u=m<.1?"<0.1%":`${Jd.format(m)}%`;return`${(s?t.slope<0:t.slope>0)?"↑":"↓"} ${u} over ${i}d`}function dr(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function ur(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 mr(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=rs(),[a,r]=l.useState(!1),[i,o]=l.useState([]),[m,u]=l.useState([]),[h,x]=l.useState([]),[c,y]=l.useState(null),[N,f]=l.useState([]),[b,p]=l.useState([]),[T,_]=l.useState(null),[O,$]=l.useState(""),[g,v]=l.useState(""),[C,J]=l.useState("30"),[z,P]=l.useState(!1),[k,U]=l.useState("30d"),[M,te]=l.useState(["clicks","impressions"]),[je,le]=l.useState(!0),[Q,de]=l.useState(null),[oe,G]=l.useState(0),[F,w]=l.useState({startDate:"",endDate:"",query:"",page:""}),[Z,re]=l.useState(0),[ce,K]=l.useState(!1),[xe,q]=l.useState(0),[ie,Se]=l.useState(!1),[Xe,rt]=l.useState(""),[it,Ge]=l.useState(!0),[X,Be]=l.useState(!1),[Ve,Pe]=l.useState(!1),[He,Ce]=l.useState(!1),[ve,D]=l.useState(!1),[R,I]=l.useState(!1),[be,De]=l.useState(!1),[H,Ee]=l.useState(null),[lt,bt]=l.useState(!1),[ke,Oe]=l.useState(!1),[ht,Ue]=l.useState(null),[We,Ae]=l.useState(null),[jt,Ct]=l.useState([]),[Le,Te]=l.useState(new Set),[ot,Fe]=l.useState({}),[Tt,vt]=l.useState(new Set),[pt,Je]=l.useState(""),[E,Ne]=l.useState(null),[me,fe]=l.useState(""),[kt,Mt]=l.useState(!1),[tt,Pt]=l.useState(!1),[is,Ds]=l.useState(!1),[Dt,Es]=l.useState(!1),[Ze,qs]=l.useState("indexed"),[Nt,Os]=l.useState(null),Qt=!!(F.query.trim()||F.page.trim()||Nt),ys=Nt!==null,ls=l.useMemo(()=>{if(!Nt)return h;const{key:d,dir:L}=Nt;return[...h].sort((W,ae)=>{const $e=d===hs.CTR?Number.isFinite(W.ctr)?W.ctr:0:W[d],qe=d===hs.CTR?Number.isFinite(ae.ctr)?ae.ctr:0:ae[d];return L==="asc"?$e-qe:qe-$e})},[h,Nt]),Ye=Rn({rows:ls,pageSize:Bt}),js=ie?Ye.rows:ls,Et=Rn({rows:(ht??[]).filter(d=>d.path.toLowerCase().includes(pt.trim().toLowerCase())),pageSize:Bt}),[yt,vs]=l.useState([]),[st,Ht]=l.useState(null),[j,ge]=l.useState(1),ye=l.useMemo(()=>{if(yt.length<2)return null;const d=yt[yt.length-1],L=yt[yt.length-2];return{indexed:d.indexed-L.indexed,notIndexed:d.notIndexed-L.notIndexed}},[yt]);l.useEffect(()=>{ge(1)},[H,Ze,st]);const S=l.useMemo(()=>st?(H?.reasonGroups??[]).find(d=>d.reason===st):void 0,[H,st]),B=l.useMemo(()=>H?Ze==="indexed"?H.indexed:Ze==="deindexed"?H.deindexed:Ze==="notIndexed"?st?S?.urls??[]:(H.reasonGroups??[]).length===0?H.notIndexed:[]:[]:[],[H,Ze,st,S]),pe=Math.max(1,Math.ceil(B.length/Zt)),ee=Math.min(Math.max(1,j),pe),se=(ee-1)*Zt,Re=l.useMemo(()=>H?.indexed.slice(se,se+Zt)??[],[H,se]),Wt=l.useMemo(()=>H?.notIndexed.slice(se,se+Zt)??[],[H,se]),xt=l.useMemo(()=>H?.deindexed.slice(se,se+Zt)??[],[H,se]),Fs=l.useMemo(()=>(S?.urls??[]).slice(se,se+Zt),[S,se]),[At,Yt]=l.useState(!1),[Ma,Me]=l.useState(null),[Ut,un]=l.useState(null),[Da,Gt]=l.useState(null);function Vi(d,L){const W=ad(d),ae=Wd(W);ae?(un(ae),Me(null)):(un(null),Me(W.message||L))}const wt=i.find(d=>d.connectionType==="gsc"),os=(wt?.scopes??[]).includes("https://www.googleapis.com/auth/webmasters"),qn=jt.length>0?jt:(ht??[]).map(d=>d.path),Ea=qn.filter(d=>ht?.some(L=>L.path===d&&L.isSitemapsIndex)).length,zi=Ea===1?"Resubmit sitemap index":Ea>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",Qi=h.length>0||N.length>0||b.length>0,On=bl(),Fn=yl();async function qa(d,L=!1){if(!d){u([]),$("");return}Pe(!0);try{const{sites:W}=await n.fetchQuery({...Ll({client:V,path:{name:t}}),staleTime:L?0:ut});u(W),$(d.propertyId??W[0]?.siteUrl??""),un(null)}catch(W){u([]),Vi(W,"Failed to load Search Console properties")}finally{Pe(!1)}}async function _s(d){D(!0);const L=d??Z;try{const W=Qt?bn:Bt,ae=Qt?0:L,$e={limit:String(W)};F.startDate&&($e.startDate=F.startDate),F.endDate&&($e.endDate=F.endDate),F.query&&($e.query=F.query),F.page&&($e.page=F.page),ae>0&&($e.offset=String(ae)),k&&k!=="all"&&!F.startDate&&($e.window=k);const qe=await n.fetchQuery({...Nl({client:V,path:{name:t},query:$e}),staleTime:ut}),Ke=qe.rows;Qt?(K(!1),x(Ke),q(Ke.length),Se(!0)):(K(ae+Ke.length<qe.totalMatching),x(Ke),q(0),Se(!1))}catch(W){x([]),K(!1),q(0),Me(W instanceof Error?W.message:"Failed to load GSC performance data")}finally{D(!1)}}async function _n(){try{const d={};F.startDate&&(d.startDate=F.startDate),F.endDate&&(d.endDate=F.endDate),k&&k!=="all"&&!F.startDate&&(d.window=k);const L=await n.fetchQuery({...vl({client:V,path:{name:t},query:d}),staleTime:ut});y(L)}catch{y(null)}}async function mn(d=!1){I(!0);try{const L=Xe.trim()||void 0,W={limit:"20"};L&&(W.url=L);const[ae,$e]=await Promise.all([n.fetchQuery({...$l({client:V,path:{name:t},query:W}),staleTime:d?0:ut}),n.fetchQuery({...Il({client:V,path:{name:t}}),staleTime:d?0:ut})]);f(ae),p($e)}catch(L){f([]),p([]),Me(L instanceof Error?L.message:"Failed to load GSC inspection history")}finally{I(!1)}}async function Oa(d=!1){bt(!0);try{const[L,W]=await Promise.all([n.fetchQuery({...Yr({client:V,path:{name:t}}),staleTime:d?0:ut}),n.fetchQuery({...Cl({client:V,path:{name:t}}),staleTime:d?0:ut}).catch(()=>[])]);Ee(L),vs(W)}catch(L){Ee(null),vs([]),Me(L instanceof Error?L.message:"Failed to load coverage data")}finally{bt(!1)}}async function Fa(d){Yt(!0),Me(null);try{const L=await Ha(t,{urls:d}),{succeeded:W,failed:ae,total:$e}=L.summary;we({title:"Indexing requested",detail:ae===0?`${W} URL${W!==1?"s":""} submitted for indexing.`:`${W}/${$e} submitted successfully, ${ae} failed.`,tone:ae===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(L){Me(L instanceof Error?L.message:"Failed to request indexing")}finally{Yt(!1)}}async function Hi(){Yt(!0),Me(null);try{const d=await Ha(t,{urls:[],allUnindexed:!0}),{succeeded:L,failed:W,total:ae}=d.summary;we({title:"Indexing requested",detail:W===0?`${L} unindexed URL${L!==1?"s":""} submitted for indexing.`:`${L}/${ae} submitted successfully, ${W} failed.`,tone:W===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(d){Me(d instanceof Error?d.message:"Failed to request indexing")}finally{Yt(!1)}}async function Un(){Oe(!0),Me(null);try{const d=await Bn(t);n.setQueryData(kl({client:V,path:{name:t}}),d),Ue(d.sitemaps),Ae(d.summary),Ct(d.preferredSubmissionUrls),Te(new Set),Fe({}),d.sitemaps.length===0&&Gt("No sitemaps found in this GSC property. Submit one here to start Google processing it.")}catch(d){Me(d instanceof Error?d.message:"Failed to list sitemaps")}finally{Oe(!1)}}async function Wi(d){const L=Le.has(d);if(Te(W=>{const ae=new Set(W);return L?ae.delete(d):ae.add(d),ae}),!(L||ot[d])){vt(W=>new Set(W).add(d));try{const W=await Bn(t,d);Fe(ae=>({...ae,[d]:W.sitemaps}))}catch(W){Me(W instanceof Error?W.message:"Failed to load sitemap files")}finally{vt(W=>{const ae=new Set(W);return ae.delete(d),ae})}}}async function Ns(d){if(!os||d.length===0)return;const L=[...new Set(d)];Pt(!0),Me(null),Ne({completed:0,total:L.length});let W=0,ae=0,$e=0,qe=null;try{for(let ct=0;ct<L.length;ct+=50){const ne=L.slice(ct,ct+50);try{const dt=await Pl(t,ne);W+=dt.summary.accepted,ae+=dt.summary.failed,$e+=ne.length,Ne({completed:$e,total:L.length})}catch(dt){$e+=ne.length;const Xt=ne.length,hn=L.length-$e,xn=dt instanceof Error?dt.message:"The batch request failed",Jt=`${W} accepted, ${ae} failed, ${Xt} unconfirmed, ${hn} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;qe=`Sitemap submission stopped after a batch request failed. ${Jt} ${xn}`,Me(qe),we({title:"Sitemap resubmission partially completed",detail:Jt,tone:"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"});return}}const Ke=L.length;we({title:ae===0?"Sitemap submitted to Google":"Some sitemap submissions need attention",detail:ae===0?"Google accepted the sitemap submission/refetch request; indexing is not guaranteed.":`Google accepted ${W}/${Ke} sitemap submissions; ${ae} failed. Indexing is not guaranteed.`,tone:ae===0?"positive":"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"}),fe("")}catch(Ke){Me(Ke instanceof Error?Ke.message:"Failed to submit sitemap to Google")}finally{Pt(!1),Ne(null),await Un(),qe&&Me(qe)}}async function Yi(){Pt(!0);const d=ht??[];try{const L=d.filter(ae=>ae.isSitemapsIndex),W=[];for(let ae=0;ae<L.length;ae+=4)(await Promise.all(L.slice(ae,ae+4).map(async qe=>{const Ke=ot[qe.path];if(Ke)return Ke;const ct=await Bn(t,qe.path);return Fe(ne=>({...ne,[qe.path]:ct.sitemaps})),ct.sitemaps}))).forEach((qe,Ke)=>{W.push(...qe.length>0?qe.map(ct=>ct.path):[L[ae+Ke].path])});await Ns([...d.filter(ae=>!ae.isSitemapsIndex).map(ae=>ae.path),...W])}catch(L){Me(L instanceof Error?L.message:"Failed to load sitemap files"),Pt(!1)}}async function _a(d){Mt(!0),Me(null);try{await Al(t,"gsc",d),await at(n,"google"),o(L=>L.map(W=>W.connectionType==="gsc"?{...W,sitemapUrl:d}:W)),we({title:"Default sitemap updated",detail:d,tone:"positive",dedupeKey:`gsc:sitemap-default:${t}`,dedupeMode:"replace"})}catch(L){Me(L instanceof Error?L.message:"Failed to set the default sitemap")}finally{Mt(!1)}}async function Ua(d){try{await Fn.mutateAsync({projectName:t,projectLabel:t,opts:d?{sitemapUrl:d}:void 0})}catch{}}async function Ga(){Ge(!0),Me(null);try{const[d,L]=await Promise.all([Wr().catch(()=>null),n.fetchQuery({...Na({client:V,path:{name:t}}),staleTime:ut}).catch(()=>[])]);r(!!d?.google?.configured),o(L);const W=L.find(ae=>ae.connectionType==="gsc");await Promise.all([qa(W),_s(),_n(),mn(),Oa(),W?.propertyId?Un():Promise.resolve()])}finally{Ge(!1)}}l.useEffect(()=>{Ga()},[t,s]),l.useEffect(()=>{re(0),de(null),w(d=>d.startDate||d.endDate?{...d,startDate:"",endDate:""}:d),G(d=>d+1),_n()},[k]);const Ba=l.useRef(!1);l.useEffect(()=>{if(!Ba.current){Ba.current=!0;return}re(0),Ye.setPage(1),_s(0)},[oe]);function Gn(d){const L=Q===d?null:d;de(L),w(W=>({...W,startDate:L??"",endDate:L??""})),G(W=>W+1)}const Ka=l.useRef(!1);l.useEffect(()=>{if(!Ka.current){Ka.current=!0;return}re(0),_s(0)},[ys]);async function Va(){if(!a){Me("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}Be(!0),Me(null),Gt(null);try{let d=function(dt){if(dt.source!==ae||dt.origin!==$e||!dt.data||typeof dt.data!="object")return;const Xt=dt.data;Xt.type!==Xd||Xt.connectionType!=="gsc"||ne(!0)};const{authUrl:L,redirectUri:W}=await Sl(t,"gsc");if(!L.startsWith("https://accounts.google.com/")){Me("Unexpected OAuth redirect URL. Please try again.");return}const ae=window.open(L,"_blank","width=600,height=700");if(!ae){window.location.assign(L);return}const $e=W?new URL(W).origin:window.location.origin;let qe=!1,Ke=null;const ct=()=>{Ke!==null&&window.clearInterval(Ke),window.removeEventListener("message",d)},ne=async dt=>{if(!qe){qe=!0,ct(),Gt(dt?"Google connected. Refreshing access…":"Refreshing Google connection…");try{await at(n,"google"),await Ga()}finally{Gt(null)}}};window.addEventListener("message",d),Gt("Finish the Google consent flow in the popup. This page will refresh automatically."),Ke=window.setInterval(()=>{ae.closed&&ne(!1)},1e3)}catch(d){Me(d instanceof Error?d.message:"Failed to start OAuth flow")}finally{Be(!1)}}async function Xi(){Me(null),Gt(null);try{await wl(t,"gsc"),await at(n,"google"),o(d=>d.filter(L=>L.connectionType!=="gsc")),u([]),$("")}catch(d){Me(d instanceof Error?d.message:"Failed to disconnect")}}async function Ji(){if(O){Ce(!0),Me(null);try{await Tl(t,"gsc",O),await at(n,"google"),o(d=>d.map(L=>L.connectionType==="gsc"?{...L,propertyId:O}:L)),we({title:"GSC property updated",detail:`${t} is now linked to ${O}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(d){Me(d instanceof Error?d.message:"Failed to save GSC property")}finally{Ce(!1)}}}async function Zi(){Me(null),Gt(null);try{await On.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(C,10)||void 0,full:z||void 0}}),await at(n,"gsc")}catch{}}async function za(){if(g.trim()){De(!0),Me(null),Gt(null);try{const d=await Rl(t,g.trim());await at(n,"gsc"),_(d),v(""),await mn()}catch(d){Me(d instanceof Error?d.message:"Failed to inspect URL")}finally{De(!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"})]})}),Ut&&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:Ut.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:Ut.message}),(us(Ut.enableUrl)||us(Ut.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[us(Ut.enableUrl)&&e.jsx("a",{href:us(Ut.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 ↗"}),us(Ut.indexingApiUrl)&&e.jsx("a",{href:us(Ut.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:()=>un(null),children:"×"})]})}),Ma&&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:[Ma,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>Me(null),children:"×"})]}),Da&&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:[Da,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>Gt(null),children:"×"})]}),it?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[wt?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:wt.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Coverage measured"," ",H?.lastInspectedAt?Ot(H.lastInspectedAt):"never"]}),e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:Ie(Xi),children:"Disconnect"})]}):e.jsxs(he,{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(ue,{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(A,{type:"button",variant:"outline",size:"sm",disabled:X,onClick:Ie(Va),children:X?"Opening…":"Connect Google Search Console"}):e.jsx(A,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(_t,{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."})]})]})]}),(wt||Qi)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs(he,{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.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Search performance"}),e.jsx(ze,{text:`Tile percentages show the fitted trend's relative change from its first measured day to its last. Click any day to filter the table below to that date. Query and page filters match case-insensitive substrings and run on Apply filters. Filtering and sorting examine up to ${bn.toLocaleString()} matching rows while the table shows ${Bt} per page.`})]}),c?.window?.startDate&&c.window.endDate&&e.jsxs("p",{className:"text-xs text-muted",children:[c.window.startDate," to ",c.window.endDate,(c.window.daysSinceLatestData??0)>0&&` · latest data ${c.window.daysSinceLatestData} day${c.window.daysSinceLatestData===1?"":"s"} ago`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"segmented",role:"group","aria-label":"Performance time period",children:Yd.map(d=>e.jsx("button",{type:"button","aria-pressed":k===d,className:`segmented-option ${k===d?"segmented-option-active":""}`,onClick:()=>{U(d),re(0),Ye.setPage(1)},children:d==="all"?"All":d},d))}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:ve,onClick:()=>{re(0),Ye.setPage(1),_s(0),_n()},children:ve?"Loading…":"Apply filters"})]})]}),c&&c.daily.length>0&&(()=>{const{totals:d,daily:L,trends:W}=c,$e=cr.filter(ne=>M.includes(ne.key)).map(ne=>({dataKey:ne.key,label:ne.label,color:ne.color,axisId:ne.key,inverted:ne.inverted,formatValue:ne.format,trend:je?W?.[ne.key]??null:null})),qe=ne=>d[ne]??null,Ke=new Map(L.map(ne=>[ne.date,ne])),ct=L.length===0?[]:dd(L[0].date,L[L.length-1].date).map(ne=>Ke.get(ne)??{date:ne});return e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:cr.map(ne=>{const dt=M.includes(ne.key),Xt=qe(ne.key),hn=W?.[ne.key]??null,xn=Xt===null;return e.jsxs("button",{type:"button","aria-pressed":dt,disabled:xn,className:`rounded-md border px-3 py-2 text-left transition-colors ${dt?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${xn?"cursor-not-allowed opacity-50":""}`,onClick:()=>{te(Jt=>Jt.includes(ne.key)?Jt.length===1?Jt:Jt.filter(el=>el!==ne.key):[...Jt,ne.key])},children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2 w-2 rounded-full",style:{backgroundColor:dt?ne.color:"transparent",border:`1px solid ${ne.color}`}}),e.jsx("span",{className:"text-xs text-secondary",children:ne.label})]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:Xt===null?"—":ne.format(Xt)}),hn&&e.jsx("span",{className:"block text-[11px] tabular-nums text-muted",children:Zd(hn,ne.inverted,d.days)})]},ne.key)})}),e.jsx("div",{className:"mt-2 flex items-center justify-end",children:e.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5 text-xs text-secondary",children:[e.jsx("input",{type:"checkbox",className:"accent-mono-400",checked:je,onChange:ne=>le(ne.target.checked)}),"Trend line"]})}),e.jsx("div",{className:"mt-1",children:e.jsx(ed,{data:ct,xKey:"date",series:$e,xTickFormatter:Tn,labelFormatter:ps,onSelectX:Gn,selectedX:Q})}),e.jsx("div",{role:"group","aria-label":"Filter the table to a single day",children:L.map(ne=>e.jsxs("button",{type:"button",className:"sr-only focus:not-sr-only focus:inline-block focus:rounded focus:border focus:border-strong focus:bg-surface-active focus:px-2 focus:py-1 focus:text-xs focus:text-strong","aria-pressed":Q===ne.date,onClick:()=>Gn(ne.date),children:[ps(ne.date),": ",ne.clicks," clicks, ",ne.impressions," impressions"]},ne.date))}),Q&&e.jsxs("div",{className:"mt-1 flex items-center gap-2 text-xs",children:[e.jsxs("span",{className:"text-secondary",children:["Table showing ",ps(Q)]}),e.jsxs("button",{type:"button",className:"text-link hover:underline",onClick:()=>Gn(Q),children:["Show all ",d.days," days"]})]}),d.position!==null&&(d.positionDays??d.days)<d.days&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position covers ",d.positionDays," of ",d.days," days. The rest have no property-level position recorded."]}),(d.position===null||d.position===void 0)&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position needs a property-level sync. Run ",e.jsx("code",{children:"canonry google sync"})," to record it."]})]})})(),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:F.startDate,onChange:d=>w(L=>({...L,startDate:d.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:F.endDate,onChange:d=>w(L=>({...L,endDate:d.target.value}))}),e.jsx(Ys,{value:F.query,onChange:d=>w(L=>({...L,query:d})),label:"Filter search queries",placeholder:"Contains query…"}),e.jsx(Ys,{value:F.page,onChange:d=>w(L=>({...L,page:d})),label:"Filter page URLs",placeholder:"Contains page URL…"})]}),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(hs).map(d=>e.jsx("th",{className:"text-right","aria-sort":Nt?.key===d?Nt.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),Os(L=>L?.key===d?L.dir==="desc"?{key:d,dir:"asc"}:null:{key:d,dir:"desc"})},children:[jl[d],Nt?.key===d?Nt.dir==="desc"?" ↓":" ↑":""]})},d))]})}),e.jsx("tbody",{children:js.map((d,L)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:d.date}),e.jsx("td",{className:"max-w-xs truncate text-strong",children:d.query}),e.jsx("td",{className:"max-w-xs text-secondary",children:e.jsx(Cn,{value:d.page})}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:d.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:d.impressions.toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[(Number.isFinite(d.ctr)?d.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:d.position.toFixed(1)})]},`${d.date}:${d.query}:${d.page}:${L}`))})]})}),e.jsx(Ps,{page:ie?Ye.page:Math.floor(Z/Bt)+1,pageSize:Bt,visibleRows:js.length,totalRows:ie?xe:void 0,hasNextPage:ie?void 0:ce,disabled:ve,itemLabel:ie?"matches":"rows",onPageChange:d=>{if(ie){Ye.setPage(d);return}const L=(d-1)*Bt;re(L),_s(L)}}),ie&&xe>=bn?e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Results are capped at ",bn.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(he,{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.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Index coverage"}),e.jsx(ze,{text:"Google's Indexing API is intended for eligible JobPosting and BroadcastEvent pages. Sitemap resubmission is the general-site bulk path."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[H&&H.notIndexed.length>0&&e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:At,onClick:()=>{Hi()},children:At?"Requesting…":`Request indexing (${H.notIndexed.length})`}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:lt,onClick:()=>{Oa(!0)},children:lt?"Loading…":"Reload saved coverage"})]})]}),H&&H.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const d=H.summary.indexed+H.summary.notIndexed,L=d>0?H.summary.indexed/d:0,W=d>0?H.summary.notIndexed/d:0,ae=54,$e=2*Math.PI*ae,qe=$e*(1-L),Ke=$e*W,ct=$e*L;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:ae,fill:"none",stroke:It.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:ae,fill:"none",stroke:gs.positiveDeep,strokeWidth:"14",strokeDasharray:$e,strokeDashoffset:qe,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),H.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:ae,fill:"none",stroke:It.textFaint,strokeWidth:"14",strokeDasharray:`${Ke} ${$e-Ke}`,strokeDashoffset:-ct,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:[(L*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:H.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:H.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:["Not indexed",(H.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-faint",children:["· ",(H.reasonGroups??[]).length," ",(H.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),H.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:H.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(d=>{const L=d==="indexed"?H.indexed.length:d==="notIndexed"?H.notIndexed.length:H.deindexed.length,W=d==="indexed"?"Indexed":d==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",role:"tab","aria-selected":Ze===d,className:`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${Ze===d?"border-accent text-heading":"border-transparent text-secondary hover:border-mono-600 hover:text-strong"}`,onClick:()=>{qs(d),Ht(null)},children:[W," (",L,")"]},d)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[Ze==="indexed"&&H.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:Re.map(d=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:d.url}),e.jsx("td",{className:"text-secondary",children:d.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:d.crawlTime?d.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:d.isMobileFriendly===!0?"Yes":d.isMobileFriendly===!1?"No":"—"})]},d.id))})]}),Ze==="notIndexed"&&!st&&(H.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:(H.reasonGroups??[]).map(d=>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:()=>Ht(d.reason),onKeyDown:L=>{(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),Ht(d.reason))},tabIndex:0,role:"button","aria-label":`View ${d.reason} pages`,children:[e.jsx("td",{className:"text-strong",children:d.reason}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:d.count})]},d.reason))})]}),Ze==="notIndexed"&&!st&&(H.reasonGroups??[]).length===0&&H.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:Wt.map(d=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:d.url}),e.jsx("td",{className:"text-secondary",children:d.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:d.coverageState??"Unknown"})]},d.id))})]}),Ze==="notIndexed"&&st&&(()=>{const d=(H.reasonGroups??[]).find(L=>L.reason===st);return d?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:()=>Ht(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:d.reason}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[d.count," affected page",d.count!==1?"s":""]})]}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:At,onClick:()=>{Fa(d.urls.map(L=>L.url))},children:At?"Requesting…":`Request indexing (${d.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:Fs.map(L=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:L.url}),e.jsx("td",{className:"text-secondary",children:L.crawlTime?L.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-strong transition-colors",disabled:At,onClick:()=>{Fa([L.url])},title:"Request indexing",children:"Index"})})]},L.id))})]})]}):null})(),Ze==="deindexed"&&H.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:xt.map((d,L)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:d.url}),e.jsx("td",{className:"text-secondary",children:d.previousState}),e.jsx("td",{className:"text-secondary",children:d.currentState}),e.jsx("td",{className:"text-secondary",children:d.transitionDate.split("T")[0]})]},`${d.url}-${L}`))})]}),(Ze==="indexed"&&H.indexed.length===0||Ze==="notIndexed"&&!st&&H.notIndexed.length===0||Ze==="deindexed"&&H.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),e.jsx(Ps,{page:ee,pageSize:Zt,visibleRows:Math.min(Zt,B.length-se),totalRows:B.length,onPageChange:ge,itemLabel:"URLs"})]}),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":Dt,onClick:()=>Es(d=>!d),children:[e.jsx("span",{children:"Coverage history"}),e.jsx("span",{children:Dt?"Hide snapshots":yt.length>0?`View ${yt.length} snapshots`:"View history"})]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["Current: ",H.summary.indexed.toLocaleString()," indexed, ",H.summary.notIndexed.toLocaleString()," not indexed.",ye&&e.jsxs(e.Fragment,{children:[" Since the last snapshot: ",ye.indexed>=0?"+":"",ye.indexed.toLocaleString()," indexed, ",ye.notIndexed>=0?"+":"",ye.notIndexed.toLocaleString()," not indexed."]})]}),Dt&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:yt.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:yt.map(d=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:d.date}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:d.indexed.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:d.notIndexed.toLocaleString()})]},d.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:lt?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),e.jsxs(he,{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.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Sitemap operations"}),e.jsx(ze,{text:"Submitting asks Google to refetch these sitemaps. Indexing is not guaranteed."})]})]}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:ke||!wt?.propertyId,onClick:()=>{Un()},children:ke?"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:me,onChange:d=>fe(d.target.value),onKeyDown:d=>d.key==="Enter"&&void Ns([me.trim()])}),e.jsx(A,{type:"button",size:"sm",disabled:!os||tt||!me.trim(),onClick:()=>{Ns([me.trim()])},children:tt?"Submitting…":"Submit sitemap to Google"})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:!os||tt||qn.length===0,onClick:()=>{Ns(qn)},children:tt?"Resubmitting…":zi}),e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:!os||tt||!ht?.length,onClick:()=>{Yi()},children:"Resubmit all files"}),We&&e.jsxs("span",{className:"text-xs text-muted",children:["Top level: ",We.indexes," index",We.indexes===1?"":"es",", ",We.files," file",We.files===1?"":"s"]}),E&&e.jsxs("span",{className:"text-xs text-secondary",children:["Submitting ",E.completed,"/",E.total]})]}),!os&&wt&&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(Va),children:"Reconnect"})]}),ht&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:ht.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Ys,{value:pt,onChange:d=>{Je(d),Et.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:Et.rows.flatMap(d=>{const L=dr(d),W=ur(d),ae=mr(d),$e=ot[d.path]??[],qe=Le.has(d.path),Ke=e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs text-strong",children:e.jsx(Cn,{value:d.path})}),e.jsx("td",{className:"text-secondary",children:d.isSitemapsIndex?e.jsx("button",{type:"button",className:"text-secondary hover:text-strong","aria-expanded":qe,"aria-label":`${qe?"Collapse":"Expand"} files in ${d.path}`,onClick:()=>{Wi(d.path)},children:Tt.has(d.path)?"Loading…":`${qe?"▾":"▸"} Index${ot[d.path]?` (${$e.length})`:""}`}):"Sitemap"}),e.jsx("td",{className:"text-secondary",children:ae}),e.jsx("td",{className:"text-secondary",children:d.lastSubmitted?d.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:d.lastDownloaded?d.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:L.toLocaleString()}),e.jsx("td",{className:"max-w-48 text-secondary",children:W||"—"}),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||tt,onClick:()=>{Ns([d.path])},children:d.lastSubmitted?"Resubmit to Google":"Submit to Google"}),wt?.sitemapUrl===d.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:kt,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{_a(d.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Fn.isPending,onClick:()=>{Ua(d.path)},children:"Inspect URLs"})]})})]},d.path),ct=d.isSitemapsIndex&&qe?$e.map(ne=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs pl-6 text-secondary",children:e.jsx(Cn,{value:ne.path})}),e.jsx("td",{className:"text-secondary",children:"File"}),e.jsx("td",{className:"text-secondary",children:mr(ne)}),e.jsx("td",{className:"text-secondary",children:ne.lastSubmitted?ne.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:ne.lastDownloaded?ne.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:dr(ne).toLocaleString()}),e.jsx("td",{className:"text-secondary",children:ur(ne)||"—"}),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||tt,onClick:()=>{Ns([ne.path])},children:"Resubmit"}),wt?.sitemapUrl===ne.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:kt,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{_a(ne.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Fn.isPending,onClick:()=>{Ua(ne.path)},children:"Inspect URLs"})]})})]},`${d.path}:${ne.path}`)):[];return[Ke,...ct]})})]}),e.jsx(Ps,{page:Et.page,pageSize:Bt,visibleRows:Et.rows.length,totalRows:Et.totalRows,onPageChange:Et.setPage,itemLabel:"sitemaps"})]}):e.jsx("p",{className:"text-sm text-muted",children:"No sitemaps found for this property."})})]}),e.jsxs(he,{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:d=>v(d.target.value),onKeyDown:d=>d.key==="Enter"&&void za()}),e.jsx(A,{type:"button",size:"sm",disabled:be||!wt?.propertyId||!g.trim(),onClick:Ie(za),children:be?"Inspecting…":"Inspect URL"})]}),T&&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:T.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:T.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:Qa(T.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:Ot(T.crawlTime)})]})]})]}),e.jsxs(he,{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(A,{type:"button",variant:"outline",size:"sm",disabled:R,onClick:()=>{mn(!0)},children:R?"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:Xe,onChange:d=>rt(d.target.value)}),e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:R,onClick:()=>{mn(!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(d=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:d.url}),e.jsx("td",{className:"text-neutral",children:d.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:d.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:d.coverageState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:Qa(d.isMobileFriendly??null)}),e.jsx("td",{className:"text-secondary",children:Ot(d.inspectedAt)})]},d.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No inspection history yet."})]}),e.jsxs(he,{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(d=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:d.url}),e.jsx("td",{className:"text-secondary",children:d.previousState??"Unknown"}),e.jsx("td",{className:"text-neutral",children:d.currentState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:Ot(d.transitionDate)})]},`${d.url}:${d.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No deindexed transitions recorded."})]})]}),wt&&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:()=>Ds(d=>!d),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 ${is?"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"})]})}),is&&e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(he,{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.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Pick the Search Console property"}),e.jsx(ze,{text:"The selected property is used for future syncs and URL inspections for this project."})]})]})}),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:O,disabled:Ve||m.length===0,onChange:d=>$(d.target.value),children:m.length===0?e.jsx("option",{value:"",children:Ve?"Loading properties…":"No properties available"}):m.map(d=>e.jsxs("option",{value:d.siteUrl,children:[d.siteUrl," · ",d.permissionLevel]},d.siteUrl))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:Ve,onClick:()=>{qa(wt,!0)},children:Ve?"Refreshing…":"Refresh properties"}),e.jsx(A,{type:"button",size:"sm",disabled:!O||He,onClick:Ie(Ji),children:He?"Saving…":"Save property"})]})]})]}),e.jsxs(he,{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:C,onChange:d=>J(d.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:z,onChange:d=>P(d.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(A,{type:"button",size:"sm",disabled:On.isPending||!wt.propertyId,onClick:Ie(Zi),children:On.isPending?"Queueing…":"Queue sync"}),!wt.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=rs(),[a,r]=l.useState(null),[i,o]=l.useState(null),[m,u]=l.useState(!1),h=_e(Na({client:V,path:{name:t}})),x=h.data?.find(q=>q.connectionType==="gbp"),c=!!x,y=a?{locationName:a}:void 0,N=_e({...Ml({client:V,path:{name:t}}),enabled:c}),f=_e({...Dl({client:V,path:{name:t},query:y}),enabled:c}),b=_e({...El({client:V,path:{name:t},query:y}),enabled:c}),p=_e({...ql({client:V,path:{name:t},query:y}),enabled:c}),T=_e({...Ol({client:V,path:{name:t},query:y}),enabled:c}),_=_e({...Fl({client:V,path:{name:t},query:y}),enabled:c}),O=_e({queryKey:["gbp-section-insights",t],queryFn:()=>_l(t),enabled:c});function $(){at(n,"gbp")}const g=Zs({...Gl(),onSuccess:q=>{Ul({id:q.runId,projectId:s,kind:en["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),we({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),v=l.useSyncExternalStore(Bl,Wa,Wa),C=Object.values(v.runs).some(q=>q.kind===en["gbp-sync"]&&q.projectId===s),J=g.isPending||C,z=Zs({...Kl(),onSuccess:()=>$()});if(l.useEffect(()=>{if(!a||!N.data)return;const q=N.data.locations.filter(ie=>ie.selected);(q.length<=1||!q.some(ie=>ie.locationName===a))&&r(null)},[a,N.data]),l.useEffect(()=>{if(!i||!N.data)return;(a?[a]:N.data.locations.filter(ie=>ie.selected).map(ie=>ie.locationName)).includes(i)||o(null)},[i,N.data,a]),h.isLoading)return null;if(!x){const q=[{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(he,{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:q.map((ie,Se)=>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:Se+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:ie.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:ie.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:ie.note})]})]},ie.title))})]})})}const P=f.data,k=N.data?.locations??[],U=k.filter(q=>q.selected),M=b.data?.keywords??[],te=p.data?.lodging??[],je=T.data?.placeActions??[],le=_.data?.places??[],Q=k.length>0?k[0].accountName:x.domain,de=a?k.find(q=>q.locationName===a)?.displayName??null:null,oe=a?k.filter(q=>q.locationName===a):U,G=new Set(oe.map(q=>q.locationName)),F=te.filter(q=>G.has(q.locationName)),w=je.filter(q=>G.has(q.locationName)),Z=le.filter(q=>G.has(q.locationName)),re=new Set(U.map(q=>q.locationName)),ce=a?M:M.filter(q=>re.has(q.locationName)),K=!a&&U.length>1,xe=(O.data??[]).filter(q=>!q.dismissed&&tu.has(q.type)&&(!de||q.query===de||q.query===a||q.title.startsWith(de)));return e.jsx("section",{className:"page-section-divider",children:e.jsxs(he,{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(ue,{tone:"positive",children:"Connected"}),!Y()&&e.jsx(et,{type:"button",variant:"outline",size:"sm",disabled:J,onClick:()=>g.mutate({client:V,path:{name:t},body:{}}),children:J?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-muted",children:[Q?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-secondary",children:Q})," · "]}):null,N.data?`${N.data.totalSelected} of ${N.data.totalDiscovered} locations tracked`:"Loading locations…"]}),U.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:q=>r(q.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"}),U.map(q=>e.jsx("option",{value:q.locationName,children:q.displayName},q.id))]})]}),U.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:[xe.length>0&&e.jsxs("div",{className:"mb-6 grid gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Needs attention"}),xe.map(q=>e.jsx("div",{className:["insight-card",pu(q.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:[q.title,q.recommendation?.reason&&e.jsx(ze,{text:q.recommendation.reason})]})},q.id))]}),P&&e.jsx(yu,{performance:P.performance,freshness:P.freshness,timeseries:P.timeseries}),P?.profileCompleteness&&e.jsx(nu,{summary:P.profileCompleteness}),oe.length>0&&e.jsx(au,{locations:oe,lodging:F,places:Z,placeActions:w,expandedLocation:i,onToggleExpanded:q=>{o(ie=>ie===q?null:q)}}),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"]})]}),ce.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"}),K&&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:ce.slice(0,25).map(q=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-neutral",children:q.keyword}),K&&e.jsx("td",{className:"text-muted",children:k.find(ie=>ie.locationName===q.locationName)?.displayName??q.locationName}),e.jsx("td",{className:"text-right font-mono text-strong",children:q.valueCount!==null?q.valueCount.toLocaleString():e.jsxs("span",{className:"text-muted",title:"Privacy floor — Google withheld the exact count",children:["<",q.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-faint",children:[q.periodStart,"–",q.periodEnd]})]},`${q.locationName}:${q.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:()=>u(q=>!q),"aria-expanded":m,children:[e.jsx("span",{"aria-hidden":"true",children:m?"▾":"▸"})," Manage locations (",k.length,")"]}),m&&e.jsx("div",{className:"mt-3",children:k.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"}),!Y()&&e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:k.map(q=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:q.displayName}),e.jsx("td",{className:"text-muted",children:q.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(ue,{tone:q.selected?"positive":"neutral",children:q.selected?"Tracked":"Not tracked"})}),!Y()&&e.jsx("td",{className:"text-right",children:e.jsx(et,{type:"button",variant:"outline",size:"sm",disabled:z.isPending,onClick:()=>z.mutate({client:V,path:{name:t,locationName:q.locationName},body:{selected:!q.selected}}),children:q.selected?"Untrack":"Track"})})]},q.id))})]})})]})]})})}function nu({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:Bs(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:Bs(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:Bs(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:Bs(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:Bs(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])),m=new Map(n.map(h=>[h.locationName,h])),u=new Map;for(const h of a){const x=u.get(h.locationName)??[];x.push(h),u.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:Y()?"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=m.get(h.locationName)??null,y=u.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(ue,{tone:h.selected?"positive":"neutral",children:h.selected?"Tracked":"Not tracked"}),h.openStatus&&h.openStatus!=="OPEN"&&e.jsx(ue,{tone:h.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:Ci(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(A,{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:ms(t.description)?"positive":"neutral",value:ms(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:ms(t.primaryPhone)?"positive":"neutral",value:ms(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:ms(t.websiteUri)?"positive":"neutral",value:ms(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(ue,{tone:n.tone,children:[n.label," ",n.value]},n.label))})}function lu({lodging:t}){return e.jsx(Sa,{...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(Sa,{...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(Sa,{...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 Sa({tone:t,label:s,detail:n}){return e.jsxs("div",{children:[e.jsx(ue,{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(Wn,{title:"Owner profile · Business Information",children:[e.jsx(gt,{label:"Primary category",value:t.primaryCategoryDisplayName??"Not returned"}),e.jsx(gt,{label:"Secondary categories",value:t.additionalCategories.length>0?t.additionalCategories.join(", "):"Not returned"}),e.jsx(gt,{label:"Description",value:ms(t.description)?t.description:"Not returned"}),e.jsx(gt,{label:"Hours",value:t.regularHours?"Returned by Google":"Not returned"}),e.jsx(gt,{label:"Service area",value:t.serviceArea?"Returned by Google":"Not returned"}),e.jsx(gt,{label:"Phone",value:t.primaryPhone??"Not returned"}),e.jsx(gt,{label:"Website",value:t.websiteUri??"Not returned"}),e.jsx(gt,{label:"Open status",value:Ci(t.openStatus)}),e.jsx(gt,{label:"Opening date",value:t.openingDate??"Not returned"})]}),e.jsx(Wn,{title:"Hotel data · Lodging API",children:s?e.jsxs(e.Fragment,{children:[e.jsx(gt,{label:"Last checked",value:hr(s.syncedAt)}),e.jsx(gt,{label:"Groups returned",value:String(s.populatedGroupCount)}),e.jsx(gt,{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(Wn,{title:"Public listing + CTAs",children:[n?e.jsxs(e.Fragment,{children:[e.jsx(gt,{label:"Places tier",value:n.tier}),e.jsx(gt,{label:"Last checked",value:hr(n.syncedAt)}),e.jsx(gt,{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 Wn({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 gt({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 Bs(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 ms(t){return typeof t=="string"&&t.trim().length>0}function Ci(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 hr(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 yu({performance:t,freshness:s,timeseries:n}){const a=t.totals,r=Vl.filter(f=>(a[f]??0)>0),i=zl.filter(f=>(a[f]??0)>0),o=Object.keys(a).filter(f=>(a[f]??0)>0&&Ql(f)==="other").sort((f,b)=>(a[b]??0)-(a[f]??0)),m=Object.keys(a).filter(f=>(a[f]??0)===0).sort(),u=n.map(f=>{const b={date:f.date};for(const[p,T]of Object.entries(f.metrics))b[p]=T;return b}),h=n.find(f=>f.pending)?.date,x=n.length>0?n[n.length-1].date:void 0,c=u.length>0,y=s.dataThroughDate?`Data through ${ps(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(xr,{data:u,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:[An(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(xr,{data:u,metrics:i,kind:"area",firstPending:h,lastDate:x})]}),m.length>0&&e.jsxs("p",{className:"text-xs text-faint",children:["Not active: ",m.map(f=>An(f)).join(", ")]})]})}function xr({data:t,metrics:s,kind:n,firstPending:a,lastDate:r}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(tn,{width:"100%",height:"100%",children:e.jsxs(sn,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(ci,{stroke:ii,vertical:!1}),e.jsx(nn,{dataKey:"date",tick:Ft,tickLine:!1,axisLine:{stroke:bs},tickFormatter:Tn,minTickGap:24}),e.jsx(an,{tick:Ft,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(rn,{...As,labelFormatter:ps,formatter:(i,o)=>[typeof i=="number"?i.toLocaleString():String(i??0),An(String(o??""))]}),e.jsx(oi,{wrapperStyle:{fontSize:11,color:It.text},formatter:i=>An(i)}),a&&r&&e.jsx(rd,{x1:a,x2:r,fill:It.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:It.textDim,fontSize:10}}),s.map((i,o)=>n==="line"?e.jsx(di,{type:"monotone",dataKey:i,stroke:mt[o%mt.length],strokeWidth:2,dot:!1,isAnimationActive:!1},i):e.jsx(Cs,{type:"monotone",dataKey:i,stackId:"reach",stroke:mt[o%mt.length],fill:mt[o%mt.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},i))]})})})}function ju(t){return li(as(String(t)))}function vu(t){return fs(as(String(t)))}function Yn({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(Yc,{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 yn=Bt;function ws(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function Xn(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===en["backlink-extract"]&&!Xr(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([]),[m,u]=l.useState(null),[h,x]=l.useState(null),[c,y]=l.useState(null),[N,f]=l.useState(Date.now()),[b,p]=l.useState(0),[T,_]=l.useState(!0),[O,$]=l.useState(!1),[g,v]=l.useState(null),C=l.useCallback(async()=>{_(!0),v(null);try{const[Q,de,oe,G,F]=await Promise.all([Hl().catch(()=>null),Wl(t,{excludeCrawlers:!0}).catch(()=>null),Yl(t,{limit:yn,offset:b,excludeCrawlers:!0}).catch(Z=>{if(Z instanceof Ls&&Z.code==="NOT_FOUND")return null;throw Z}),Xl(t).catch(()=>[]),Jl(t).catch(()=>[])]);u(Q),n(de),r(oe),o(G);const w=Su(F);x(w)}catch(Q){v(Q instanceof Error?Q.message:"Failed to load backlinks")}finally{_(!1)}},[t,b]);l.useEffect(()=>{C()},[C]),l.useEffect(()=>{if(!h)return;const Q=h.id;let de=!1;const oe=async()=>{try{const F=await ua(Q);if(de)return;Xr(F.status)?(x(null),y(F),await C()):x(w=>w?.id===F.id?{...w,...F}:w)}catch{}},G=window.setInterval(()=>{oe()},3e3);return()=>{de=!0,window.clearInterval(G)}},[h,C]),l.useEffect(()=>{if(!h)return;const Q=window.setInterval(()=>f(Date.now()),1e3);return()=>window.clearInterval(Q)},[h]),l.useEffect(()=>{if(!c||c.status==="failed")return;const Q=window.setTimeout(()=>y(null),1e4);return()=>window.clearTimeout(Q)},[c]);async function J(){$(!0),v(null);try{const Q=await eo(t);x(Q)}catch(Q){Q instanceof Ls&&Q.code==="MISSING_DEPENDENCY"?v("DuckDB is not installed. Visit the Backlinks admin page to install it."):v(Q instanceof Error?Q.message:"Failed to trigger extract")}finally{$(!1)}}const z=l.useMemo(()=>i.slice().sort((Q,de)=>Q.queriedAt.localeCompare(de.queriedAt)).map(Q=>({date:Q.queriedAt,linkingDomains:Q.totalLinkingDomains})),[i]),P=a?.rows??[],k=a?.total??0,U=s?.excludedLinkingDomains??0,M=Math.floor(b/yn)+1;return l.useEffect(()=>{b>0&&b>=k&&p(0)},[b,k]),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(he,{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(he,{className:"surface-card p-4 mb-4 border-info-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Hc,{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(ue,{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(he,{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(ai,{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:Zl(c.error)}):c.status!=="failed"?e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),te()]});function te(){return T?e.jsx(he,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading backlinks…"})}):je()}function je(){const Q=s!==null&&s.totalLinkingDomains>0,de=c?.status==="failed",oe=s!==null&&s.totalLinkingDomains===0&&!de,G=m?.status==="ready",F=m?.status==="failed",w=m&&(m.status==="downloading"||m.status==="querying"||m.status==="queued");return Q?le(e.jsxs(e.Fragment,{children:[!Y()&&e.jsxs(e.Fragment,{children:[e.jsxs(A,{type:"button",variant:"outline",size:"sm",disabled:O||h!==null,onClick:Ie(J),children:[e.jsx(ri,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":O?"Queuing…":"Re-run extract"]}),e.jsx(Yn,{label:"About re-running",children:"Re-queries the current release for this project without downloading it again."})]}),!Y()&&e.jsx(A,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:ws("/backlinks"),children:"Open admin"})})]})):e.jsx(he,{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(Wc,{className:"h-5 w-5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1",children:[!m&&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."}),!Y()&&e.jsx("div",{className:"mt-4",children:e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:ws("/backlinks"),children:"Set up backlinks"})})})]}),w&&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 (",m.status,m.phaseDetail?` — ${m.phaseDetail}`:"","). Backlinks will appear here once it finishes."]}),!Y()&&e.jsx("div",{className:"mt-4",children:e.jsx(A,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:ws("/backlinks"),children:"View sync status"})})})]}),F&&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:m.error??"The workspace release sync failed. Retry from the Backlinks admin page."}),!Y()&&e.jsx("div",{className:"mt-4",children:e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:ws("/backlinks"),children:"Go to Backlinks admin"})})})]}),G&&!w&&!oe&&!de&&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:m.release})," is ready. Run an extract for this project."]}),!Y()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(A,{type:"button",size:"sm",disabled:O||h!==null,onClick:Ie(J),children:[e.jsx(In,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":O?"Queuing…":"Run extract"]}),e.jsx(Yn,{label:"About extraction",children:"Queries the current release for this project without downloading it again."})]})]}),de&&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."}),!Y()&&e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:ws("/backlinks"),children:"Go to Backlinks admin"})})})]}),oe&&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."]}),!Y()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:ws("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(A,{type:"button",variant:"outline",size:"sm",disabled:O||h!==null,onClick:Ie(J),children:[e.jsx(In,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":O?"Queuing…":"Re-run extract"]}),e.jsxs(Yn,{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 le(Q){if(!s)return null;const de="Linking hosts",oe="linking hosts",G="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:Xn(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 ",oe]}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:Xn(s.totalHosts)})}),e.jsxs("p",{className:"metric-card-sub",children:["aggregate ",oe," across referring domains"]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsx("p",{className:"metric-card-eyebrow",children:"Top-10 concentration"}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:Nu(s.top10HostsShare)})}),e.jsxs("p",{className:"metric-card-sub",children:["share of ",oe," from the 10 largest linking domains"]})]})]}),e.jsxs("p",{className:"text-xs text-muted mt-2",children:[e.jsx("span",{className:"text-secondary",children:"Common Crawl"})," · ",G," ",e.jsx("code",{className:"text-secondary",children:s.release})," · queried ",wu(s.queriedAt),U>0&&e.jsxs(e.Fragment,{children:[" · ",U," excluded domain",U===1?"":"s"]})]}),z.length>=2&&e.jsxs(he,{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(tn,{width:"100%",height:"100%",children:e.jsxs(sn,{data:z,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:mt[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:mt[0],stopOpacity:0})]})}),e.jsx(nn,{dataKey:"date",tick:Ft,stroke:bs,tickFormatter:ju}),e.jsx(an,{tick:Ft,stroke:bs,allowDecimals:!1}),e.jsx(rn,{contentStyle:As.contentStyle,labelStyle:As.labelStyle,itemStyle:As.itemStyle,labelFormatter:vu}),e.jsx(Cs,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:mt[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(he,{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:de})]})}),e.jsxs("tbody",{children:[P.map(F=>e.jsxs("tr",{className:"border-b border-mono-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-strong",children:F.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-secondary tabular-nums",children:Xn(F.numHosts)})]},F.linkingDomain)),P.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-muted",colSpan:2,children:U>0&&k===0?`Every referring domain in this ${G} was a crawler/proxy host (${U} hidden).`:`No referring domains in this ${G}.`})})]})]})}),e.jsx(Ps,{page:M,pageSize:yn,visibleRows:P.length,totalRows:k,onPageChange:F=>p((F-1)*yn)})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:Q})]})}}function Pu({projectName:t}){const s=_e({...to({client:V,path:{name:t}}),staleTime:Jr}),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:wa(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(Tu,{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(jn,{label:"Cited + mentioned",value:`${n} / ${s}`,helper:"In sources AND named in answer",tone:n>0?"positive":"neutral"}),e.jsx(jn,{label:"Cited only",value:`${a} / ${s}`,helper:"In sources, not named in answer",tone:a>0?"positive-dim":"neutral"}),e.jsx(jn,{label:"Mentioned only",value:`${r} / ${s}`,helper:"Named in answer, no source link",tone:r>0?"caution":"neutral"}),e.jsx(jn,{label:"Invisible",value:`${i} / ${s}`,helper:"No engine cites or mentions",tone:i>0?"negative":"neutral"})]})}function jn({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(Xc,{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(ks,{active:!0,tone:"cited"}),e.jsx("span",{children:"cited (in sources)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ks,{active:!0,tone:"mentioned"}),e.jsx("span",{children:"mentioned (in answer)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ks,{active:!1,tone:"cited"}),e.jsx(ks,{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(ks,{active:t.cited,tone:"cited"}),e.jsx(ks,{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 ks({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 Tu({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 cn="__cited__",dn="__mentioned__",$t="__mentionShare__";function ki(t){const s=t,{dataStartDate:n,dataEndDate:a}=s;return typeof n!="string"||typeof a!="string"?null:{start:as(n),end:as(a),sweepCount:s.sweepCount??1}}function Dn(t){const s=ki(t);if(!s)return"Sweep date unavailable";const n=fs(s.start),a=fs(s.end);return n===a?n:`${n} – ${a} · ${s.sweepCount} sweeps combined`}function Mu(t){const s=ki(t);return s?li(s.start):""}function Ms(t){return t.trim().toLowerCase()}function pa(t){return Math.round(t*1e3)/10}function ga(t){return t.byProvider??{}}function Du(t,s,n){const a=t.buckets.length>0,r=t.buckets.length===1;if(n==="overall"){const u=s==="cited"?cn:dn,h=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(c=>({date:c.startDate,[u]:pa(c[h])})),series:[u],hasData:a,singleBucket:r}}const i=s==="mentioned"?"mentionRate":"citationRate",o=[...new Set(t.buckets.flatMap(u=>Object.keys(ga(u))))].sort();return{rows:t.buckets.map(u=>{const h={date:u.startDate},x=ga(u);for(const c of o){const y=x[c];h[c]=y?pa(y[i]):null}return h}),series:o,hasData:a,singleBucket:r}}function Pi(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 pr(t,s){const n=Ms(s);return Object.entries(t).find(([a])=>Ms(a)===n)?.[1]}function Kt(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(!pr(ga(a),s))continue;const r=Pi(a);return r?pr(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 Ku(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 zu(t){const s=t.buckets.map(a=>{const r=a.mentionShare;return{date:a.startDate,[$t]:r?.rate==null?null:pa(r.rate)}}),n=s.map(a=>a[$t]).filter(a=>typeof a=="number"&&Number.isFinite(a));return{rows:s,series:[$t],hasData:n.length>0,singleBucket:n.length===1}}function Qu(t,s,n){return s==="mentionShare"?zu(t):Du(t,s,n)}function gr(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 fr(t){const[,s,n]=t.slice(0,10).split("-");return!s||!n?t:`${s}/${n}`}function br(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=>`${br(n.delta)} on ${fr(n.date)}`).join(", ")}`;const s=[...t].sort((n,a)=>a.date.localeCompare(n.date))[0];return`Query set changed ${t.length} times (latest ${br(s.delta)} on ${fr(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"}],Xu=[{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."}],Ca=mt[2],Ju="var(--chart-tooltip-bg)",Zu={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",local:"Local"};function zt(t){const s=Ms(t);return Zu[s]??t.charAt(0).toUpperCase()+t.slice(1)}function ss(t){return Math.round(t*10)/10}function em(t){return t===cn||t===dn||t===$t}function Ai(t){return t===cn?"Cited":t===dn?"Mentioned":t===$t?"Mention share":zt(t)}function zs(t,s){return t===cn?gs.positive:t===dn?mt[1]:t===$t?Ca:td(Ms(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(`
2
2
  `)}function Pn(t){return t==="cited"?"Cited":t==="mentionShare"?"Mention share":"Mentioned"}function ln(t){return t==="cited"?"citationRate":"mentionRate"}function Ri(t,s){return s==="cited"?t.cited:t.mentionedCount}function $i(t,s,n){const a=t.byProvider[s];return a?{count:n==="cited"?a.cited:a.mentionedCount,total:a.total,rate:n==="cited"?a.citationRate:a.mentionRate}:null}function Ii(t,s){if(s===void 0)return null;const n=String(s);return t.find(a=>a.startDate===n)??null}function fa(t){const s=Pi(t);if(s===null)return"Model attribution unavailable for this bucket.";const n=Object.entries(s).sort(([a],[r])=>Ms(a).localeCompare(Ms(r))).map(([a,r])=>`${zt(a)}: ${Kt(r)}`);return n.length>0?`Model evidence: ${n.join("; ")}`:"No model evidence in this bucket."}function nm(t){return t.some(({event:s})=>s.to.status==="mixed")?gs.caution:t.some(({event:s})=>s.to.status==="unknown")?gs.negative:t.every(({event:s})=>s.from.status==="known"&&s.to.status==="known")?mt[4]:gs.positive}function am(t,s,n){const a=Ii(t,s);return a?Dn(a):fs(as(n))}function rm({partition:t,available:s,counts:n,truncated:a,incompleteHistory:r,served:i,mismatch:o,buckets:m}){const u=l.useId(),h=Object.entries(i).sort(([c],[y])=>c.localeCompare(y)),x=t.buckets.length>0||t.beforeWindow.length>0;return e.jsxs("aside",{className:"trend-model-evidence","aria-labelledby":"trend-model-evidence-title","aria-describedby":u,children:[e.jsxs("div",{className:"trend-model-evidence-head",children:[e.jsx("p",{id:"trend-model-evidence-title",className:"trend-model-evidence-title",children:"Model evidence changes"}),e.jsx("span",{className:"trend-model-evidence-key","aria-hidden":"true",children:"Dashed chart markers"})]}),e.jsxs("p",{id:u,className:"sr-only",children:["Model evidence is recorded from the exact snapshots that produced each trend bucket. It is not the project’s configured provider model.",n.total>0?` ${n.shown} of ${n.total} recorded changes are listed.`:""]}),s?x?e.jsxs(e.Fragment,{children:[t.buckets.length>0&&e.jsx("ul",{className:"trend-model-evidence-list",children:t.buckets.flatMap(({bucketStartDate:c,events:y})=>y.map(({provider:N,event:f})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:am(m,c,f.observedAt)}),e.jsxs("span",{children:[zt(N),": ",Kt(f.from)," → ",Kt(f.to)]})]},`${N}-${f.observedAt}-${f.bucketStartDate}`)))}),t.beforeWindow.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"trend-model-evidence-note",children:"Changed before this date range"}),e.jsx("ul",{className:"trend-model-evidence-list",children:t.beforeWindow.map(({provider:c,event:y})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsxs("span",{className:"trend-model-evidence-date",children:["on or before ",fs(as(y.observedAt))]}),e.jsxs("span",{children:[zt(c),": ",Kt(y.from)," → ",Kt(y.to),y.anchorObservedAt?` (last seen ${Kt(y.from)} on ${fs(as(y.anchorObservedAt))})`:""]})]},`before-${c}-${y.observedAt}`))})]}),a.map(c=>e.jsxs("p",{className:"trend-model-evidence-note",children:[zt(c.provider),": showing the most recent ",c.shown," of ",c.total," changes."]},`truncated-${c.provider}`)),r.map(c=>e.jsxs("p",{className:"trend-model-evidence-note",children:["We did not look far enough back to be sure this is every ",zt(c)," change."]},`incomplete-${c}`))]}):e.jsx("p",{className:"trend-model-evidence-empty",children:"No model evidence changes in this window."}):e.jsx("p",{className:"trend-model-evidence-empty",children:"Attribution unavailable from this API version."}),h.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"trend-model-evidence-note",children:"What the engines answered with"}),e.jsx("ul",{className:"trend-model-evidence-list",children:h.map(([c,y])=>{const N=_u(y.latestServedModelIds),f=o[c];return e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:fs(as(y.latestObservation.observedAt))}),e.jsxs("span",{children:[zt(c),": ",N??Kt(y.latestObservation.state),f?` — not the ${Kt(f.configured)} you selected`:""]})]},`served-${c}`)})})]})]})}function yr(t){return t===null?"no data":`${t}%`}function Jn(t){return t==null?"undefined":`${ss(t*100)}%`}function im({active:t,label:s,payload:n,metric:a,mode:r,buckets:i}){if(!t)return null;const o=Ii(i,s);if(!o)return null;if(a==="mentionShare"){const u=o.mentionShare.projectMentionSnapshots,h=o.mentionShare.competitorMentionSnapshots,x=u+h,c=o.mentionShare.rate==null?null:ss(o.mentionShare.rate*100);return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:Dn(o)}),e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch trend-tooltip-swatch-ring",style:{borderColor:Ca},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:"Mention share"}),e.jsx("span",{className:"trend-tooltip-value",children:yr(c)})]}),x>0?e.jsxs("p",{className:"trend-tooltip-detail",children:["You ",u," / ",x," brand mentions. Competitors ",h,"."]}):e.jsx("p",{className:"trend-tooltip-detail",children:"No project or competitor brand mentions in this bucket."}),e.jsx("p",{className:"trend-tooltip-detail",children:fa(o)})]})}const m=r==="byProvider"?(n??[]).filter(u=>u.dataKey!==void 0):[{dataKey:a==="cited"?cn:dn,value:ss(o[ln(a)]*100)}];return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:Dn(o)}),m.map((u,h)=>{const x=String(u.dataKey??u.name??""),c=r==="byProvider"?$i(o,x,a):null,y=c?.count??Ri(o,a),N=c?.total??o.total,f=typeof u.value=="number"?u.value:ss(c?c.rate*100:o[ln(a)]*100),b=u.color??zs(x,h);return e.jsxs("div",{className:"trend-tooltip-block",children:[e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch",style:{backgroundColor:b},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:Ai(x)}),e.jsx("span",{className:"trend-tooltip-value",children:yr(f)})]}),e.jsxs("p",{className:"trend-tooltip-detail",children:[y," / ",N," snapshots, ",a==="cited"?"source links":"answer text"]})]},`${x}-${h}`)}),e.jsx("p",{className:"trend-tooltip-detail",children:fa(o)})]})}function lm({buckets:t,metric:s,mode:n,series:a}){return e.jsxs("table",{className:"sr-only",children:[e.jsxs("caption",{children:[Pn(s)," trend data"]}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Bucket"}),e.jsx("th",{scope:"col",children:"Values"})]})}),e.jsx("tbody",{children:t.map(r=>{let i;if(s==="mentionShare"){const o=r.mentionShare.projectMentionSnapshots,m=r.mentionShare.competitorMentionSnapshots,u=o+m;i=u>0?`${Jn(r.mentionShare.rate)} mention share, ${o} of ${u} brand mentions were you`:"mention share undefined, no project or competitor brand mentions"}else n==="byProvider"?i=a.map(o=>{const m=$i(r,o,s);return m?`${zt(o)} ${Jn(m.rate)} ${Pn(s).toLowerCase()}, ${m.count} of ${m.total} snapshots`:`${zt(o)} no data`}).join("; "):i=`${Jn(r[ln(s)])} ${Pn(s).toLowerCase()}, ${Ri(r,s)} of ${r.total} snapshots`;return i+=`; ${fa(r)}`,e.jsxs("tr",{children:[e.jsx("th",{scope:"row",children:Dn(r)}),e.jsx("td",{children:i})]},r.startDate)})})]})}function Zn({options:t,value:s,onChange:n,ariaLabel:a,className:r}){const i=l.useId();return e.jsx("div",{role:"group","aria-label":a,className:`segmented ${r??""}`,children:t.map(o=>{const m=s===o.value,u=o.description?`${i}-${o.value}-description`:void 0;return e.jsxs(l.Fragment,{children:[e.jsx("button",{type:"button","aria-pressed":m,"aria-describedby":u,className:`segmented-option ${m?"segmented-option-active":""}`,onClick:()=>n(o.value),children:o.label}),o.description&&e.jsx("span",{id:u,className:"sr-only",children:o.description})]},o.value)})})}function om({projectName:t,competitorDomains:s=[],analyticsRevision:n="none"}){const[a,r]=l.useState("all"),[i,o]=l.useState("mentioned"),[m,u]=l.useState("byProvider"),h=l.useMemo(()=>sm(s),[s]),x=_e({queryKey:["analytics-metrics",t,a,h,n],queryFn:()=>so(t,a),staleTime:Jr}),c=x.data??null,y=x.error,N=i==="mentionShare"?"overall":m,f=l.useMemo(()=>c?Qu(c,i,N):null,[c,i,N]),b=c?Eu(c):null,p=l.useMemo(()=>Bu(b??{}),[b]),T=l.useMemo(()=>Ku(b??{}),[b]),_=l.useMemo(()=>Vu(b??{}),[b]),O=l.useMemo(()=>Object.entries(b??{}).filter(([,G])=>G.anchorUnavailable).map(([G])=>G).sort(),[b]),$=l.useMemo(()=>c?qu(c):{},[c]),g=l.useMemo(()=>c?Ou(c):{},[c]),v=l.useMemo(()=>c?no(Fu(c)):null,[c]),C=i!=="mentionShare"&&N==="byProvider",J=Pn(i),z=i==="cited"?gs.positive:i==="mentionShare"?Ca:mt[1],P=C?It.textDim:z,k=c?.buckets??[],U=l.useMemo(()=>{const G=new Map(k.map(F=>[F.startDate,Mu(F)]));return F=>G.get(String(F))??""},[k]),M=i==="mentionShare"?f?gr(f.rows,$t):null:k.length>0?ss(k[k.length-1][ln(i)]*100):null,te=i==="mentionShare"?f?tm(f.rows,$t):null:k.length>0?ss(k[0][ln(i)]*100):null,je=i==="mentionShare"?f?.rows.filter(G=>typeof G[$t]=="number").length??0:k.length,le=M!==null&&te!==null&&je>1?ss(M-te):null,Q=s.length,de=e.jsxs(e.Fragment,{children:[v?.kind==="change"&&e.jsx("p",{className:"mb-3 rounded-lg border border-caution-800/60 bg-caution-950/20 px-3 py-2 text-[11px] leading-snug text-secondary",children:v.text}),e.jsxs("div",{className:"visibility-trend-head",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsxs("h2",{className:"visibility-trend-title",children:["Answer-engine trend",e.jsx(ze,{text:"Three separate signals over sweep buckets: answer text mentions, source citations, and your answer-text mention share against tracked competitors. Mentioned and Cited use query-provider snapshot rates; Mention share uses project plus competitor brand mentions."})]})]}),M!==null&&e.jsxs("div",{className:"visibility-trend-current",children:[e.jsx("span",{className:"visibility-trend-current-dot",style:{backgroundColor:P},"aria-hidden":"true"}),e.jsx("span",{className:"visibility-trend-current-label",children:J}),C&&e.jsx("span",{className:"visibility-trend-current-qualifier",children:"avg"}),e.jsxs("span",{className:"visibility-trend-current-value",children:[M,"%"]}),le!==null&&e.jsxs("span",{className:`visibility-trend-current-delta ${le>0?"text-positive-400":le<0?"text-negative-400":"text-muted"}`,children:[le>0?"+":"",le.toFixed(1)," pts"]})]})]}),e.jsxs("div",{className:"visibility-trend-controls",children:[e.jsx(Zn,{options:Xu,value:i,onChange:o,ariaLabel:"Metric",className:"visibility-trend-metric-control"}),i!=="mentionShare"&&e.jsx(Zn,{options:Yu,value:m,onChange:u,ariaLabel:"Series"}),e.jsx(Zn,{options:Wu,value:a,onChange:r,ariaLabel:"Time window",className:"sm:ml-auto"})]}),v?.kind==="no-known-change"&&e.jsxs("p",{className:"mt-3 text-[11px] leading-snug text-muted",children:[v.text,e.jsx(ze,{text:v.detail})]})]});let oe;if(y)oe=e.jsx("p",{className:"text-sm text-negative-400",children:wa(y)});else if(x.isLoading&&!c)oe=e.jsx("div",{className:"visibility-trend-chart animate-pulse rounded-lg bg-bg-elevated/40","aria-hidden":"true"});else if(i==="mentionShare"&&Q===0)oe=e.jsx("p",{className:"text-sm text-secondary",children:"Add tracked competitors to measure mention share over time."});else if(!c||!f)oe=null;else{const{rows:G,series:F,hasData:w,singleBucket:Z}=f,re=Hu(c.queryChanges);if(!w)oe=e.jsx("p",{className:"text-sm text-secondary",children:i==="mentionShare"?"No answer-text brand mentions for you or tracked competitors in this window yet.":"Run a sweep to start tracking citations and mentions over time."});else if(C&&F.length===0)oe=e.jsxs("p",{className:"text-sm text-secondary",children:["No per-engine breakdown for this data yet. Switch to ",e.jsx("span",{className:"text-strong",children:"All engines"})," to see the trend."]});else{const ce=`${J} rate across ${G.length} ${G.length===1?"sweep":"sweeps"}. Latest ${M}%${le!==null?`, ${le>=0?"up":"down"} ${Math.abs(le).toFixed(1)} points over the period`:""}.`;oe=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"sr-only",children:ce}),e.jsx(lm,{buckets:k,metric:i,mode:N,series:F}),C&&F.length>0&&e.jsx("ul",{className:"trend-legend","aria-label":"Engines",children:F.map((K,xe)=>{const q=gr(G,K),ie=Uu(k,K),Se=b===null?"Attribution unavailable":ie?Kt(ie):"No observed model evidence";return e.jsxs("li",{className:"trend-legend-item",children:[e.jsx("span",{className:"trend-legend-swatch",style:{backgroundColor:zs(K,xe)},"aria-hidden":"true"}),e.jsxs("span",{className:"trend-legend-label",children:[e.jsx("span",{className:"trend-legend-name",children:Ai(K)}),e.jsxs("span",{className:"trend-legend-model",children:[e.jsx("span",{"aria-hidden":"true",children:"· "}),Se]})]}),q!==null&&e.jsxs("span",{className:"trend-legend-value",children:[q,"%"]})]},K)})}),e.jsx("div",{className:"visibility-trend-chart",role:"img","aria-label":`${J} trend chart over ${G.length} ${G.length===1?"bucket":"buckets"}`,children:e.jsx(tn,{width:"100%",height:"100%",children:e.jsxs(sn,{data:G,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(ci,{stroke:ii,vertical:!1}),e.jsx(nn,{dataKey:"date",tick:Ft,tickLine:!1,axisLine:{stroke:bs},tickFormatter:U,minTickGap:24}),e.jsx(an,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:K=>`${K}%`,tick:Ft,tickLine:!1,axisLine:!1,width:40}),e.jsx(rn,{cursor:{stroke:bs,strokeWidth:1},content:e.jsx(im,{metric:i,mode:N,buckets:k})}),p.buckets.map(({bucketStartDate:K,events:xe})=>e.jsx(id,{x:K,stroke:nm(xe),strokeDasharray:"4 4",strokeWidth:1.5,ifOverflow:"extendDomain"},`model-evidence-${K}`)),F.map((K,xe)=>e.jsx(di,{type:"monotone",dataKey:K,name:K,stroke:zs(K,xe),strokeDasharray:K===$t?"5 4":void 0,strokeWidth:em(K)?2.5:2,dot:K===$t?{r:2.75,fill:"var(--chart-tooltip-bg)",stroke:zs(K,xe),strokeWidth:1.5}:{r:2.5,fill:zs(K,xe),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:Ju},connectNulls:K!==$t,isAnimationActive:!1},K))]})})}),e.jsx(rm,{partition:p,available:b!==null,counts:T,truncated:_,incompleteHistory:O,served:$,mismatch:g,buckets:k}),Z&&e.jsx("p",{className:"visibility-trend-note",children:i==="mentionShare"?"Only one competitive mention-share point so far. The trend line fills in after another sweep with brand mentions.":"Only one sweep so far. The trend line fills in after the next run."}),re&&e.jsx("p",{className:"visibility-trend-note",children:re})]})}}return e.jsxs("section",{className:"visibility-trend",children:[de,oe]})}const jr=new Set([Ws.queued,Ws.running]);function cm({projectName:t}){const s=rs(),[n,a]=l.useState(""),[r,i]=l.useState(""),[o,m]=l.useState(""),[u,h]=l.useState("__default__"),[x,c]=l.useState(null),y=_e({...ao({client:V,path:{name:t}}),staleTime:6e4}),N=_e({...Zr({client:V}),staleTime:6e4}),f=_e({...ro({client:V,path:{name:t},query:{limit:20}}),refetchInterval:P=>P.state.data?.runs.some(k=>jr.has(k.status))?3e3:!1}),b=f.data?.runs??[];l.useEffect(()=>{!x&&b[0]&&c(b[0].id)},[b,x]);const p=b.find(P=>P.id===x)??null,T=_e({...io({client:V,path:{name:t,runId:x??""}}),enabled:!!x,refetchInterval:p&&jr.has(p.status)?3e3:!1}),_=T.data??null,O=l.useMemo(()=>mm(n),[n]),$=y.data?.locations??[],g=l.useMemo(()=>{const P=new Map((N.data?.providerCatalog??[]).map(k=>[k.name,k]));return(N.data?.providers??[]).filter(k=>k.configured&&P.get(k.name)?.mode==="api").map(k=>({...k,catalog:P.get(k.name)}))},[N.data]),v=!N.isLoading&&g.length===0,C=g.find(P=>P.name===r)??null;l.useEffect(()=>{r&&!C&&(i(""),m(""))},[r,C]);const J=Zs({...lo(),onSuccess:async P=>{c(P.id),a(""),m(""),await gm(s),we({title:"Research batch saved",detail:`${P.totalQueries} quer${P.totalQueries===1?"y is":"ies are"} in research history. Nothing was added to tracked queries.`,tone:"positive",dedupeKey:`research:start:${P.id}`,dedupeMode:"replace"})},onError:P=>{we({title:"Could not start research",detail:P instanceof Error?P.message:"Check the provider, model, and location, then try again.",tone:"negative"})}});function z(){if(O.length===0||O.length>50||v||J.isPending||Y())return;const P=u==="__default__"?void 0:u==="__none__"?null:$.find(k=>k.label===u)??void 0;J.mutate({client:V,path:{name:t},body:{queries:O,...r?{provider:r}:{},...r&&o.trim()?{model:o.trim()}:{},...P!==void 0?{location:P}:{}}})}return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.85fr)_minmax(360px,1.15fr)]",children:[e.jsxs(he,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"New batch"}),e.jsx("h3",{children:"Research queries"}),e.jsx("p",{className:"mt-1 max-w-xl text-sm leading-6 text-muted",children:"Run specific queries against one API model and keep the answers as a separate research record."})]})}),e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("label",{className:"block",htmlFor:"research-queries",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Queries"}),e.jsx("textarea",{id:"research-queries",className:"mt-1 min-h-36 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:`one query per line
3
3
  e.g. What is the best way to choose an AEO platform?`,value:n,onChange:P=>a(P.target.value),"aria-describedby":"research-query-count"}),e.jsxs("span",{id:"research-query-count",className:`mt-1 block text-[11px] ${O.length>50?"text-negative":"text-faint"}`,children:[O.length," ",O.length===1?"query":"queries",", duplicates and blank lines are removed. Maximum 50."]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"block",htmlFor:"research-provider",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"API provider"}),e.jsxs("select",{id:"research-provider",className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none",value:r,onChange:P=>{i(P.target.value),m("")},children:[e.jsx("option",{value:"",children:"Project default"}),g.map(P=>e.jsx("option",{value:P.name,children:P.displayName??P.name},P.name))]})]}),e.jsxs("label",{className:"block",htmlFor:"research-location",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Location"}),e.jsxs("select",{id:"research-location",className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none",value:u,onChange:P=>h(P.target.value),children:[e.jsx("option",{value:"__default__",children:"Project default"}),e.jsx("option",{value:"__none__",children:"No location"}),$.map(P=>e.jsx("option",{value:P.label,children:P.label},P.label))]})]})]}),e.jsxs("label",{className:"block",htmlFor:"research-model",children:[e.jsxs("span",{className:"text-xs font-medium text-secondary",children:["Exact model ",e.jsx("span",{className:"font-normal text-muted",children:"(optional)"})]}),e.jsx("input",{id:"research-model",list:"research-known-models",className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none disabled:cursor-not-allowed disabled:opacity-50",placeholder:C?`Default: ${C.model??C.defaultModel??C.catalog.defaultModel}`:"Choose a provider to select an exact model",value:o,disabled:!C,onChange:P=>m(P.target.value)}),e.jsx("datalist",{id:"research-known-models",children:(C?.catalog.knownModels??[]).map(P=>e.jsx("option",{value:P.id,children:P.displayName},P.id))})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 border-t border-default pt-4",children:[!Y()&&e.jsxs(et,{type:"button",size:"sm",disabled:O.length===0||O.length>50||v||J.isPending,onClick:z,children:[e.jsx(In,{size:14}),J.isPending?"Starting research…":`Run ${O.length||""} research ${O.length===1?"query":"queries"}`]}),e.jsx("p",{className:"text-xs leading-5 text-muted",children:"Saved to research history. Nothing is added to tracked queries."})]}),v&&e.jsx("p",{className:"rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2 text-sm text-caution",children:"Configure an API provider in Settings before starting research. Browser engines are not available for this workflow."})]})]}),e.jsxs(he,{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:"Saved research batches"})]}),f.isFetching&&e.jsx(ue,{tone:"neutral",children:"Loading"})]}),b.length===0?e.jsx("p",{className:"mt-4 text-sm text-muted",children:"No research batches yet. Add one or more queries to begin."}):e.jsx("div",{className:"mt-4 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[680px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Run"}),e.jsx("th",{children:"Model"}),e.jsx("th",{children:"Location"}),e.jsx("th",{children:"Progress"}),e.jsx("th",{children:"Status"})]})}),e.jsx("tbody",{children:b.map(P=>e.jsxs("tr",{className:x===P.id?"bg-bg-elevated/40":void 0,children:[e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-left font-medium text-heading hover:text-link focus:outline-none focus:underline",onClick:()=>c(P.id),children:hm(P.createdAt)})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:P.provider}),e.jsx("span",{className:"font-mono text-[11px] text-muted",children:P.requestedModel??P.resolvedModel})]}),e.jsx("td",{className:"text-secondary",children:P.location?.label??"No location"}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[P.completedQueries+P.failedQueries,"/",P.totalQueries]}),e.jsx("td",{children:e.jsx(ue,{tone:Li(P.status),children:P.status})})]},P.id))})]})})]})]}),e.jsx(dm,{detail:_,isLoading:T.isFetching})]})}function dm({detail:t,isLoading:s}){const[n,a]=l.useState(null);l.useEffect(()=>{a(t?.queries[0]?.id??null)},[t?.id]);const r=t?.queries.find(i=>i.id===n)??t?.queries[0]??null;return e.jsxs(he,{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:"Results"}),e.jsx("h3",{children:t?`Research run ${xm(t.id)}`:"Choose a research batch"})]}),t&&e.jsx(ue,{tone:Li(t.status),children:t.status})]}),t?e.jsxs("div",{className:"mt-4 grid gap-4 xl:grid-cols-[minmax(0,1.15fr)_minmax(320px,0.85fr)]",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[680px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"})]})}),e.jsx("tbody",{children:t.queries.map(i=>e.jsxs("tr",{className:r?.id===i.id?"bg-bg-elevated/40":void 0,children:[e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-left font-medium text-heading hover:text-link focus:outline-none focus:underline",onClick:()=>a(i.id),children:i.query})}),e.jsx("td",{children:e.jsx(ue,{tone:pm(i.status),children:i.status})}),e.jsx("td",{children:e.jsx(ue,{tone:i.answerMentioned===!0?"positive":i.answerMentioned===!1?"neutral":i.status===xs.failed?"negative":"caution",children:i.answerMentioned===null?i.status===xs.failed?"Unavailable":"Pending":i.answerMentioned?"Mentioned":"Not mentioned"})}),e.jsx("td",{children:e.jsx(ue,{tone:i.citationState==="cited"?"positive":i.citationState==="not-cited"?"neutral":i.status===xs.failed?"negative":"caution",children:i.citationState===null?i.status===xs.failed?"Unavailable":"Pending":i.citationState==="cited"?"Cited":"Not cited"})})]},i.id))})]})}),e.jsx(um,{query:r,isLoading:s})]}):e.jsx("p",{className:"mt-4 text-sm text-muted",children:"Select a saved batch to inspect each answer and its source links."})]})}function um({query:t,isLoading:s}){return t?e.jsxs("div",{className:"space-y-4 border-t border-default pt-4 xl:border-t-0 xl:border-l xl:pl-4 xl:pt-0",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Selected query"}),e.jsx("p",{className:"mt-1 text-sm font-medium leading-6 text-heading",children:t.query})]}),t.error?e.jsx("div",{className:"rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:t.error}):t.answerText?e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Answer"}),e.jsx("p",{className:"mt-1 whitespace-pre-wrap text-sm leading-6 text-secondary",children:t.answerText})]}):e.jsx("p",{className:"text-sm text-muted",children:t.status===xs.failed?"This query did not return an answer.":"The answer will appear here when this query finishes."}),t.namedCompetitors.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Named in answer"}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:t.namedCompetitors.map(n=>e.jsx("span",{className:"mention-chip mention-chip--competitor",children:n},n))})]}),t.citedCompetitorDomains.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Cited competitor domains"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:"Cited as a source, not merely named in the answer."}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:t.citedCompetitorDomains.map(n=>e.jsx("span",{className:"mention-chip mention-chip--competitor",children:n.replace(/^www\./,"")},n))})]}),t.groundingSources.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Source links"}),e.jsx("ul",{className:"mt-2 space-y-1",children:t.groundingSources.map((n,a)=>{const r=us(n.uri),i=n.title||n.uri;return e.jsxs("li",{className:"flex min-w-0 items-start gap-1.5 text-sm",children:[r?e.jsx("a",{href:r,target:"_blank",rel:"noopener noreferrer",className:"truncate text-secondary hover:text-link focus:outline-none focus:underline",children:i}):e.jsx("span",{className:"truncate text-secondary",children:i}),r&&e.jsx(Jc,{className:"mt-0.5 size-3 shrink-0 text-muted","aria-hidden":"true"})]},`${n.uri}-${a}`)})})]})]}):e.jsx("p",{className:"text-sm text-muted",children:s?"Loading saved answers…":"Select a query to inspect its answer."})}function mm(t){const s=new Set;return t.split(/\r?\n/).map(n=>n.trim()).filter(n=>{const a=n.toLocaleLowerCase();return!n||s.has(a)?!1:(s.add(a),!0)})}function hm(t){const s=new Date(t);return Number.isNaN(s.valueOf())?t:new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(s)}function xm(t){return t.length>8?t.slice(0,8):t}function Li(t){return t===Ws.completed?"positive":t===Ws.partial?"caution":t===Ws.failed?"negative":"neutral"}function pm(t){return t===xs.completed?"positive":t===xs.failed?"negative":"neutral"}async function gm(t){await at(t,"researchRuns")}const ba=new Set(["queued","seeding","probing"]);function fm({projectName:t}){const[s,n]=l.useState("find");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:"Query discovery"}),e.jsx("h2",{children:"Discover or research queries"})]})}),e.jsxs("div",{className:"inline-flex rounded-md border border-default bg-surface p-1",role:"tablist","aria-label":"Query discovery workflow",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":s==="find",className:`rounded px-3 py-1.5 text-sm font-medium transition-colors ${s==="find"?"bg-bg-elevated text-heading shadow-sm":"text-muted hover:text-strong"}`,onClick:()=>n("find"),children:"Find queries"}),e.jsx("button",{type:"button",role:"tab","aria-selected":s==="research",className:`rounded px-3 py-1.5 text-sm font-medium transition-colors ${s==="research"?"bg-bg-elevated text-heading shadow-sm":"text-muted hover:text-strong"}`,onClick:()=>n("research"),children:"Research queries"})]}),e.jsx("div",{className:"mt-4",children:s==="find"?e.jsx(bm,{projectName:t}):e.jsx(cm,{projectName:t})})]})}function bm({projectName:t}){const s=rs(),[n,a]=l.useState(null),[r,i]=l.useState(""),[o,m]=l.useState("100"),u=_e({...oo({client:V,path:{name:t},query:{limit:"10"}}),refetchInterval:g=>g.state.data?.some(C=>ba.has(C.status))?3e3:!1}),h=u.data??[];l.useEffect(()=>{!n&&h[0]&&a(h[0].id)},[n,h]);const x=h.find(g=>g.id===n)??null,c=_e({...co({client:V,path:{name:t,id:n??""}}),enabled:!!n,refetchInterval:x&&ba.has(x.status)?3e3:!1}),y=c.data??null,N=_e({...uo({client:V,path:{name:t,id:n??""}}),enabled:!!(n&&x?.status==="completed")}),f=Zs({mutationFn:()=>{const g={},v=r.trim();v&&(g.icpDescription=v);const C=Number.parseInt(o,10);return Number.isFinite(C)&&C>0&&(g.maxProbes=C),mo(t,g)},onSuccess:async g=>{a(g.sessionId),i(""),await Nr(s,t,g.sessionId),we({title:"Discovery started",detail:`Run ${ea(g.sessionId)} is testing questions your customers might ask.`,tone:"neutral",dedupeKey:`discovery:start:${g.sessionId}`,dedupeMode:"replace"})},onError:g=>{we({title:"Discovery failed to start",detail:g instanceof Error?g.message:"Could not start discovery.",tone:"negative"})}}),b=Zs({mutationFn:g=>{if(!n)throw new Error("Select a completed discovery session first.");return ho(t,n,g)},onSuccess:async g=>{await Nr(s,t,g.sessionId),s.invalidateQueries({queryKey:ei({client:V})}),s.invalidateQueries({predicate:v=>Array.isArray(v.queryKey)&&v.queryKey[0]==="projects"&&v.queryKey.length>1}),we({title:"Queries added",detail:Nm(g),tone:"positive",dedupeKey:`discovery:promote:${g.sessionId}`,dedupeMode:"replace"})},onError:g=>{we({title:"Could not add queries",detail:g instanceof Error?g.message:"Could not add queries from this run.",tone:"negative"})}}),p=y??x,T=N.data??null,_=(T?.queriesByBucket.cited.length??0)+(T?.queriesByBucket.aspirational.length??0),O=l.useMemo(()=>(y?.probes??[]).slice(0,30),[y?.probes]);async function $(){try{const g=await u.refetch();if(g.error)throw g.error;const v=g.data?.length??0;we({title:"Discovery sessions refreshed",detail:`${v} recent session${v===1?"":"s"} loaded.`,tone:"positive",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}catch(g){we({title:"Discovery refresh failed",detail:g instanceof Error?g.message:"Could not reload discovery sessions.",tone:"negative",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}}return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 1"}),e.jsx("h2",{children:"Generate and check questions"}),e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-secondary",children:Y()?"Generate customer questions and check whether your site is already visible.":"Generate customer questions, check current visibility, then choose what to track."})]}),e.jsxs(A,{type:"button",variant:"outline",size:"sm",disabled:u.isFetching,onClick:()=>{$()},children:[e.jsx($n,{className:`size-3.5 ${u.isFetching?"animate-spin":""}`,"aria-hidden":"true"}),"Refresh"]})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[360px_minmax(0,1fr)]",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs(he,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 1"}),e.jsx("h3",{children:"Describe your customer"})]}),e.jsx(ue,{tone:"neutral",children:"Runs on Gemini"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm text-secondary",children:"Who is your ideal customer?"}),e.jsx("textarea",{className:"mt-1 min-h-24 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:"e.g. Small e-commerce stores that want AI-powered customer support. Leave blank to use the customer profile saved on this project.",value:r,onChange:g=>i(g.target.value)})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm text-secondary",children:"How many questions to test"}),e.jsx("input",{className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",inputMode:"numeric",value:o,onChange:g=>m(g.target.value)}),e.jsx("span",{className:"mt-1 block text-sm text-secondary",children:"More questions means broader coverage but a longer run. 100 is a good default."})]}),!Y()&&e.jsxs(et,{type:"button",size:"sm",disabled:f.isPending,onClick:()=>f.mutate(),children:[e.jsx(In,{size:14}),f.isPending?"Starting…":"Find queries"]})]})]}),e.jsxs(he,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Recent runs"})]}),u.isFetching&&e.jsx(ue,{tone:"neutral",children:"Loading"})]}),h.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No discovery runs yet. Describe your customer above to start your first one."}):e.jsx("div",{className:"space-y-2",children:h.map(g=>e.jsxs("button",{type:"button",className:`w-full rounded-md border px-3 py-2 text-left transition-colors ${n===g.id?"border-mono-600 bg-bg-elevated/70":"border-default bg-bg/40 hover:border-strong hover:bg-bg-elevated/40"}`,onClick:()=>a(g.id),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:ea(g.id)}),e.jsx(ue,{tone:vr(g.status),children:g.status})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-sm text-secondary",children:[e.jsxs("span",{children:["Cited queries ",g.citedCount??0]}),e.jsxs("span",{children:["Worth tracking ",g.aspirationalCount??0]}),e.jsxs("span",{children:["Skip ",g.wastedCount??0]})]})]},g.id))})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(he,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Run detail"}),e.jsx("h3",{children:p?ea(p.id):"No run selected"})]}),p&&e.jsx(ue,{tone:vr(p.status),children:p.status})]}),p?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(es,{label:"Questions tested",value:p.probeCount??0}),e.jsx(es,{label:"Cited queries",value:p.citedCount??0,tone:"positive"}),e.jsx(es,{label:"Worth tracking",value:p.aspirationalCount??0,tone:"caution"}),e.jsx(es,{label:"Skip",value:p.wastedCount??0,tone:"negative"})]}),p.error&&e.jsx("div",{className:"rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:p.error}),p.warning&&e.jsx("div",{className:"rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2 text-sm text-caution",children:p.warning}),p.icpDescription&&e.jsxs("div",{className:"rounded-md border border-default bg-surface px-3 py-2",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Customer profile"}),e.jsx("p",{className:"mt-1 text-sm text-neutral",children:p.icpDescription})]}),p.competitorMap.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-sm font-medium text-secondary",children:"Sites that keep getting cited"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:p.competitorMap.slice(0,8).map(g=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[g.domain," ",e.jsx("span",{className:"text-muted",children:g.hits})]},g.domain))})]})]}):e.jsx("p",{className:"text-sm text-secondary",children:"Start a run above, or pick one from Recent runs to see its progress."})]}),p?.status==="completed"&&e.jsxs(he,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 2"}),e.jsx("h3",{children:"Choose queries to track"})]}),!Y()&&e.jsxs(et,{type:"button",size:"sm",disabled:b.isPending||_===0,onClick:()=>b.mutate(void 0),children:[e.jsx(ai,{size:14}),b.isPending?"Adding…":"Add recommended queries"]})]}),N.isLoading?e.jsx("p",{className:"text-sm text-muted",children:"Loading recommendations…"}):T?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(es,{label:"Queries to add",value:_,tone:"positive"}),e.jsx(es,{label:"Cited queries",value:T.queriesByBucket.cited.length,tone:"positive"}),e.jsx(es,{label:"Worth tracking",value:T.queriesByBucket.aspirational.length,tone:"caution"}),e.jsx(es,{label:"Skip",value:T.queriesByBucket["wasted-surface"].length,tone:"negative"})]}),e.jsx("p",{className:"text-sm leading-6 text-secondary",children:"Adds Cited queries and Worth tracking queries, plus recurring competitor sites. Skip items remain available for review only."}),T.suggestedCompetitors.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-secondary",children:"Competitor sites that will be added"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:T.suggestedCompetitors.map(g=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[g.domain," ",e.jsx("span",{className:"text-muted",children:g.hits})]},g.domain))})]})]}):e.jsx("p",{className:"text-sm text-muted",children:"No recommendations available for this run."})]}),e.jsxs(he,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"All results"}),e.jsx("h3",{children:"Every question we tested"})]}),c.isFetching&&e.jsx(ue,{tone:"neutral",children:"Loading"})]}),O.length===0?e.jsx("p",{className:"text-sm text-muted",children:"Results show up here once the run starts testing questions."}):e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Question"}),e.jsx("th",{children:"Result"}),e.jsx("th",{children:"Sites cited"})]})}),e.jsx("tbody",{children:O.map(g=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:g.query}),e.jsx("td",{children:e.jsx(ue,{tone:ym(g.bucket),children:vm(g.bucket)})}),e.jsx("td",{className:"text-secondary",children:g.citedDomains.length>0?g.citedDomains.slice(0,3).join(", "):"-"})]},g.id))})]})})]})]})]})]})}function es({label:t,value:s,tone:n="neutral"}){const a=n==="positive"?"text-positive":n==="caution"?"text-caution":n==="negative"?"text-negative":"text-heading";return e.jsxs("div",{className:"rounded-md border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:t}),e.jsx("p",{className:`mt-1 text-2xl font-semibold tabular-nums ${a}`,children:s})]})}function vr(t){return t==="completed"?"positive":t==="failed"?"negative":ba.has(t)?"caution":"neutral"}function ym(t){return t==="cited"?"positive":t==="aspirational"?"caution":t==="wasted-surface"?"negative":"neutral"}const jm={cited:"Cited queries",aspirational:"Worth tracking","wasted-surface":"Skip"};function vm(t){return t?jm[t]:"Not classified"}function ea(t){return t.length>8?t.slice(0,8):t}function Nm(t){const s=t.promoted.queries.length,n=t.promoted.competitors.length,a=t.skipped.queries.length+t.skipped.competitors.length;return`${s} quer${s===1?"y":"ies"} and ${n} competitor${n===1?"":"s"} added${a>0?`; ${a} already tracked`:""}.`}async function Nr(t,s,n){await Promise.all([at(t,"discovery"),t.invalidateQueries({queryKey:xo({client:V})})])}function wr(t){return`${(t*100).toFixed(1)}%`}function wm({projectName:t}){const[s,n]=l.useState("changes"),[a,r]=l.useState(null),[i,o]=l.useState(null),m=_e({...po({client:V,path:{name:t},query:{limit:30}}),enabled:s==="health"}),u=_e({...go({client:V,path:{name:t},query:{kind:"answer-visibility",limit:100}}),enabled:s==="compare"}),h=(u.data??[]).filter(p=>(p.status==="completed"||p.status==="partial")&&p.trigger!=="probe").reverse(),x=i??h[0]?.id??"",c=a??h.find(p=>p.id!==x)?.id??"",y=!!(c&&x&&c!==x),N=_e({...fo({client:V,path:{name:t},query:{run1:c,run2:x}}),enabled:s==="compare"&&y}),f=m.data??[],b=N.data?.diff.filter(p=>p.changed||p.visibilityChanged)??[];return e.jsxs("div",{className:"mt-6",children:[e.jsx("div",{className:"filter-row",role:"tablist","aria-label":"Project history views",children:[["changes","Changes"],["health","Coverage history"],["compare","Compare runs"]].map(([p,T])=>e.jsx("button",{type:"button",role:"tab","aria-selected":s===p,className:`filter-chip ${s===p?"filter-chip-active":""}`,onClick:()=>n(p),children:T},p))}),s==="changes"?e.jsx(ld,{projectName:t}):null,s==="health"?e.jsxs("section",{className:"mt-6","aria-labelledby":"coverage-history-heading",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Query evidence"}),e.jsx("h2",{id:"coverage-history-heading",children:"Mention and citation coverage"}),e.jsx("p",{className:"supporting-copy mt-1",children:"Independent answer-text mentions and source citations across completed sweeps."})]}),m.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Loading coverage history…"}):null,!m.isLoading&&f.length===0?e.jsxs(he,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No coverage history yet"}),e.jsx("p",{children:"Complete an answer visibility sweep to create the first snapshot."})]}):null,f.length>0?e.jsx("div",{className:"evidence-table-wrap mt-4",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date"}),e.jsx("th",{className:"text-right",children:"Mentioned"}),e.jsx("th",{className:"text-right",children:"Mention coverage"}),e.jsx("th",{className:"text-right",children:"Cited"}),e.jsx("th",{className:"text-right",children:"Citation coverage"})]})}),e.jsx("tbody",{children:f.map(p=>e.jsxs("tr",{children:[e.jsx("td",{className:"whitespace-nowrap tabular-nums text-secondary",children:new Date(p.createdAt).toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[p.mentionedPairs,"/",p.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:wr(p.overallMentionRate)}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[p.citedPairs,"/",p.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:wr(p.overallCitedRate)})]},p.id))})]})}):null]}):null,s==="compare"?e.jsxs("section",{className:"mt-6","aria-labelledby":"compare-runs-heading",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Evidence diff"}),e.jsx("h2",{id:"compare-runs-heading",children:"Compare answer visibility runs"}),e.jsx("p",{className:"supporting-copy mt-1",children:"See which tracked queries changed mention or citation state between two sweeps."})]}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"text-xs text-muted",children:["Earlier run",e.jsx("select",{value:c,onChange:p=>r(p.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:h.map(p=>e.jsx("option",{value:p.id,children:new Date(p.createdAt).toLocaleString()},p.id))})]}),e.jsxs("label",{className:"text-xs text-muted",children:["Later run",e.jsx("select",{value:x,onChange:p=>o(p.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:h.map(p=>e.jsx("option",{value:p.id,children:new Date(p.createdAt).toLocaleString()},p.id))})]})]}),u.isLoading||N.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Comparing runs…"}):null,!u.isLoading&&h.length<2?e.jsxs(he,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"Two completed sweeps are required"}),e.jsx("p",{children:"Run another answer visibility sweep before comparing historical evidence."})]}):null,N.data&&b.length===0?e.jsxs(he,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No mention or citation changes"}),e.jsx("p",{children:"The selected sweeps have the same states for every comparable tracked query."})]}):null,b.length>0?e.jsx("div",{className:"evidence-table-wrap mt-4",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:"Citation"}),e.jsx("th",{children:"Mention"})]})}),e.jsx("tbody",{children:b.map(p=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:p.query??"Archived query"}),e.jsx("td",{children:e.jsxs(ue,{tone:p.changed?"caution":"neutral",children:[p.run1State??"none"," → ",p.run2State??"none"]})}),e.jsx("td",{children:e.jsxs(ue,{tone:p.visibilityChanged?"caution":"neutral",children:[p.run1MentionState??"none"," → ",p.run2MentionState??"none"]})})]},p.queryId??p.query??"unknown"))})]})}):null]}):null]})}const ta=20,Vt=50,Sm=50,Cm=50;function ka(t){return t==="viewer"}function Pa(t){return t?.status==="unavailable"}function Ti(t,s,n){return n?t.includes(s)?[...t]:[...t,s]:t.filter(a=>a!==s)}function Mi(t,s){const n=new Map(s.map(r=>[r.id,r.label])),a=t.map(r=>n.get(r)).filter(r=>!!r);return a.length===0?"Not applied":a.length>3?`${a.length} Properties`:a.join(", ")}function vn(t,s,n){if(t.kind==="all")return s.map(i=>i.id);if(t.kind==="specific")return s.filter(i=>t.propertyIds.includes(i.id)).map(i=>i.id);const a=new Set(t.groupIds),r=new Set(n.filter(i=>a.has(i.id)).flatMap(i=>i.propertyIds));return s.filter(i=>r.has(i.id)).map(i=>i.id)}function km(t,s,n){if(t.kind==="all")return`all ${n} ${n===1?"Property":"Properties"}`;if(t.kind==="specific")return n===1?"1 Property":`${n} Properties`;const a=t.groupIds.map(r=>s.find(i=>i.id===r)?.name).filter(r=>!!r);return a.length===0?"selected groups":a.join(" + ")}function sa(t,s){const n=new Set(s.map(r=>r.id)),a=t.propertyIds.filter(r=>n.has(r)).length;return`${t.name} · ${a===1?"1 Property":`${a} Properties`}`}function Sr(t){return t==="matched"?"positive":t==="duplicate"?"neutral":t==="ambiguous"||t==="proposed"||t==="excluded"?"caution":"negative"}function Cr(t){return t==="matched"?"Matched":t==="duplicate"?"Duplicate":t==="ambiguous"?"Ambiguous":t==="proposed"?"Property needs review":t==="excluded"?"Property excluded":t==="invalid"?"Invalid row":"Not matched"}function Nn(t){return t.status==="duplicate"&&t.duplicateOfRow?`Duplicates row ${t.duplicateOfRow}.`:t.status==="matched"?null:t.reason==="group-label-ambiguous"?`More than one group matches “${t.group}”. Rename duplicate groups, then preview again.`:t.status==="ambiguous"?"More than one Property matches this row. Add an exact URL to choose one.":t.status==="unmatched"?"No included Property matches this row.":t.reason==="group-key-conflict"?`The group name “${t.group}” conflicts with an existing setup identity. Rename the group, then preview again.`:t.status==="invalid"?"Check the Property, group, and optional URL fields.":t.status==="proposed"?"Review this proposed Property before importing it.":t.status==="excluded"?"Include this Property before importing it.":t.reason??null}function ya(t){return t.state==="missing"||t.source==="unavailable-tracked-query"||!t.source}function na(t){return ya(t)?"Unavailable tracked query":t.text?.trim()||"Unavailable tracked query"}function ja({properties:t,selectedPropertyIds:s,onSelectedPropertyIdsChange:n,legend:a,showBulkActions:r=!0}){const[i,o]=l.useState(""),[m,u]=l.useState(!1),h=i.trim().toLocaleLowerCase(),x=h?t.filter(f=>f.label.toLocaleLowerCase().includes(h)):t,c=m?x:x.slice(0,Sm),y=c.length<x.length;function N(){const f=new Set([...s,...c.map(b=>b.id)]);n(t.filter(b=>f.has(b.id)).map(b=>b.id))}return e.jsxs("fieldset",{children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:a}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-end justify-between gap-3",children:[e.jsxs("label",{className:"block min-w-48 flex-1",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Search Properties"}),e.jsx("input",{type:"search",value:i,onChange:f=>o(f.currentTarget.value),className:"mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400"})]}),r?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:c.length===0,onClick:N,children:"Select all shown"}),e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:s.length===0,onClick:()=>n([]),children:"Clear selection"})]}):null]}),x.length===0?e.jsx("p",{className:"mt-3 text-sm text-secondary",children:"No Properties match this search."}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"mt-3 text-sm text-secondary",children:["Showing ",c.length," of ",x.length," Properties"]}),e.jsx("div",{className:"mt-2 max-h-96 divide-y divide-default overflow-y-auto border-y border-default",children:c.map(f=>{const b=s.includes(f.id);return e.jsxs("label",{className:"flex min-h-11 cursor-pointer items-center justify-between gap-3 py-2 text-sm text-primary",children:[e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx("input",{"aria-label":`Select ${f.label}`,checked:b,type:"checkbox",onChange:p=>n(Ti(s,f.id,p.currentTarget.checked))}),e.jsx("span",{children:f.label})]}),f.urlCount===void 0?null:e.jsxs("span",{className:"tabular-nums text-secondary",children:[f.urlCount," URLs"]})]},f.id)})}),y?e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",onClick:()=>u(!0),children:"Show all Properties"}):null]})]})}function Aa(){return e.jsxs("div",{className:"flex items-center gap-2 text-sm text-secondary",children:[e.jsx(ue,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]})}function Ra({message:t}){return e.jsxs("div",{role:"status",className:"border-y border-caution-800/40 bg-caution-950/20 py-4 text-sm text-caution",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ue,{tone:"caution",children:"Unavailable"}),e.jsx("h4",{className:"font-medium",children:"Measurement setup unavailable"})]}),e.jsx("p",{className:"mt-2 max-w-2xl text-secondary",children:t})]})}function Pm({value:t}){const[s,n]=l.useState(0),[a,r]=l.useState(0),[i,o]=l.useState(null),m=t.preview,u=m?.counts.needsAttention??0,h=m?.rows.filter(C=>C.status==="matched")??[],x=m?.rows??[],c=x.filter(C=>C.status!=="matched"),y=Math.max(1,Math.ceil(x.length/Vt)),N=Math.min(s,y-1),f=x.slice(N*Vt,(N+1)*Vt),b=Math.max(1,Math.ceil(c.length/Vt)),p=Math.min(a,b-1),T=c.slice(p*Vt,(p+1)*Vt),_=t.csv.trim().length>0&&!t.isReviewing&&!t.isApplying,O=h.length>0&&!t.isApplying,$=m!==null&&i===m.previewChecksum,g=c.length>0&&p===b-1;l.useEffect(()=>{n(0),r(0),o(null)},[m?.previewChecksum]);async function v(C){if(C)try{t.onCsvChange(await C.text())}catch{}}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-group-import-title",className:"border-y border-default py-4",children:[e.jsxs("div",{className:"max-w-2xl",children:[e.jsx("h4",{id:"advanced-measurement-group-import-title",className:"text-sm font-medium text-heading",children:"Import groups from CSV"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Import market membership once instead of selecting the same Properties for every group."})]}),e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"CSV file"}),e.jsx("input",{"aria-label":"Group membership CSV file",type:"file",accept:".csv,text/csv",disabled:t.isReviewing||t.isApplying,onChange:C=>{v(C.currentTarget.files?.[0])},className:"mt-1 block min-h-11 w-full text-sm text-secondary file:mr-3 file:min-h-11 file:rounded-md file:border file:border-default file:bg-surface file:px-3 file:text-sm file:font-medium file:text-primary"})]}),e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Or paste CSV"}),e.jsx("textarea",{"aria-label":"Group membership CSV",rows:5,value:t.csv,disabled:t.isReviewing||t.isApplying,onChange:C=>t.onCsvChange(C.currentTarget.value),placeholder:`property,group,url
4
4
  Harbor House,Dallas,https://example.com/harbor-house`,className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!_,onClick:()=>{t.onReview()},children:t.isReviewing?"Reviewing CSV…":"Review CSV"}),e.jsx("span",{className:"text-sm text-secondary",children:"Use columns named property and group. URL is optional."})]}),t.error?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:t.error}):null,t.notice?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:t.notice}):null]}),m?e.jsxs("div",{className:"mt-4 border-t border-default pt-4","aria-live":"polite",children:[e.jsx("h5",{className:"text-sm font-medium text-heading",children:"Review group membership"}),e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:[m.counts.matchedRows," matched · ",m.counts.groupsReady," group",m.counts.groupsReady===1?"":"s"," ready",u>0?` · ${u} need${u===1?"s":""} attention`:""]}),m.groupChanges.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"Groups and memberships ready to apply"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Change"}),e.jsx("th",{children:"Properties"}),e.jsx("th",{children:"New memberships"})]})}),e.jsx("tbody",{children:m.groupChanges.map(C=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:C.label}),e.jsx("td",{className:"text-secondary",children:C.action==="create"?"Create group":"Add to existing group"}),e.jsx("td",{className:"tabular-nums text-secondary",children:C.targetKeys.length}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[C.addedTargetKeys.length,C.unchangedTargetKeys.length>0?` · ${C.unchangedTargetKeys.length} already members`:""]})]},C.groupKey))})]})}):null,m.rows.length>0?e.jsxs("details",{className:"mt-3 border-y border-default py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Review CSV rows (",m.counts.dataRows,")"]}),e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"CSV group membership review"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Row"}),e.jsx("th",{children:"Property"}),e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Status"})]})}),e.jsx("tbody",{children:f.map(C=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:C.dataRow}),e.jsx("td",{className:"text-heading",children:C.property}),e.jsx("td",{className:"text-secondary",children:C.group}),e.jsxs("td",{children:[e.jsx(ue,{tone:Sr(C.status),children:Cr(C.status)}),Nn(C)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:Nn(C)}):null]})]},C.dataRow))})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Page ",N+1," of ",y," · ",m.rows.length," rows"]}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:N===0,onClick:()=>n(C=>Math.max(0,C-1)),children:"Previous 50 rows"}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:N===y-1,onClick:()=>n(C=>Math.min(y-1,C+1)),children:"Next 50 rows"})]})]}):null,u>0?e.jsxs("details",{className:"mt-3 border-y border-caution-800/30 py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Fix ",u," row",u===1?"":"s"," before applying"]}),e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Correct these rows, or explicitly continue with only the reviewed matches. Rows needing attention are not added."}),e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"CSV rows that need attention"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Row"}),e.jsx("th",{children:"Property"}),e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Issue"})]})}),e.jsx("tbody",{children:T.map(C=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:C.dataRow}),e.jsx("td",{className:"text-heading",children:C.property}),e.jsx("td",{className:"text-secondary",children:C.group}),e.jsxs("td",{children:[e.jsx(ue,{tone:Sr(C.status),children:Cr(C.status)}),Nn(C)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:Nn(C)}):null]})]},C.dataRow))})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Exception page ",p+1," of ",b]}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:p===0,onClick:()=>r(C=>Math.max(0,C-1)),children:"Previous 50 exceptions"}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:p===b-1,onClick:()=>r(C=>Math.min(b-1,C+1)),children:"Review next 50 exceptions"})]}),e.jsxs("label",{className:"mt-3 flex min-h-11 max-w-xl items-center gap-3 text-sm text-heading",children:[e.jsx("input",{type:"checkbox",checked:$,disabled:t.isApplying||!g,onChange:C=>o(C.currentTarget.checked?m.previewChecksum:null),className:"size-4 rounded border-default"}),"I reviewed the exceptions and understand that ",u," row",u===1?"":"s"," will be skipped."]}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",disabled:!O||!$,onClick:()=>{t.onApply(h.map(C=>C.dataRow))},children:t.isApplying?"Applying groups…":`Apply ${h.length} matched row${h.length===1?"":"s"}`})]}):e.jsx(A,{type:"button",className:"mt-3 min-h-11",disabled:!O,onClick:()=>{t.onApply(h.map(C=>C.dataRow))},children:t.isApplying?"Creating groups…":`Create ${m.counts.groupsReady} group${m.counts.groupsReady===1?"":"s"} with ${h.length} membership${h.length===1?"":"s"}`})]}):null]})}const Am="—";function Rm({access:t,availability:s,properties:n,queries:a,selectedQueryIds:r,isApplying:i=!1,isBusy:o=!1,canContinue:m=!0,onSelectedQueryIdsChange:u,onApplySelectedQueries:h,onClearQueryAssignments:x,onRemoveQuery:c,onCreateQueries:y,onCreateAndPairQuestions:N,isCreatingQueries:f=!1,createQueriesError:b=null,onManageProjectQueries:p,groups:T,audience:_,onAudienceChange:O,assignmentImpact:$=null,isPreviewingAssignmentImpact:g=!1,assignmentImpactError:v=null,onRetryAssignmentImpact:C,assignmentNotice:J=null,onReplaceAssignments:z,isReplacingAssignments:P=!1,onBack:k,onContinue:U}){const[M,te]=l.useState(""),[je,le]=l.useState(!1),[Q,de]=l.useState(!1),[oe,G]=l.useState(""),[F,w]=l.useState(""),[Z,re]=l.useState(null);if(Pa(s))return e.jsx("section",{"aria-label":"Queries",children:e.jsx(Ra,{message:s.message})});const ce=ka(t),K=_,xe=O,q=vn(K,n,T),ie=q.length,Se=ie>0&&r.length>0&&!i&&!o&&!g&&$!==null&&v===null,Xe=x??c,rt=M.trim().toLocaleLowerCase(),it=rt?a.filter(I=>na(I).toLocaleLowerCase().includes(rt)):a,Ge=it.filter(I=>(I.propertyIds?.length??0)===0),X=Q?Ge:it,Be=je?X:X.slice(0,Cm),Ve=Be.filter(I=>!ya(I)),Pe=[...new Set(oe.split(`