@canonry/canonry 4.156.0 → 4.157.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/assets/agent-workspace/skills/canonry/SKILL.md +8 -3
- package/assets/agent-workspace/skills/canonry/references/server-side-traffic.md +454 -21
- package/assets/assets/{AuditHistoryPanel-gmJMVlXX.js → AuditHistoryPanel-D12lHs6n.js} +1 -1
- package/assets/assets/{BacklinksPage-Bv2sTCyN.js → BacklinksPage-D2ScFYru.js} +1 -1
- package/assets/assets/{HistoryPage-13q7GkiI.js → HistoryPage-jZ_I4rwX.js} +1 -1
- package/assets/assets/{MeasurementPropertyPage-BgBqXT1p.js → MeasurementPropertyPage-BIdQjXJT.js} +1 -1
- package/assets/assets/{ProjectPage-EsGwKhot.js → ProjectPage-CLvLOOtj.js} +3 -3
- package/assets/assets/{RunRow-bPzapIGJ.js → RunRow-Q2X0NR74.js} +1 -1
- package/assets/assets/{RunsPage-Dqfz18lH.js → RunsPage-Cw7YVsbJ.js} +1 -1
- package/assets/assets/{SettingsPage-_wMecn-V.js → SettingsPage-bFl2EXOD.js} +1 -1
- package/assets/assets/{TrafficPage-RYBdsOLB.js → TrafficPage-DJjhk7Jw.js} +1 -1
- package/assets/assets/{TrafficSourceDetailPage-DpeMMyKU.js → TrafficSourceDetailPage-CGKwIu9A.js} +1 -1
- package/assets/assets/{extract-error-message-DUarAlyD.js → extract-error-message-BHm98tXH.js} +1 -1
- package/assets/assets/{index-DP-fT2uI.js → index-VO6nKq5b.js} +25 -25
- package/assets/assets/{react-sigma_core.esm.min-DnypJl5w.js → react-sigma_core.esm.min-EzswMBkr.js} +1 -1
- package/assets/index.html +1 -1
- package/dist/{chunk-ZWESOFA5.js → chunk-AEIKAWOW.js} +88 -8
- package/dist/{chunk-CPASKGUE.js → chunk-KMTRO56O.js} +35 -1
- package/dist/{chunk-ABNN2ZVR.js → chunk-MEBL4EJO.js} +1820 -431
- package/dist/{chunk-AMPT2EP7.js → chunk-TRRVBTU5.js} +71 -0
- package/dist/cli.js +667 -142
- package/dist/index.d.ts +32 -0
- package/dist/index.js +4 -4
- package/dist/{intelligence-service-WHC7B32V.js → intelligence-service-YUUPSJRC.js} +2 -2
- package/dist/mcp.js +2 -2
- package/package.json +10 -9
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./react-sigma_core.esm.min-
|
|
2
|
-
import{j as e,r as d,L as ts,n as Ss,u as De,o as Mn,B as ui,C as eo,D as Rl,h as Ll,k as Bi}from"./vendor-tanstack-pFxw0eGP.js";import{T as oe,t as El,a as Il,u as to,C as Dl,P as Zs,B as L,h as Tl,b as Ml,c as _l,d as ye,i as ie,e as pt,f as Ue,I as at,g as yn,j as Gl,k as H,l as Ol,m as ql,n as Fl,o as Ul,p as so,q as zl,r as Bl,S as Ls,s as Kl,v as Vl,w as Ps,x as es,y as Ql,z as Ki,A as no,G as bt,D as hi,E as Hl,F as Wl,H as Yl,J as Xl,K as Vi,L as $e,M as ao,N as Jl,O as ka,Q as Zl,R as ec,U as tc,V as sc,W as nc,X as ac,Y as ic,Z as rc,_ as oc,$ as lc,a0 as cc,a1 as dc,a2 as uc,a3 as hc,a4 as mc,a5 as pc,a6 as ws,a7 as xc,a8 as io,a9 as ha,aa as gc,ab as nt,ac as fc,ad as bc,ae as yc,af as ma,ag as vc,ah as jc,ai as Nc,aj as en,ak as wc,al as Sc,am as kc,an as ro,ao as Ya,ap as Cc,aq as oo,ar as Ac,as as $c,at as Pc,au as Rc,av as lo,aw as Lc,ax as Ec,ay as Ic,az as En,aA as Es,aB as Dc,aC as Tc,aD as Mc,aE as _c,aF as co,aG as Gc,aH as Oc,aI as qc,aJ as Fc,aK as vn,aL as Uc,aM as zc,aN as Bc,aO as mi,aP as uo,aQ as Kc,aR as Vc,aS as Qc,aT as Hc,aU as Wc,aV as Yc,aW as Xc,aX as Jc,aY as Zc,aZ as ed,a_ as td,a$ as st,b0 as sd,b1 as nd,b2 as ad,b3 as id,b4 as rd,b5 as od,b6 as ld,b7 as cd,b8 as dd,b9 as ud,ba as hd,bb as md,bc as pd,bd as xd,be as gd,bf as fd,bg as bd,bh as yd,bi as vd,bj as jd,bk as Nd,bl as wd,bm as Sd,bn as kd,bo as Cd,bp as Ad,bq as $d,br as Pd,bs as Rd,bt as Ld,bu as Ed,bv as Id,bw as Dd,bx as Td,by as Md,bz as _d,bA as Gd,bB as Od,bC as Ca,bD as qd,bE as Fd,bF as Qi,bG as Ud,bH as zd,bI as Bd,bJ as Kd,bK as Vd,bL as Qd,bM as Hd,bN as Wd,bO as Yd,bP as Xd,bQ as Jd,bR as Zd,bS as eu,bT as ho,bU as tu,bV as su,bW as nu,bX as au,bY as iu,bZ as ru,b_ as ou,b$ as Hi,c0 as lu,c1 as Aa,c2 as cu,c3 as du,c4 as uu,c5 as hu,c6 as mu,c7 as pu,c8 as xu,c9 as gu,ca as mo,cb as po,cc as fu,cd as bu,ce as yu,cf as vu,cg as ju,ch as Qn,ci as Nu,cj as wu,ck as Su,cl as Wi,cm as ku}from"./index-DP-fT2uI.js";import{R as Cu}from"./RunRow-bPzapIGJ.js";import{S as pi,X as Au,q as $u,e as qn,r as Is,U as Pu,s as Ru,L as It,t as xo,i as Lu,P as Ms,D as go,u as Eu,v as fo,E as bo,p as Iu,b as Du,T as Xa,w as Yi,C as tn,x as Tu,y as Mu}from"./vendor-lucide-BtYdosYk.js";import{f as Ja,C as us,a as Ot,b as pa,c as Ds,d as Ct,e as kt,g as cs,h as xi,i as gi,j as Ns,o as ss,p as _u}from"./ChartPrimitives-DXVLCdBi.js";import{u as Gu,t as Ou,e as qu,a as Xi}from"./extract-error-message-DUarAlyD.js";import{R as sn,C as nn,X as an,Y as rn,T as on,L as yo,A as Qs,a as fi,b as Fu,d as bi,e as Uu}from"./vendor-recharts-C4ktw_aE.js";import{A as zu}from"./AuditHistoryPanel-gmJMVlXX.js";import{a as Bu,b as Ku}from"./v2-overview-adapter-COMP5UGt.js";function ca(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 Vu(t,s){return s<=0?null:Math.round((t-s)/s*100)}function $a(t,s,n="vs prior 7 days"){return t.deltaPct===null?t.prior===0?"First baseline week":"":t.deltaPct>0?`Up ${t.deltaPct}% ${n} (${ca(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${ca(t.prior)} ${s})`:`Flat ${n} (${ca(t.prior)} ${s})`}const vo=30;function Ji(t){return Math.round(t*10)/10}function Qu(t){return t.prior>=vo&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% vs prior`:`${t.deltaAbs>0?"+":""}${Ji(t.deltaAbs)} vs ${Ji(t.prior)}`}function Hu(t,s,n){return t.prior>=vo&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% ${n}`:`${t.deltaAbs>0?"+":""}${ca(Math.round(t.deltaAbs))} ${s} ${n}`}const Wu=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function jo(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function No(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 wo(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(jo).map(No).filter(Boolean)):new Set}function So(t,s){const n=jo(t).map(No).filter(Boolean).filter(a=>!Wu.has(a)).filter(a=>!s.has(a));return[...new Set(n)].sort().join(" ")}function Yu(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function Xu(t,s){const n=wo(t);if(s.length<=1||n.size===0)return[...s];const a=new Set,i=[];for(const r of s){if(r.category!=="content"){i.push(r);continue}const o=So(Yu(r),n);!o||a.has(o)||(a.add(o),i.push(r))}return i}function Ju(t){const s=wo(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const a=new Set;return n.filter(i=>{const r=So(i.query,s);return!r||a.has(r)?!1:(a.add(r),!0)})}const ko={queryClass:"all"},Zu=["all","non-brand","branded"];function eh(t){return typeof t=="string"&&Zu.includes(t)}function th(t){const s=eh(t.class)?t.class:ko.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 sh(t,s){return s===null||t===null?!1:t!==s}function nh(t){return{scope:t.scope==="group"&&t.groupKey?`group:${t.groupKey}`:void 0,class:t.queryClass===ko.queryClass?void 0:t.queryClass}}function Za({state:t,label:s}){return e.jsx(oe,{tone:Il(t),children:s??El(t)})}const Ht=25;function ah(t){return t.trim().toLocaleLowerCase().split(/\s+/).filter(Boolean)}function Co(t){let s=t;try{s=decodeURIComponent(t.replace(/\+/g," "))}catch{}let n="";const a=t.indexOf("?");return a>=0&&new URLSearchParams(t.slice(a+1)).forEach((r,o)=>{n+=` ${o} ${r}`}),`${t} ${s}${n}`}function ih(t,s=36,n=18){const a=[...t];return a.length<=s+n+1?t:`${a.slice(0,s).join("")}…${a.slice(-n).join("")}`}function In({value:t,headLength:s,tailLength:n,className:a,title:i}){const r=ih(t,s,n);return e.jsx("span",{className:a,title:i??t,children:r===t?t:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"sr-only",children:t}),e.jsx("span",{"aria-hidden":"true",children:r})]})})}function _n({rows:t,getSearchText:s,pageSize:n=Ht}){const[a,i]=d.useState(""),[r,o]=d.useState(1),l=d.useMemo(()=>ah(a),[a]),c=d.useMemo(()=>l.length===0||!s?t:t.filter(w=>{const b=s(w).toLocaleLowerCase();return l.every(A=>b.includes(A))}),[s,t,l]),u=Math.max(1,Math.ceil(c.length/n)),m=Math.min(Math.max(1,r),u),h=(m-1)*n,x=d.useMemo(()=>c.slice(h,h+n),[c,n,h]),N=d.useCallback(w=>{i(w),o(1)},[]),f=d.useCallback(w=>{o(Math.max(1,w))},[]);return{query:a,setQuery:N,page:m,setPage:f,rows:x,filteredRows:c,totalRows:c.length,totalPages:u,pageSize:n,rangeStart:c.length===0?0:h+1,rangeEnd:h+x.length,hasQuery:a.trim().length>0}}function Ys({value:t,onChange:s,label:n,placeholder:a="Filter rows",className:i}){return e.jsxs("div",{className:`relative ${i??""}`,children:[e.jsx(pi,{"aria-hidden":"true",className:"pointer-events-none absolute left-3 top-1/2 size-3.5 -translate-y-1/2 text-muted"}),e.jsx("input",{type:"search",value:t,onChange:r=>s(r.target.value),"aria-label":n,placeholder:a,autoComplete:"off",spellCheck:!1,className:"h-9 w-full rounded-md border border-default bg-surface/50 pl-9 pr-9 text-sm text-strong placeholder:text-muted outline-none transition focus:border-mono-500 focus:ring-1 focus:ring-mono-500 [&::-webkit-search-cancel-button]:appearance-none"}),t.trim().length>0?e.jsx("button",{type:"button",onClick:()=>s(""),"aria-label":`Clear ${n.toLocaleLowerCase()}`,className:"absolute right-2 top-1/2 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded text-muted transition-colors hover:bg-surface-hover hover:text-strong focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",children:e.jsx(Au,{"aria-hidden":"true",className:"size-3.5"})}):null]})}function Ts({page:t,pageSize:s=Ht,visibleRows:n,totalRows:a,hasNextPage:i,onPageChange:r,itemLabel:o="rows",className:l,disabled:c=!1}){if(n===0)return null;const u=(t-1)*s+1,m=u+n-1,h=a===void 0?void 0:Math.max(1,Math.ceil(a/s)),x=i??(h!==void 0&&t<h),N=t>1||x;return e.jsxs("div",{className:`mt-3 flex flex-wrap items-center justify-between gap-x-4 gap-y-2 text-xs text-secondary ${l??""}`,children:[e.jsxs("p",{className:"tabular-nums",children:[u.toLocaleString("en-US"),"–",m.toLocaleString("en-US"),a===void 0?`${x?"+":""} ${o}`:` of ${a.toLocaleString("en-US")} ${o}`]}),N?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>r(t-1),disabled:c||t<=1,className:"inline-flex items-center gap-1 rounded-md border border-base bg-bg px-2.5 py-1.5 text-strong transition hover:border-strong hover:text-primary disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-base disabled:hover:text-strong",children:[e.jsx($u,{"aria-hidden":"true",className:"size-3.5"}),"Previous"]}),e.jsx("span",{className:"tabular-nums",children:h===void 0?`Page ${t}`:`Page ${t} of ${h}`}),e.jsxs("button",{type:"button",onClick:()=>r(t+1),disabled:c||!x,className:"inline-flex items-center gap-1 rounded-md border border-base bg-bg px-2.5 py-1.5 text-strong transition hover:border-strong hover:text-primary disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-base disabled:hover:text-strong",children:["Next",e.jsx(qn,{"aria-hidden":"true",className:"size-3.5"})]})]}):null]})}function Zi({history:t,maxDots:s=12}){const n=t.slice(-s);if(n.length===0)return e.jsx("span",{className:"text-[11px] text-faint",children:"No data"});const a={cited:"bg-positive-400","not-cited":"bg-mono-600",lost:"bg-negative-400",emerging:"bg-caution-400 ring-1 ring-caution-300/60"},i={cited:"rounded-full","not-cited":"rounded-sm",lost:"rotate-45 rounded-[1px]",emerging:"rounded-full"},r=n.length-1,o=new Date(n[0].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),l=new Date(n[r].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),c=n.map((u,m)=>{const h=new Date(u.createdAt).toLocaleDateString();return`${m===r?"Latest run, ":""}${h}: ${u.citationState}${u.model?`, model ${u.model}`:""}`}).join("; ");return e.jsxs("div",{className:"flex items-center gap-1",role:"img","aria-label":`Citation history across ${n.length} runs. ${c}`,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((u,m)=>{const h=!!(u.model&&m>0&&n[m-1]?.model&&n[m-1].model!==u.model),x=m===r;return e.jsx("span",{className:`h-2.5 w-2.5 ${i[u.citationState]??"rounded-sm"} ${a[u.citationState]??"bg-mono-700"} ${h?"ring-1 ring-caution-300/80 ring-offset-1 ring-offset-bg":""} ${x?"outline outline-1 outline-offset-2 outline-mono-400":""}`,title:[u.citationState,new Date(u.createdAt).toLocaleDateString(),u.model?`model ${u.model}`:null,h?"model changed":null,x?"latest run":null].filter(Boolean).join(" · ")},`${u.runId}:${u.createdAt}`)})}),e.jsxs("span",{className:"text-[9px] shrink-0 text-secondary","aria-hidden":"true",children:[l," ",e.jsx("span",{className:"text-faint",children:"latest"})]})]})}function ei(t){const s=new Map;for(const a of t)for(const i of a.runHistory){const r=s.get(i.createdAt);r?r.states.push(i.citationState):s.set(i.createdAt,{states:[i.citationState],runId:i.runId})}return[...s.entries()].sort(([a],[i])=>a.localeCompare(i)).map(([a,{states:i,runId:r}])=>({runId:r,createdAt:a,citationState:i.includes("cited")?"cited":i.includes("emerging")?"emerging":"not-cited"}))}const rh=320;function oh(t){return[t.phrase,t.location??"",...t.rawItems.map(s=>s.provider)].join(" ")}function er(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 tr(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 sr(t,s){const n=s==="mentions"?"mentioned":"cited",a=s==="mentions"?"Mentioned":"Cited";if(t.length===0)return"Awaiting first run";if(t.length===1)return"First observation";const i=t[t.length-1].citationState,r=t[t.length-2].citationState;if(r!=="cited"&&i==="cited")return`Newly ${n}`;if(r==="cited"&&i!=="cited")return"Lost since last run";let o=0;for(let l=t.length-1;l>=0&&t[l].citationState===i;l--)o++;return i==="cited"?o<=1?`${a} in latest run`:`${a} for ${o} runs`:o<=1?`Not ${n} in latest run`:`Not ${n} across ${o} runs`}function lh(t,s){return t.map(n=>Ao(n,s))}function Ao(t,s){return s==="citations"?t:{...t,citationState:er(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:er(n,s)}))}}function nr(t,s){const n=s==="mentions"?"mention":"citation",a=s==="mentions"?"Mention":"Citation";if(t.length===0)return{key:s,label:`${a} pending`,tone:"pending"};const i=t[t.length-1].citationState,r=t.length>=2?t[t.length-2].citationState:null,o=i==="cited"||i==="emerging",l=r==="cited"||r==="emerging";return i==="lost"||r!==null&&l&&!o?{key:s,label:`Lost ${n}`,tone:"negative"}:i==="emerging"||r!==null&&!l&&o?{key:s,label:`New ${n}`,tone:"positive"}:r===null&&o?{key:s,label:`First ${n}`,tone:"positive"}:o?{key:s,label:s==="mentions"?"Still mentioned":"Still cited",tone:"neutral"}:{key:s,label:`No ${n}`,tone:"neutral"}}function ch(t){const s=ei(lh(t,"mentions")),n=ei(t);return[nr(s,"mentions"),nr(n,"citations")]}function dh({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 ar({items:t}){return e.jsx("div",{className:"mt-1 flex flex-wrap gap-1","aria-label":"Latest run mention and citation signals",children:ch(t).map(s=>e.jsx(dh,{signal:s},s.key))})}function uh({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:a}=to(),[i,r]=d.useState(new Set),[o,l]=d.useState("mentions"),[c,u]=d.useState(n),m=d.useMemo(()=>{const T=new Map;for(const P of t){const j=P.query,p=s?P.location??null:null,y=s?JSON.stringify([j,p]):j,v=T.get(y)??{key:y,phrase:j,location:p,items:[],rawItems:[]};v.items.push(Ao(P,o)),v.rawItems.push(P),T.set(y,v)}return[...T.values()]},[t,o,s]),h=_n({rows:m,getSearchText:oh}),x=h.rows.map(T=>T.key),N=x.length>0&&x.every(T=>i.has(T)),f=T=>{r(P=>{const j=new Set(P);return j.has(T)?j.delete(T):j.add(T),j})},w=o==="mentions"?"mentioned":"cited",b=o==="mentions"?"Mention History":"Citation History",A=o==="mentions"?"mentioned":"cited";return e.jsxs("div",{children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"View by"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-bg-elevated/60 border border-subtle",role:"tablist","aria-label":"Citation tracking view",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":o==="mentions",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${o==="mentions"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>l("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:()=>l("citations"),children:"Citations"})]}),e.jsx("span",{className:"text-[11px] text-muted",children:o==="mentions"?"Brand or domain in answer text":"Brand or domain in source links"}),e.jsxs("div",{className:"ml-auto flex items-center gap-3",children:[e.jsx("button",{type:"button",className:"text-[11px] text-secondary hover:text-strong",onClick:()=>{r(T=>{const P=new Set(T);for(const j of x)N?P.delete(j):P.add(j);return P})},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":c==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${c==="compact"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>u("compact"),children:"Compact"}),e.jsx("button",{type:"button",role:"tab","aria-selected":c==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${c==="detailed"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>u("detailed"),children:"Detailed"})]})]})]})]}),m.length>0?e.jsx(Ys,{value:h.query,onChange:h.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:b}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:h.rows.map(({key:T,phrase:P,location:j,items:p,rawItems:y})=>{const v=i.has(T),D=p.map(C=>C.citationState),q=D.includes("cited")?"cited":D.includes("emerging")?"emerging":D.includes("lost")?"lost":D.every(C=>C==="pending")?"pending":"not-cited",S=ei(p),k=p.filter(C=>C.citationState===Dl.cited||C.citationState==="emerging").length,F=sr(S,o);return e.jsxs(d.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(T),onKeyDown:C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),f(T))},tabIndex:0,role:"button","aria-expanded":v,children:[e.jsx("td",{children:e.jsx(qn,{size:14,className:`transition-transform duration-150 text-muted ${v?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-heading",children:P}),s&&e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-muted",children:j??"No location"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:p.map(C=>e.jsx(Zs,{provider:C.provider},C.id))})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Za,{state:q,label:tr(q,o)}),e.jsxs("span",{className:"text-[11px] text-muted",title:`${k} of ${p.length} engines ${A}`,children:[k,"/",p.length]})]})}),e.jsx("td",{children:e.jsx(Zi,{history:S})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:F}),e.jsx(ar,{items:y})]}),e.jsx("td",{})]}),v&&p.map((C,I)=>e.jsxs(d.Fragment,{children:[e.jsxs("tr",{className:"bg-surface",children:[e.jsx("td",{}),e.jsx("td",{className:"evidence-query-cell pl-5",children:e.jsx(Zs,{provider:C.provider})}),e.jsx("td",{children:e.jsx(Za,{state:C.citationState,label:tr(C.citationState,o)})}),e.jsx("td",{children:e.jsx(Zi,{history:C.runHistory})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:sr(C.runHistory,o)}),e.jsx(ar,{items:[y[I]??C]})]}),e.jsx("td",{children:e.jsx(L,{variant:"ghost",size:"sm",type:"button",onClick:me=>{me.stopPropagation(),a(C.id)},children:"View"})})]}),c==="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(ph,{item:C,onViewFull:()=>a(C.id)})})]})]},C.id))]},T)})})]})}),h.totalRows===0&&h.hasQuery?e.jsx("p",{className:"supporting-copy mt-3",children:"No tracked queries match this filter."}):null,e.jsx(Ts,{page:h.page,pageSize:h.pageSize,visibleRows:h.rows.length,totalRows:h.totalRows,onPageChange:h.setPage,itemLabel:h.hasQuery?"matches":"queries"}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",w==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function hh(t){const s=(t.matchedTerms??[]).filter(i=>i.trim().length>2),n=[...t.competitorDomains.flatMap(i=>{const r=Ml(i);return r.length>=4?[r]:[]}),...t.recommendedCompetitors??[]].filter(i=>i.trim().length>2),a=[];return s.length>0&&a.push({terms:s,className:"answer-highlight-brand"}),n.length>0&&a.push({terms:n,className:"answer-highlight-competitor"}),a}function mh(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 ph({item:t,onViewFull:s}){if(!(t.answerSnippet.trim().length>0))return e.jsx("p",{className:"text-[11px] text-muted italic",children:"No answer text captured for this run."});const{body:a,truncated:i}=mh(t.answerSnippet,rh),r=hh(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:Tl(a,r)}),(t.citedDomains.length>0||t.competitorDomains.length>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[t.citedDomains.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Cited:"}),t.citedDomains.slice(0,6).map(o=>e.jsx("span",{className:"rounded-full border border-mono-700/60 bg-bg-elevated/60 px-2 py-0.5 text-[11px] text-neutral",children:o},`c-${o}`)),t.citedDomains.length>6&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.citedDomains.length-6," more"]})]}),t.competitorDomains.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-negative-500/80",children:"Competitors:"}),t.competitorDomains.slice(0,4).map(o=>e.jsx("span",{className:"rounded-full border border-negative-900/40 bg-negative-950/30 px-2 py-0.5 text-[11px] text-negative",children:o},`co-${o}`)),t.competitorDomains.length>4&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.competitorDomains.length-4," more"]})]})]}),i&&e.jsx("button",{type:"button",className:"text-[11px] font-medium text-positive-400 hover:text-positive",onClick:o=>{o.stopPropagation(),s()},children:"View full answer →"})]})}function xh({competitors:t,onSelectCompetitor:s,onRemoveCompetitor:n,activeFilter:a}){if(t.length===0)return e.jsx("p",{className:"text-sm text-muted",children:"No competitors configured. Add competitors to track overlap."});const i=s!=null,r=n!=null;return e.jsx("div",{className:"competitor-table-wrap",children:e.jsxs("table",{className:"competitor-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Domain"}),e.jsx("th",{children:"Pressure"}),e.jsx("th",{children:"Citations"}),e.jsx("th",{children:"Queries"}),r&&e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{children:t.map(o=>{const l=a!=null&&a.toLowerCase()===o.domain.toLowerCase(),c=[i?"cursor-pointer hover:bg-mono-800/30 transition-colors":"",l?"bg-negative-950/20":""].filter(Boolean).join(" ");return e.jsxs("tr",{className:c,onClick:i?()=>s(o.domain):void 0,title:i?`Filter answers to queries where ${o.domain} surfaced`:void 0,children:[e.jsx("td",{className:"font-medium text-heading",children:o.domain}),e.jsx("td",{children:e.jsx(oe,{tone:_l(o.pressureLabel),children:o.pressureLabel})}),e.jsx("td",{className:"text-neutral tabular-nums",children:o.totalQueries>0?`${o.citationCount} / ${o.totalQueries}`:"—"}),e.jsx("td",{className:"text-muted text-xs",children:o.citedQueries.length>0?o.citedQueries.join(", "):"Not cited"}),r&&e.jsx("td",{className:"text-right",children:e.jsx("button",{type:"button",className:"rounded px-1.5 py-0.5 text-xs text-muted transition-colors hover:text-negative-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-negative-500","aria-label":`Remove competitor ${o.domain}`,title:`Remove ${o.domain}`,onClick:u=>{u.stopPropagation(),n(o.domain)},children:"Remove"})})]},o.id)})})]})})}function Hn({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 gh=6,ln="__other__",Xs="_socialTotal";function fh(t,s=gh){const n=new Map;for(const m of t)n.set(m.source,(n.get(m.source)??0)+m.sessions);const a=[...n.entries()].sort((m,h)=>h[1]!==m[1]?h[1]-m[1]:m[0].localeCompare(h[0])),i=a.slice(0,s),r=new Set(i.map(([m])=>m)),o=Math.max(0,a.length-s),l=new Map;for(const m of t){let h=l.get(m.date);h||(h={date:m.date,[Xs]:0},l.set(m.date,h));const x=r.has(m.source)?m.source:ln;h[x]=(h[x]??0)+m.sessions,h[Xs]=(h[Xs]??0)+m.sessions}const c=[...l.values()].sort((m,h)=>String(m.date).localeCompare(String(h.date))),u=i.map(([m])=>m);return o>0&&u.push(ln),{data:c,sources:u,otherCount:o}}function Js(t){return t.replace(/\+/g," ")}function $o(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const ir="_totalSessions",rr="_organicSessions";function bh(t,s){const n=new Map;for(const o of s)n.set(o.date,{[ir]:o.sessions,[rr]:o.organicSessions});for(const o of t.days){let l=n.get(o.date);l||(l={[ir]:0,[rr]:0},n.set(o.date,l));for(const c of o.bySource)l[c.source]=(l[c.source]??0)+c.sessions}const a=[...n.entries()].sort(([o],[l])=>o.localeCompare(l)).map(([o,l])=>({date:o,...l})),i=a.map(o=>o.date),r=i.length>0?{start:i[0],end:i[i.length-1]}:null;return{data:a,sources:t.sources,dateRange:r}}const yh=["7d","30d","90d","all"],ys=kt,ti=Ct.textDim,Po=Ct.textFaint,jn=25;function vh(t){return Co(t.landingPage)}const jh=25,Pa={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0};function Wn(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function Ro(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 Nh({projectName:t}){const{data:s,isLoading:n,isError:a}=Gu(t);if(n)return e.jsx(ye,{className:"p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading server activity…"})});if(a)return e.jsx(ye,{className:"p-5",children:e.jsx("div",{className:"text-sm text-negative-400",children:"Failed to load server activity."})});const i=s?.sources??[];return e.jsxs("section",{children:[e.jsx("div",{className:"flex items-baseline justify-between mb-3",children:e.jsxs("div",{children:[e.jsx("div",{className:"eyebrow",children:"Server activity (last 24h)"}),e.jsx("h2",{className:"text-lg font-semibold text-primary",children:"Server activity"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["Crawler, AI fetch, and referral activity from connected sources."," ",!ie()&&e.jsx(ts,{to:"/traffic",className:"text-link hover:underline",children:"Manage sources →"})]})]})}),i.length===0?e.jsx(ye,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-secondary",children:["No server traffic source connected yet."," ",!ie()&&e.jsxs(e.Fragment,{children:[e.jsx(ts,{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(ye,{className:"overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-bg-elevated/50 text-[10px] uppercase tracking-wide text-muted",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Source"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Status"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Crawler hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI sessions 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Last sync"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium","aria-label":"open"})]})}),e.jsx("tbody",{children:i.map(r=>e.jsxs("tr",{className:"border-t border-default",children:[e.jsx("td",{className:"px-4 py-3 text-heading",children:r.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(oe,{tone:Ou(r.status),children:r.status})}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:r.totals24h.crawlerHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:r.totals24h.aiUserFetchHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:r.totals24h.aiReferralHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right text-secondary text-xs",children:r.lastSyncedAt?Ro(r.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:ie()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(ts,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:r.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},r.id))})]})})]})}function wh({projectName:t}){return e.jsxs("div",{className:"space-y-10",children:[e.jsx(Nh,{projectName:t}),e.jsx(Sh,{projectName:t})]})}function Sh({projectName:t}){const s=Ss(),[n,a]=d.useState(null),[i,r]=d.useState(null),[o,l]=d.useState(!0),[c,u]=d.useState(!1),[m,h]=d.useState(!1),[x,N]=d.useState(null),[f,w]=d.useState(null),[b,A]=d.useState("sessions"),[T,P]=d.useState("desc"),[j,p]=d.useState("sessions"),[y,v]=d.useState("desc"),[D,q]=d.useState("sessions"),[S,k]=d.useState("desc"),[F,C]=d.useState("sessions"),[I,me]=d.useState("desc"),[pe,J]=d.useState(Pa),[ne,Z]=d.useState([]),[Q,V]=d.useState([]),[$,te]=d.useState(!1),[ce,re]=d.useState("30d");async function Y(K){l(!0),N(null);try{const Ie=await s.fetchQuery({...Gl({client:H,path:{name:t}}),staleTime:yn});if(K.current)return;if(a(Ie),!Ie.connected){r(null),J(Pa),Z([]),V([]),l(!1);return}const ve=ce==="all"?void 0:ce,[Ae,Ze,ms,dt]=await Promise.all([s.fetchQuery({...Ol({client:H,path:{name:t},query:ve?{window:ve}:void 0}),staleTime:yn}).then(ns=>ns),s.fetchQuery({...ql({client:H,path:{name:t},query:ve?{window:ve}:void 0}),staleTime:yn}).catch(()=>Pa),s.fetchQuery({...Fl({client:H,path:{name:t},query:ve?{window:ve}:void 0}),staleTime:yn}).catch(()=>[]),s.fetchQuery({...Ul({client:H,path:{name:t},query:ve?{window:ve}:void 0}),staleTime:yn}).catch(()=>[])]);if(K.current)return;r(Ae),J(Ze),Z(ms),V(dt),l(!1)}catch(Ie){if(K.current)return;N(Ie instanceof Error?Ie.message:"Failed to load GA4 data"),l(!1)}}d.useEffect(()=>{const K={current:!1};return Y(K),()=>{K.current=!0}},[t,ce,s]);async function fe(){u(!0),N(null),w(null);try{const K=await so(t);w(`Synced ${K.rowCount.toLocaleString()} page rows, ${K.aiReferralCount.toLocaleString()} AI and ${K.socialReferralCount.toLocaleString()} social referral rows (${K.days} days)`),await pt(s,"ga"),await Y({current:!1})}catch(K){N(K instanceof Error?K.message:"Sync failed")}finally{u(!1)}}async function U(){h(!0),N(null),w(null);try{await zl(t),await pt(s,"ga"),a({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),r(null),w("GA4 disconnected")}catch(K){N(K instanceof Error?K.message:"Disconnect failed")}finally{h(!1)}}function be(K){b===K?P(Ie=>Ie==="desc"?"asc":"desc"):(A(K),P("desc"))}function Ce(K){j===K?v(Ie=>Ie==="desc"?"asc":"desc"):(p(K),v("desc"))}function G(K){D===K?k(Ie=>Ie==="desc"?"asc":"desc"):(q(K),k("desc"))}const Ee=d.useMemo(()=>i?.topPages?[...i.topPages].sort((K,Ie)=>{const ve=K[b],Ae=Ie[b];return typeof ve=="string"&&typeof Ae=="string"?T==="asc"?ve.localeCompare(Ae):Ae.localeCompare(ve):T==="asc"?ve-Ae:Ae-ve}):[],[i?.topPages,b,T]),Re=d.useMemo(()=>i?.aiReferrals?[...i.aiReferrals].sort((K,Ie)=>{const ve=K[j],Ae=Ie[j];return typeof ve=="string"&&typeof Ae=="string"?y==="asc"?ve.localeCompare(Ae):Ae.localeCompare(ve):y==="asc"?ve-Ae:Ae-ve}):[],[i?.aiReferrals,j,y]),M=d.useMemo(()=>i?.aiReferralLandingPages?[...i.aiReferralLandingPages].sort((K,Ie)=>{const ve=K[F],Ae=Ie[F];return typeof ve=="string"&&typeof Ae=="string"?I==="asc"?ve.localeCompare(Ae):Ae.localeCompare(ve):I==="asc"?ve-Ae:Ae-ve}):[],[i?.aiReferralLandingPages,F,I]),de=_n({rows:M,getSearchText:vh,pageSize:jh}),ke=de.totalRows>0?`${de.totalRows.toLocaleString()} ${de.hasQuery?de.totalRows===1?"match":"matches":de.totalRows===1?"row":"rows"}`:de.hasQuery&&(i?.aiReferralLandingPages.length??0)>0?"0 matches":"No landing-page rows";function Oe(K){de.setPage(1),F===K?me(Ie=>Ie==="desc"?"asc":"desc"):(C(K),me("desc"))}const Me=d.useMemo(()=>i?.socialReferrals?[...i.socialReferrals].sort((K,Ie)=>{const ve=K[D],Ae=Ie[D];return typeof ve=="string"&&typeof Ae=="string"?S==="asc"?ve.localeCompare(Ae):Ae.localeCompare(ve):S==="asc"?ve-Ae:Ae-ve}):[],[i?.socialReferrals,D,S]),{socialChartData:W,socialChartSources:X,socialOtherCount:Ne}=d.useMemo(()=>{const K=fh(Q);return{socialChartData:K.data,socialChartSources:K.sources,socialOtherCount:K.otherCount}},[Q]),{chartData:O,chartSources:E,dateRange:z}=d.useMemo(()=>{const K=bh(pe,ne);return{chartData:K.data,chartSources:K.sources,dateRange:K.dateRange}},[pe,ne]);if(o&&!n)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!n?.connected)return ie()?e.jsx(ye,{className:"p-5",children:e.jsx("div",{className:"text-sm text-secondary",children:"No Google Analytics 4 property connected yet."})}):e.jsx(kh,{projectName:t,onConnected:()=>{(async()=>(await pt(s,"ga"),await Y({current:!1})))()}});const Se=i?.organicSharePctDisplay??"0%",Qe=i?.channelBreakdown?.organic.sharePctDisplay??Se,qe=i?.channelBreakdown?.organic.sessions??i?.totalOrganicSessions??0,Ye=i?.aiSessionsDeduped??0,$t=i?.channelBreakdown?.ai.sessions??i?.aiSessionsBySession??0,At=i?.channelBreakdown?.ai.sharePctDisplay??i?.aiSharePctBySessionDisplay??"0%",_e=i?.paidAiSessionsBySession??0,Ke=i?.paidAiSharePctBySessionDisplay??"0%",it=i?new Set(i.aiReferrals.map(K=>K.source.toLowerCase())).size:0,lt=Re[0]??null,ze=i?.totalDirectSessions??0,ct=i?.directSharePctDisplay??"0%",Pt=i?.channelBreakdown?.direct.sessions??ze,Ft=i?.channelBreakdown?.direct.sharePctDisplay??ct,Ge=i?.channelBreakdown?.other.sessions??i?.otherSessions??0,Be=i?.channelBreakdown?.other.sharePctDisplay??i?.otherSharePctDisplay??"0%",xt=i?.socialSessions??0,He=i?.socialSharePctDisplay??"0%",Ut=i?.channelBreakdown?.social.sessions??xt,Dt=i?.channelBreakdown?.social.sharePctDisplay??He,tt=i?new Set(i.socialReferrals.map(K=>K.source.toLowerCase())).size:0,Je=Me[0]??null;return e.jsxs(e.Fragment,{children:[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}),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})]})]})]}),!ie()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(L,{variant:"outline",size:"sm",disabled:c,onClick:Ue(fe),children:[e.jsx(Is,{className:`w-3.5 h-3.5 mr-1.5 ${c?"animate-spin":""}`}),c?"Syncing…":"Sync"]}),e.jsxs(L,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:m,onClick:Ue(U),children:[e.jsx(Pu,{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(at,{text:`Aggregated traffic metrics from Google Analytics 4. Sessions and users are summed across the selected period.${i?.periodStart&&i?.periodEnd?` Data available: ${new Date(i.periodStart+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})} – ${new Date(i.periodEnd+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}.`:""} Organic sessions are Google organic search sessions specifically.`})]})]}),e.jsx("div",{className:"segmented",role:"group","aria-label":"Traffic time period",children:yh.map(K=>e.jsx("button",{type:"button","aria-pressed":ce===K,className:`segmented-option ${ce===K?"segmented-option-active":""}`,onClick:()=>re(K),children:K==="all"?"All":K},K))})]}),i?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(Ra,{value:Wn(i.totalSessions),label:"Total Sessions",subtitle:i.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(Ra,{value:Wn(i.totalOrganicSessions),label:"Organic Sessions",subtitle:`${Se} of total`,tone:"positive"}),e.jsx(Ra,{value:Wn(i.totalUsers),label:"Total Users",subtitle:i.totalUsers.toLocaleString(),tone:"neutral"})]}):e.jsxs("div",{className:"surface-card rounded-lg p-6 text-center border border-default",children:[e.jsx("p",{className:"text-sm text-secondary mb-3",children:"No traffic data yet."}),!ie()&&e.jsxs(L,{variant:"outline",size:"sm",disabled:c,onClick:Ue(fe),children:[e.jsx(Is,{className:`w-3.5 h-3.5 mr-1.5 ${c?"animate-spin":""}`}),"Sync from GA4"]})]})]}),i&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Traffic Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Traffic by channel",e.jsx(at,{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."})]})]}),z&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(z.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(z.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),O.length>0&&e.jsxs(ye,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:E.length>0?"AI vs. total sessions":"All sessions (baseline)"}),E.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),E.length===0&&e.jsx("p",{className:"text-xs text-muted",children:"No AI referrals detected yet"})]}),e.jsx("div",{className:"h-64",children:e.jsx(sn,{width:"100%",height:"100%",children:e.jsxs(nn,{data:O,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(an,{dataKey:"date",tick:Ot,tickLine:!1,axisLine:{stroke:us},tickFormatter:Ja}),e.jsx(rn,{tick:Ot,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(on,{...Ds,labelFormatter:pa,formatter:(K,Ie)=>{const ve=typeof K=="number"?K.toLocaleString():String(K??0),Ae=String(Ie??"");return Ae==="_totalSessions"?[ve,"Total Sessions"]:Ae==="_organicSessions"?[ve,"Organic Sessions"]:[ve,Ae]}}),e.jsx(yo,{wrapperStyle:{fontSize:11,color:Ct.text},formatter:K=>K==="_totalSessions"?"Total Sessions":K==="_organicSessions"?"Organic Sessions":K}),e.jsx(Qs,{type:"monotone",dataKey:"_totalSessions",stroke:Ct.textFaint,fill:Ct.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),E.map((K,Ie)=>e.jsx(Qs,{type:"monotone",dataKey:K,stackId:"ai",stroke:ys[Ie%ys.length],fill:ys[Ie%ys.length],fillOpacity:.4,strokeWidth:1.5},K))]})})})]}),e.jsxs(ye,{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(Vt,{label:"Organic",value:Qe,hint:`${qe.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(Vt,{label:"Social",value:Dt,hint:`${Ut.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(Vt,{label:"Direct",value:Ft,hint:`${Pt.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(Vt,{label:"Known AI referrers (lower bound)",value:At,hint:_e>0?`${$t.toLocaleString()} sessions · ${_e.toLocaleString()} paid`:`${$t.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(Vt,{label:"Other channels",value:Be,hint:`${Ge.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."})]}),lt&&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:lt.source})," via ",lt.medium,", accounting for ",lt.sessions.toLocaleString()," sessions.",_e>0&&e.jsxs("span",{children:[" Paid AI: ",_e.toLocaleString()," sessions (",Ke,")."]})]})]}),e.jsxs(ye,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Detail"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Known AI referrers by source"})]}),e.jsx("p",{className:"text-xs text-muted",children:i.aiReferrals.length>0?`${it} unique sources, ${i.aiReferrals.length} rows`:"No source rows"})]}),i.aiReferrals.length>0?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(Et,{label:"Source",sortKey:"source",current:j,dir:y,onSort:Ce,align:"left"}),e.jsx(Et,{label:"Medium",sortKey:"medium",current:j,dir:y,onSort:Ce,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(Et,{label:"Sessions",sortKey:"sessions",current:j,dir:y,onSort:Ce,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:Re.map(K=>e.jsx(Ah,{referral:K,totalSessions:Ye},`${K.source}:${K.medium}:${K.sourceDimension}`))})]})}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No AI referrer sessions detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"AI engines that preserve a referrer (Perplexity, copy/paste from ChatGPT, etc.) will appear here. Most AI traffic strips the referrer — see the Direct cell above for the upper bound."})]})]}),e.jsxs(ye,{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:ke})]}),i.aiReferralLandingPages.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Ys,{value:de.query,onChange:de.setQuery,label:"Filter landing page URLs or query parameters",placeholder:"Filter URL or query parameters",className:"mb-4 max-w-md"}),de.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(Et,{label:"Landing Page",sortKey:"landingPage",current:F,dir:I,onSort:Oe,align:"left"}),e.jsx(Et,{label:"Source",sortKey:"source",current:F,dir:I,onSort:Oe,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(Et,{label:"Sessions",sortKey:"sessions",current:F,dir:I,onSort:Oe,align:"right"})]})}),e.jsx("tbody",{children:de.rows.map(K=>e.jsx($h,{row:K},`${K.landingPage}:${K.source}:${K.medium}:${K.sourceDimension}`))})]})}),e.jsx(Ts,{page:de.page,pageSize:de.pageSize,visibleRows:de.rows.length,totalRows:de.totalRows,onPageChange:de.setPage,itemLabel:de.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:()=>de.setQuery(""),className:"mt-2 text-xs text-link hover:underline focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",children:"Clear filter"})]})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No AI landing pages detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"Known-AI landing pages appear after a GA4 sync records visits from AI referrers."})]})]})]})]}),i&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Social Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Social Media Traffic",e.jsx(at,{text:"Tracks sessions classified as social traffic by GA4's default channel grouping (Organic Social and Paid Social). Google maintains the source-to-channel mapping."})]})]}),W.length>0&&e.jsxs(ye,{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"})]}),Ne>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",X.length-1," sources · ",Ne," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(sn,{width:"100%",height:"100%",children:e.jsxs(nn,{data:W,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(an,{dataKey:"date",tick:Ot,tickLine:!1,axisLine:{stroke:us},tickFormatter:Ja}),e.jsx(rn,{tick:Ot,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(on,{...Ds,labelFormatter:pa,formatter:(K,Ie)=>{const ve=typeof K=="number"?K.toLocaleString():String(K??0),Ae=String(Ie??"");if(Ae===Xs)return[ve,"Total Social"];if(Ae===ln){const Ze=`Other (${Ne} source${Ne===1?"":"s"})`;return[ve,Ze]}return[ve,Js(Ae)]}}),e.jsx(Qs,{type:"monotone",dataKey:Xs,stroke:Po,fill:Ct.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),X.map((K,Ie)=>{const Ae=K===ln?ti:ys[Ie%ys.length];return e.jsx(Qs,{type:"monotone",dataKey:K,stackId:"social",stroke:Ae,fill:Ae,fillOpacity:.4,strokeWidth:1.5},K)})]})})}),e.jsx(Rh,{sources:X,otherCount:Ne})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.5fr)]",children:[e.jsxs(ye,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Summary"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social media visits"})]}),i.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(Vt,{label:"Social Sessions",value:Wn(xt),hint:`${xt.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(Vt,{label:"Share of Traffic",value:He,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(Vt,{label:"Platforms",value:String(tt),hint:`${i.socialReferrals.length} source rows`,tone:"neutral",tooltip:"Number of distinct social media platforms detected. Each unique source/medium combination counts as one source row."})]}),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:$o(Js(Je.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:Je.medium,children:["via ",Js(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(Vt,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(Vt,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(Vt,{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(ye,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Breakdown"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Source / medium"})]}),e.jsx("p",{className:"text-xs text-muted",children:i.socialReferrals.length>0?Me.length>jn&&!$?`Top ${jn} of ${Me.length}`:`${Me.length} rows`:"No source rows"})]}),i.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm table-fixed",children:[e.jsxs("colgroup",{children:[e.jsx("col",{className:"w-[32%]"}),e.jsx("col",{className:"w-[22%]"}),e.jsx("col",{className:"w-[12%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[12%]"})]}),e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(Et,{label:"Source",sortKey:"source",current:D,dir:S,onSort:G,align:"left"}),e.jsx(Et,{label:"Medium",sortKey:"medium",current:D,dir:S,onSort:G,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(Et,{label:"Sessions",sortKey:"sessions",current:D,dir:S,onSort:G,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(Et,{label:"Users",sortKey:"users",current:D,dir:S,onSort:G,align:"right"})]})}),e.jsx("tbody",{children:($?Me:Me.slice(0,jn)).map(K=>e.jsx(Ph,{referral:K,totalSessions:xt},`${K.source}:${K.medium}:${K.channelGroup}`))})]})}),Me.length>jn&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>te(K=>!K),className:"rounded-md border border-base px-3 py-1.5 text-xs text-secondary transition-colors hover:border-strong hover:text-strong",children:$?`Show top ${jn}`:`Show all ${Me.length} sources`})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No social media sessions detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"When visitors arrive from Facebook, X/Twitter, LinkedIn, or other social platforms, their sessions will be broken down here by source and medium."})]})]})]})]})]}),i&&i.topPages.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Page Performance"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Top Landing Pages",e.jsx(at,{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(Et,{label:"Landing Page",sortKey:"landingPage",current:b,dir:T,onSort:be,align:"left"}),e.jsx(Et,{label:"Sessions",sortKey:"sessions",current:b,dir:T,onSort:be,align:"right"}),e.jsx(Et,{label:"Organic",sortKey:"organicSessions",current:b,dir:T,onSort:be,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"})]})}),e.jsx("tbody",{children:Ee.map(K=>e.jsx(Ch,{page:K},K.landingPage))})]})})]})]}),e.jsxs("div",{className:"mt-6 flex items-center justify-between text-xs text-muted",children:[e.jsx("span",{children:i?.lastSyncedAt?`Last synced ${Ro(i.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:i?`${i.topPages.length} pages · ${i.aiReferrals.length} AI rows · ${i.socialReferrals.length} social rows`:""})]})]})}function kh({projectName:t,onConnected:s}){const[n,a]=d.useState(""),[i,r]=d.useState(null),[o,l]=d.useState(null),[c,u]=d.useState(!1),[m,h]=d.useState(null),x=d.useRef(null),N=d.useCallback(w=>{const b=w.target.files?.[0];if(!b)return;h(null),r(b.name);const A=new FileReader;A.onload=()=>{const T=A.result;try{const P=JSON.parse(T);if(!P.client_email||!P.private_key){h("JSON file is missing required fields: client_email and private_key. Make sure you downloaded a service account key (not an OAuth client)."),l(null);return}l(T)}catch{h("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),l(null)}},A.onerror=()=>{h("Failed to read file."),l(null)},A.readAsText(b)},[]);async function f(){if(h(null),!n.trim()){h("Property ID is required.");return}if(!o){h("Please upload a service account key file.");return}u(!0);try{await Bl(t,{propertyId:n.trim(),keyJson:o});try{await so(t)}catch{}s()}catch(w){h(w instanceof Error?w.message:"Failed to connect GA4")}finally{u(!1)}}return e.jsxs(ye,{className:"surface-card p-6",children:[e.jsx("h3",{className:"text-base font-semibold text-primary mb-1",children:"Connect Google Analytics 4"}),e.jsx("p",{className:"text-sm text-secondary mb-5",children:"Connect a GA4 property to see traffic data for this project. You'll need a service account key file from Google Cloud Console."}),m&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative",children:m}),e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{htmlFor:"ga4-property-id",className:"block text-xs font-medium text-secondary mb-1.5",children:"GA4 Property ID"}),e.jsx("input",{id:"ga4-property-id",type:"text",placeholder:"e.g. 123456789",value:n,onChange:w=>a(w.target.value),className:"w-full rounded-lg bg-bg-elevated/60 border border-default px-3 py-2 text-sm text-strong placeholder-mono-600 focus:outline-none focus:ring-1 focus:ring-mono-600"}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:"Find this in GA4 → Admin → Property Settings. It's a numeric ID, not the Measurement ID (G-XXXXXX)."})]}),e.jsxs("div",{className:"mb-5",children:[e.jsx("label",{className:"block text-xs font-medium text-secondary mb-1.5",children:"Service Account Key File"}),e.jsx("input",{ref:x,type:"file",accept:".json,application/json",onChange:N,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>x.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(Ru,{className:"w-4 h-4 shrink-0"}),i?e.jsx("span",{className:"text-strong truncate",children:i}):e.jsx("span",{children:"Upload .json key file"})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Download from Google Cloud Console → IAM & Admin → Service Accounts → Keys → Add Key → JSON. The service account must have ",e.jsx("span",{className:"text-secondary",children:"Viewer"})," access on the GA4 property."]})]}),e.jsx(L,{variant:"default",size:"sm",disabled:c||!n.trim()||!o,onClick:Ue(f),children:c?"Connecting & syncing…":"Connect GA4"})]})}function Et({label:t,sortKey:s,current:n,dir:a,onSort:i,align:r}){const o=n===s;return e.jsx("th",{className:`py-1 ${r==="right"?"text-right":"text-left"}`,children:e.jsxs("button",{type:"button",className:"font-medium cursor-pointer select-none hover:text-neutral transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-400 rounded",onClick:()=>i(s),"aria-label":`Sort by ${t}${o?` (currently ${a==="asc"?"ascending":"descending"})`:""}`,children:[t,o&&e.jsx("span",{className:"ml-0.5",children:a==="asc"?"↑":"↓"})]})})}const Lo={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function Ra({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 ${Lo[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Vt({value:t,label:s,hint:n,tone:a,tooltip:i}){return e.jsxs("div",{className:"rounded-lg border border-default bg-bg/40 px-4 py-3 flex flex-col",children:[e.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1 flex items-center gap-1",children:[s,i&&e.jsx(at,{text:i})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${Lo[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Ch({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 Eo={session:"Session",first_user:"First Visit",manual_utm:"UTM"},Io={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 Ah({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=Eo[t.sourceDimension]??t.sourceDimension,i=Io[t.sourceDimension]??"",r=t.trafficClass==="paid"?"Paid":"Organic",o=t.trafficClass==="paid"?"Paid AI traffic inferred from paid/cpc/sponsored UTM values or a GA4 paid channel group":"AI traffic without a paid attribution signal";return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 text-strong max-w-[220px] truncate",title:t.source,children:t.source}),e.jsx("td",{className:"py-1.5 text-muted max-w-[180px] truncate",title:t.medium,children:t.medium}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:`inline-block text-[10px] px-1.5 py-0.5 rounded-full border ${t.trafficClass==="paid"?"border-caution-700 text-caution-300":"border-strong text-secondary"}`,title:o,children:r})}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:i,children:a})}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[n,"%"]})]})}function $h({row:t}){const s=Eo[t.sourceDimension]??t.sourceDimension,n=Io[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(In,{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 Ph({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=t.channelGroup==="Paid Social"?"Paid":"Organic",i=Js(t.source),r=Js(t.medium);return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 pr-3 text-strong truncate",title:t.source,children:i}),e.jsx("td",{className:"py-1.5 pr-3 text-muted truncate",title:t.medium,children:r}),e.jsx("td",{className:"py-1.5 pr-3",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:`GA4 channel group: ${t.channelGroup}`,children:a})}),e.jsx("td",{className:"py-1.5 text-right text-info-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[n,"%"]}),e.jsx("td",{className:"py-1.5 text-right text-strong tabular-nums",children:t.users.toLocaleString()})]})}function Rh({sources:t,otherCount:s}){const n=[{key:Xs,color:Po,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const i=t[a];if(i===ln)n.push({key:ln,color:ti,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const r=Js(i);n.push({key:i,color:ys[a%ys.length]??ti,label:$o(r,32),tooltip:r})}}return e.jsx("div",{className:"mt-3 flex flex-wrap gap-x-4 gap-y-1.5 text-[11px] text-secondary",children:n.map(a=>e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 max-w-[260px]",title:a.tooltip,children:[e.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-sm shrink-0",style:{backgroundColor:a.color},"aria-hidden":"true"}),e.jsx("span",{className:"truncate",children:a.label})]},a.key))})}function Lh(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 Eh=["7d","30d","90d","all"],Yn=500,fs=25,Ih="canonry:google-oauth-complete";function or(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function lr(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 cr(t){return t.isPending?"Processing":Number(t.errors??0)>0?"Errors":Number(t.warnings??0)>0?"Warnings":"Success"}function Dh({projectName:t,refreshNonce:s}){const n=Ss(),[a,i]=d.useState(!1),[r,o]=d.useState([]),[l,c]=d.useState([]),[u,m]=d.useState([]),[h,x]=d.useState(null),[N,f]=d.useState([]),[w,b]=d.useState([]),[A,T]=d.useState(null),[P,j]=d.useState(""),[p,y]=d.useState(""),[v,D]=d.useState("30"),[q,S]=d.useState(!1),[k,F]=d.useState("30d"),[C,I]=d.useState({startDate:"",endDate:"",query:"",page:""}),[me,pe]=d.useState(0),[J,ne]=d.useState(!1),[Z,Q]=d.useState(0),[V,$]=d.useState(!1),[te,ce]=d.useState(""),[re,Y]=d.useState(!0),[fe,U]=d.useState(!1),[be,Ce]=d.useState(!1),[G,Ee]=d.useState(!1),[Re,M]=d.useState(!1),[de,ke]=d.useState(!1),[Oe,Me]=d.useState(!1),[W,X]=d.useState(null),[Ne,O]=d.useState(!1),[E,z]=d.useState(!1),[Se,Qe]=d.useState(null),[qe,Ye]=d.useState(null),[$t,At]=d.useState([]),[_e,Ke]=d.useState(new Set),[it,lt]=d.useState({}),[ze,ct]=d.useState(new Set),[Pt,Ft]=d.useState(""),[Ge,Be]=d.useState(null),[xt,He]=d.useState(""),[Ut,Dt]=d.useState(!1),[tt,Je]=d.useState(!1),[K,Ie]=d.useState(!1),[ve,Ae]=d.useState(!1),[Ze,ms]=d.useState("indexed"),[dt,ns]=d.useState(null),Wt=!!(C.query.trim()||C.page.trim()||dt),pn=dt!==null,_s=d.useMemo(()=>{if(!dt)return u;const{key:g,dir:B}=dt;return[...u].sort((ue,ge)=>{const Fe=g===Ls.CTR?Number.isFinite(ue.ctr)?ue.ctr:0:ue[g],Ve=g===Ls.CTR?Number.isFinite(ge.ctr)?ge.ctr:0:ge[g];return B==="asc"?Fe-Ve:Ve-Fe})},[u,dt]),Yt=_n({rows:_s,pageSize:Ht}),Gs=V?Yt.rows:_s,Xt=_n({rows:(Se??[]).filter(g=>g.path.toLowerCase().includes(Pt.trim().toLowerCase())),pageSize:Ht}),[jt,Os]=d.useState([]),[vt,ht]=d.useState(null),[xn,qs]=d.useState(1),as=d.useMemo(()=>{if(jt.length<2)return null;const g=jt[jt.length-1],B=jt[jt.length-2];return{indexed:g.indexed-B.indexed,notIndexed:g.notIndexed-B.notIndexed}},[jt]);d.useEffect(()=>{qs(1)},[W,Ze,vt]);const ps=d.useMemo(()=>vt?(W?.reasonGroups??[]).find(g=>g.reason===vt):void 0,[W,vt]),Jt=d.useMemo(()=>W?Ze==="indexed"?W.indexed:Ze==="deindexed"?W.deindexed:Ze==="notIndexed"?vt?ps?.urls??[]:(W.reasonGroups??[]).length===0?W.notIndexed:[]:[]:[],[W,Ze,vt,ps]),gn=Math.max(1,Math.ceil(Jt.length/fs)),R=Math.min(Math.max(1,xn),gn),xe=(R-1)*fs,Pe=d.useMemo(()=>W?.indexed.slice(xe,xe+fs)??[],[W,xe]),zt=d.useMemo(()=>W?.notIndexed.slice(xe,xe+fs)??[],[W,xe]),Rt=d.useMemo(()=>W?.deindexed.slice(xe,xe+fs)??[],[W,xe]),_=d.useMemo(()=>(ps?.urls??[]).slice(xe,xe+fs),[ps,xe]),[ae,je]=d.useState(!1),[he,se]=d.useState(null),[Le,Bt]=d.useState(null),[gt,Lt]=d.useState(null);function xs(g,B){const ue=qu(g),ge=Lh(ue);ge?(Bt(ge),se(null)):(Bt(null),se(ue.message||B))}const ft=r.find(g=>g.connectionType==="gsc"),ks=(ft?.scopes??[]).includes("https://www.googleapis.com/auth/webmasters"),va=$t.length>0?$t:(Se??[]).map(g=>g.path),Di=va.filter(g=>Se?.some(B=>B.path===g&&B.isSitemapsIndex)).length,yl=Di===1?"Resubmit sitemap index":Di>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",vl=u.length>0||N.length>0||w.length>0,ja=Kl(),Na=Vl();async function Ti(g,B=!1){if(!g){c([]),j("");return}Ce(!0);try{const{sites:ue}=await n.fetchQuery({...ic({client:H,path:{name:t}}),staleTime:B?0:bt});c(ue),j(g.propertyId??ue[0]?.siteUrl??""),Bt(null)}catch(ue){c([]),xs(ue,"Failed to load Search Console properties")}finally{Ce(!1)}}async function fn(g){M(!0);const B=g??me;try{const ue=Wt?Yn:Ht,ge=Wt?0:B,Fe={limit:String(ue)};C.startDate&&(Fe.startDate=C.startDate),C.endDate&&(Fe.endDate=C.endDate),C.query&&(Fe.query=C.query),C.page&&(Fe.page=C.page),ge>0&&(Fe.offset=String(ge)),k&&k!=="all"&&!C.startDate&&(Fe.window=k);const Ve=await n.fetchQuery({...Hl({client:H,path:{name:t},query:Fe}),staleTime:bt}),We=Ve.rows;Wt?(ne(!1),m(We),Q(We.length),$(!0)):(ne(ge+We.length<Ve.totalMatching),m(We),Q(0),$(!1))}catch(ue){m([]),ne(!1),Q(0),se(ue instanceof Error?ue.message:"Failed to load GSC performance data")}finally{M(!1)}}async function wa(){try{const g={};C.startDate&&(g.startDate=C.startDate),C.endDate&&(g.endDate=C.endDate),k&&k!=="all"&&!C.startDate&&(g.window=k);const B=await n.fetchQuery({...Wl({client:H,path:{name:t},query:g}),staleTime:bt});x(B)}catch{x(null)}}async function zn(g=!1){ke(!0);try{const B=te.trim()||void 0,ue={limit:"20"};B&&(ue.url=B);const[ge,Fe]=await Promise.all([n.fetchQuery({...nc({client:H,path:{name:t},query:ue}),staleTime:g?0:bt}),n.fetchQuery({...ac({client:H,path:{name:t}}),staleTime:g?0:bt})]);f(ge),b(Fe)}catch(B){f([]),b([]),se(B instanceof Error?B.message:"Failed to load GSC inspection history")}finally{ke(!1)}}async function Mi(g=!1){O(!0);try{const[B,ue]=await Promise.all([n.fetchQuery({...ao({client:H,path:{name:t}}),staleTime:g?0:bt}),n.fetchQuery({...Jl({client:H,path:{name:t}}),staleTime:g?0:bt}).catch(()=>[])]);X(B),Os(ue)}catch(B){X(null),Os([]),se(B instanceof Error?B.message:"Failed to load coverage data")}finally{O(!1)}}async function _i(g){je(!0),se(null);try{const B=await Vi(t,{urls:g}),{succeeded:ue,failed:ge,total:Fe}=B.summary;$e({title:"Indexing requested",detail:ge===0?`${ue} URL${ue!==1?"s":""} submitted for indexing.`:`${ue}/${Fe} submitted successfully, ${ge} failed.`,tone:ge===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(B){se(B instanceof Error?B.message:"Failed to request indexing")}finally{je(!1)}}async function jl(){je(!0),se(null);try{const g=await Vi(t,{urls:[],allUnindexed:!0}),{succeeded:B,failed:ue,total:ge}=g.summary;$e({title:"Indexing requested",detail:ue===0?`${B} unindexed URL${B!==1?"s":""} submitted for indexing.`:`${B}/${ge} submitted successfully, ${ue} failed.`,tone:ue===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(g){se(g instanceof Error?g.message:"Failed to request indexing")}finally{je(!1)}}async function Sa(){z(!0),se(null);try{const g=await ka(t);n.setQueryData(Zl({client:H,path:{name:t}}),g),Qe(g.sitemaps),Ye(g.summary),At(g.preferredSubmissionUrls),Ke(new Set),lt({}),g.sitemaps.length===0&&Lt("No sitemaps found in this GSC property. Submit one here to start Google processing it.")}catch(g){se(g instanceof Error?g.message:"Failed to list sitemaps")}finally{z(!1)}}async function Nl(g){const B=_e.has(g);if(Ke(ue=>{const ge=new Set(ue);return B?ge.delete(g):ge.add(g),ge}),!(B||it[g])){ct(ue=>new Set(ue).add(g));try{const ue=await ka(t,g);lt(ge=>({...ge,[g]:ue.sitemaps}))}catch(ue){se(ue instanceof Error?ue.message:"Failed to load sitemap files")}finally{ct(ue=>{const ge=new Set(ue);return ge.delete(g),ge})}}}async function Fs(g){if(!ks||g.length===0)return;const B=[...new Set(g)];Je(!0),se(null),Be({completed:0,total:B.length});let ue=0,ge=0,Fe=0,Ve=null;try{for(let rt=0;rt<B.length;rt+=50){const Te=B.slice(rt,rt+50);try{const Nt=await ec(t,Te);ue+=Nt.summary.accepted,ge+=Nt.summary.failed,Fe+=Te.length,Be({completed:Fe,total:B.length})}catch(Nt){Fe+=Te.length;const Kt=Te.length,Cs=B.length-Fe,Us=Nt instanceof Error?Nt.message:"The batch request failed",bn=`${ue} accepted, ${ge} failed, ${Kt} unconfirmed, ${Cs} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;Ve=`Sitemap submission stopped after a batch request failed. ${bn} ${Us}`,se(Ve),$e({title:"Sitemap resubmission partially completed",detail:bn,tone:"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"});return}}const We=B.length;$e({title:ge===0?"Sitemap submitted to Google":"Some sitemap submissions need attention",detail:ge===0?"Google accepted the sitemap submission/refetch request; indexing is not guaranteed.":`Google accepted ${ue}/${We} sitemap submissions; ${ge} failed. Indexing is not guaranteed.`,tone:ge===0?"positive":"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"}),He("")}catch(We){se(We instanceof Error?We.message:"Failed to submit sitemap to Google")}finally{Je(!1),Be(null),await Sa(),Ve&&se(Ve)}}async function wl(){Je(!0);const g=Se??[];try{const B=g.filter(ge=>ge.isSitemapsIndex),ue=[];for(let ge=0;ge<B.length;ge+=4)(await Promise.all(B.slice(ge,ge+4).map(async Ve=>{const We=it[Ve.path];if(We)return We;const rt=await ka(t,Ve.path);return lt(Te=>({...Te,[Ve.path]:rt.sitemaps})),rt.sitemaps}))).forEach((Ve,We)=>{ue.push(...Ve.length>0?Ve.map(rt=>rt.path):[B[ge+We].path])});await Fs([...g.filter(ge=>!ge.isSitemapsIndex).map(ge=>ge.path),...ue])}catch(B){se(B instanceof Error?B.message:"Failed to load sitemap files"),Je(!1)}}async function Gi(g){Dt(!0),se(null);try{await tc(t,"gsc",g),await pt(n,"google"),o(B=>B.map(ue=>ue.connectionType==="gsc"?{...ue,sitemapUrl:g}:ue)),$e({title:"Default sitemap updated",detail:g,tone:"positive",dedupeKey:`gsc:sitemap-default:${t}`,dedupeMode:"replace"})}catch(B){se(B instanceof Error?B.message:"Failed to set the default sitemap")}finally{Dt(!1)}}async function Oi(g){try{await Na.mutateAsync({projectName:t,projectLabel:t,opts:g?{sitemapUrl:g}:void 0})}catch{}}async function qi(){Y(!0),se(null);try{const[g,B]=await Promise.all([no().catch(()=>null),n.fetchQuery({...hi({client:H,path:{name:t}}),staleTime:bt}).catch(()=>[])]);i(!!g?.google?.configured),o(B);const ue=B.find(ge=>ge.connectionType==="gsc");await Promise.all([Ti(ue),fn(),wa(),zn(),Mi(),ue?.propertyId?Sa():Promise.resolve()])}finally{Y(!1)}}d.useEffect(()=>{qi()},[t,s]),d.useEffect(()=>{pe(0),fn(0),wa()},[k]);const Fi=d.useRef(!1);d.useEffect(()=>{if(!Fi.current){Fi.current=!0;return}pe(0),fn(0)},[pn]);async function Ui(){if(!a){se("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}U(!0),se(null),Lt(null);try{let g=function(Nt){if(Nt.source!==ge||Nt.origin!==Fe||!Nt.data||typeof Nt.data!="object")return;const Kt=Nt.data;Kt.type!==Ih||Kt.connectionType!=="gsc"||Te(!0)};const{authUrl:B,redirectUri:ue}=await Xl(t,"gsc");if(!B.startsWith("https://accounts.google.com/")){se("Unexpected OAuth redirect URL. Please try again.");return}const ge=window.open(B,"_blank","width=600,height=700");if(!ge){window.location.assign(B);return}const Fe=ue?new URL(ue).origin:window.location.origin;let Ve=!1,We=null;const rt=()=>{We!==null&&window.clearInterval(We),window.removeEventListener("message",g)},Te=async Nt=>{if(!Ve){Ve=!0,rt(),Lt(Nt?"Google connected. Refreshing access…":"Refreshing Google connection…");try{await pt(n,"google"),await qi()}finally{Lt(null)}}};window.addEventListener("message",g),Lt("Finish the Google consent flow in the popup. This page will refresh automatically."),We=window.setInterval(()=>{ge.closed&&Te(!1)},1e3)}catch(g){se(g instanceof Error?g.message:"Failed to start OAuth flow")}finally{U(!1)}}async function Sl(){se(null),Lt(null);try{await Yl(t,"gsc"),await pt(n,"google"),o(g=>g.filter(B=>B.connectionType!=="gsc")),c([]),j("")}catch(g){se(g instanceof Error?g.message:"Failed to disconnect")}}async function kl(){if(P){Ee(!0),se(null);try{await rc(t,"gsc",P),await pt(n,"google"),o(g=>g.map(B=>B.connectionType==="gsc"?{...B,propertyId:P}:B)),$e({title:"GSC property updated",detail:`${t} is now linked to ${P}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(g){se(g instanceof Error?g.message:"Failed to save GSC property")}finally{Ee(!1)}}}async function Cl(){se(null),Lt(null);try{await ja.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(v,10)||void 0,full:q||void 0}}),await pt(n,"gsc")}catch{}}async function zi(){if(p.trim()){Me(!0),se(null),Lt(null);try{const g=await sc(t,p.trim());await pt(n,"gsc"),T(g),y(""),await zn()}catch(g){se(g instanceof Error?g.message:"Failed to inspect URL")}finally{Me(!1)}}}return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search Console"}),e.jsx("h2",{children:"Google Search Console"})]})}),Le&&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:Le.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:Le.message}),(Ps(Le.enableUrl)||Ps(Le.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[Ps(Le.enableUrl)&&e.jsx("a",{href:Ps(Le.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 ↗"}),Ps(Le.indexingApiUrl)&&e.jsx("a",{href:Ps(Le.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:()=>Bt(null),children:"×"})]})}),he&&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:[he,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>se(null),children:"×"})]}),gt&&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:[gt,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>Lt(null),children:"×"})]}),re?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[ft?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:ft.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Coverage measured"," ",W?.lastInspectedAt?es(W.lastInspectedAt):"never"]}),e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:Ue(Sl),children:"Disconnect"})]}):e.jsxs(ye,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(oe,{tone:a?"caution":"negative",children:a?"Ready to connect":"App credentials missing"})]}),e.jsxs("div",{className:"mt-3 rounded-lg border border-default bg-surface px-4 py-5",children:[e.jsx("p",{className:"text-sm text-neutral",children:a?"Generate a Google OAuth link for this project and have the client sign in with a Google account that already has access to the correct Search Console property.":"Set Google OAuth client credentials first. Once configured, you can generate a consent link for this project domain."}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[a?e.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:fe,onClick:Ue(Ui),children:fe?"Opening…":"Connect Google Search Console"}):e.jsx(L,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(ts,{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."})]})]})]}),(ft||vl)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs(ye,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Performance"}),e.jsx("h3",{children:"Search performance"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"segmented",role:"group","aria-label":"Performance time period",children:Eh.map(g=>e.jsx("button",{type:"button","aria-pressed":k===g,className:`segmented-option ${k===g?"segmented-option-active":""}`,onClick:()=>{F(g),pe(0),Yt.setPage(1)},children:g==="all"?"All":g},g))}),e.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:Re,onClick:()=>{pe(0),Yt.setPage(1),fn(0),wa()},children:Re?"Loading…":"Apply filters"})]})]}),h&&h.daily.length>0&&(()=>{const g=h.daily,B=Math.max(...g.map(et=>et.impressions),1),{clicks:ue,impressions:ge,ctr:Fe}=h.totals,Ve=(Fe*100).toFixed(1),We=700,rt=220,Te={top:12,bottom:36,left:48,right:12},Nt=We-Te.left-Te.right,Kt=rt-Te.top-Te.bottom,Cs=Nt/g.length,Us=Math.max(Math.min(Cs*.35,24),4),bn=Math.max(Us*.15,1),Al=et=>{if(et<=0)return 1;const is=Math.pow(10,Math.floor(Math.log10(et))),Tt=et/is,gs=Tt<=1.5?1.5:Tt<=3?3:Tt<=5?5:10;return Math.ceil(gs*is)},Bn=4,Kn=Math.ceil(Al(B)/Bn)*Bn,$l=Array.from({length:Bn+1},(et,is)=>Kn/Bn*is),Pl=et=>et>=1e3?`${(et/1e3).toFixed(et>=1e4?0:1)}k`:String(et);return e.jsxs("div",{className:"mt-3",children:[e.jsxs("div",{className:"flex items-center gap-5 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-sm bg-positive-500"}),e.jsxs("span",{className:"text-xs text-secondary",children:["Clicks ",e.jsx("span",{className:"text-strong tabular-nums font-medium",children:ue.toLocaleString()})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-sm bg-chart-series-2"}),e.jsxs("span",{className:"text-xs text-secondary",children:["Impressions ",e.jsx("span",{className:"text-strong tabular-nums font-medium",children:ge.toLocaleString()})]})]}),e.jsxs("span",{className:"text-xs text-muted",children:["CTR ",e.jsxs("span",{className:"text-caution-400 tabular-nums font-medium",children:[Ve,"%"]})]})]}),e.jsx("div",{className:"relative w-full",style:{aspectRatio:`${We} / ${rt}`},children:e.jsxs("svg",{viewBox:`0 0 ${We} ${rt}`,className:"h-full w-full",children:[$l.map((et,is)=>{const Tt=Te.top+Kt-et/Kn*Kt;return e.jsxs("g",{children:[e.jsx("line",{x1:Te.left,y1:Tt,x2:We-Te.right,y2:Tt,stroke:Ct.gridLine,strokeWidth:"1"}),e.jsx("text",{x:Te.left-6,y:Tt+3.5,textAnchor:"end",fill:Ct.text,fontSize:"10",fontFamily:"inherit",children:Pl(et)})]},`t-${is}`)}),g.map((et,is)=>{const Tt=Te.left+Cs*is+Cs/2,gs=et.impressions/Kn*Kt,Vn=et.clicks/Kn*Kt;return e.jsxs("g",{children:[e.jsx("title",{children:`${et.date}
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./react-sigma_core.esm.min-EzswMBkr.js","./vendor-tanstack-pFxw0eGP.js","./index-VO6nKq5b.js","./vendor-radix-BxMXSwbC.js","./vendor-recharts-C4ktw_aE.js","./vendor-lucide-BtYdosYk.js","./vendor-markdown-D274_wsI.js","./vendor-yaml-GWJz5H2G.js","./index-BxegEwic.css","./RunRow-Q2X0NR74.js","./ChartPrimitives-DXVLCdBi.js","./extract-error-message-BHm98tXH.js","./AuditHistoryPanel-D12lHs6n.js","./v2-overview-adapter-COMP5UGt.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{j as e,r as d,L as ts,n as Ss,u as De,o as Mn,B as ui,C as eo,D as Rl,h as Ll,k as Bi}from"./vendor-tanstack-pFxw0eGP.js";import{T as oe,t as El,a as Il,u as to,C as Dl,P as Zs,B as L,h as Tl,b as Ml,c as _l,d as ye,i as ie,e as pt,f as Ue,I as at,g as yn,j as Gl,k as H,l as Ol,m as ql,n as Fl,o as Ul,p as so,q as zl,r as Bl,S as Ls,s as Kl,v as Vl,w as Ps,x as es,y as Ql,z as Ki,A as no,G as bt,D as hi,E as Hl,F as Wl,H as Yl,J as Xl,K as Vi,L as $e,M as ao,N as Jl,O as ka,Q as Zl,R as ec,U as tc,V as sc,W as nc,X as ac,Y as ic,Z as rc,_ as oc,$ as lc,a0 as cc,a1 as dc,a2 as uc,a3 as hc,a4 as mc,a5 as pc,a6 as ws,a7 as xc,a8 as io,a9 as ha,aa as gc,ab as nt,ac as fc,ad as bc,ae as yc,af as ma,ag as vc,ah as jc,ai as Nc,aj as en,ak as wc,al as Sc,am as kc,an as ro,ao as Ya,ap as Cc,aq as oo,ar as Ac,as as $c,at as Pc,au as Rc,av as lo,aw as Lc,ax as Ec,ay as Ic,az as En,aA as Es,aB as Dc,aC as Tc,aD as Mc,aE as _c,aF as co,aG as Gc,aH as Oc,aI as qc,aJ as Fc,aK as vn,aL as Uc,aM as zc,aN as Bc,aO as mi,aP as uo,aQ as Kc,aR as Vc,aS as Qc,aT as Hc,aU as Wc,aV as Yc,aW as Xc,aX as Jc,aY as Zc,aZ as ed,a_ as td,a$ as st,b0 as sd,b1 as nd,b2 as ad,b3 as id,b4 as rd,b5 as od,b6 as ld,b7 as cd,b8 as dd,b9 as ud,ba as hd,bb as md,bc as pd,bd as xd,be as gd,bf as fd,bg as bd,bh as yd,bi as vd,bj as jd,bk as Nd,bl as wd,bm as Sd,bn as kd,bo as Cd,bp as Ad,bq as $d,br as Pd,bs as Rd,bt as Ld,bu as Ed,bv as Id,bw as Dd,bx as Td,by as Md,bz as _d,bA as Gd,bB as Od,bC as Ca,bD as qd,bE as Fd,bF as Qi,bG as Ud,bH as zd,bI as Bd,bJ as Kd,bK as Vd,bL as Qd,bM as Hd,bN as Wd,bO as Yd,bP as Xd,bQ as Jd,bR as Zd,bS as eu,bT as ho,bU as tu,bV as su,bW as nu,bX as au,bY as iu,bZ as ru,b_ as ou,b$ as Hi,c0 as lu,c1 as Aa,c2 as cu,c3 as du,c4 as uu,c5 as hu,c6 as mu,c7 as pu,c8 as xu,c9 as gu,ca as mo,cb as po,cc as fu,cd as bu,ce as yu,cf as vu,cg as ju,ch as Qn,ci as Nu,cj as wu,ck as Su,cl as Wi,cm as ku}from"./index-VO6nKq5b.js";import{R as Cu}from"./RunRow-Q2X0NR74.js";import{S as pi,X as Au,q as $u,e as qn,r as Is,U as Pu,s as Ru,L as It,t as xo,i as Lu,P as Ms,D as go,u as Eu,v as fo,E as bo,p as Iu,b as Du,T as Xa,w as Yi,C as tn,x as Tu,y as Mu}from"./vendor-lucide-BtYdosYk.js";import{f as Ja,C as us,a as Ot,b as pa,c as Ds,d as Ct,e as kt,g as cs,h as xi,i as gi,j as Ns,o as ss,p as _u}from"./ChartPrimitives-DXVLCdBi.js";import{u as Gu,t as Ou,e as qu,a as Xi}from"./extract-error-message-BHm98tXH.js";import{R as sn,C as nn,X as an,Y as rn,T as on,L as yo,A as Qs,a as fi,b as Fu,d as bi,e as Uu}from"./vendor-recharts-C4ktw_aE.js";import{A as zu}from"./AuditHistoryPanel-D12lHs6n.js";import{a as Bu,b as Ku}from"./v2-overview-adapter-COMP5UGt.js";function ca(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 Vu(t,s){return s<=0?null:Math.round((t-s)/s*100)}function $a(t,s,n="vs prior 7 days"){return t.deltaPct===null?t.prior===0?"First baseline week":"":t.deltaPct>0?`Up ${t.deltaPct}% ${n} (${ca(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${ca(t.prior)} ${s})`:`Flat ${n} (${ca(t.prior)} ${s})`}const vo=30;function Ji(t){return Math.round(t*10)/10}function Qu(t){return t.prior>=vo&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% vs prior`:`${t.deltaAbs>0?"+":""}${Ji(t.deltaAbs)} vs ${Ji(t.prior)}`}function Hu(t,s,n){return t.prior>=vo&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% ${n}`:`${t.deltaAbs>0?"+":""}${ca(Math.round(t.deltaAbs))} ${s} ${n}`}const Wu=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function jo(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function No(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 wo(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(jo).map(No).filter(Boolean)):new Set}function So(t,s){const n=jo(t).map(No).filter(Boolean).filter(a=>!Wu.has(a)).filter(a=>!s.has(a));return[...new Set(n)].sort().join(" ")}function Yu(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function Xu(t,s){const n=wo(t);if(s.length<=1||n.size===0)return[...s];const a=new Set,i=[];for(const r of s){if(r.category!=="content"){i.push(r);continue}const o=So(Yu(r),n);!o||a.has(o)||(a.add(o),i.push(r))}return i}function Ju(t){const s=wo(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const a=new Set;return n.filter(i=>{const r=So(i.query,s);return!r||a.has(r)?!1:(a.add(r),!0)})}const ko={queryClass:"all"},Zu=["all","non-brand","branded"];function eh(t){return typeof t=="string"&&Zu.includes(t)}function th(t){const s=eh(t.class)?t.class:ko.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 sh(t,s){return s===null||t===null?!1:t!==s}function nh(t){return{scope:t.scope==="group"&&t.groupKey?`group:${t.groupKey}`:void 0,class:t.queryClass===ko.queryClass?void 0:t.queryClass}}function Za({state:t,label:s}){return e.jsx(oe,{tone:Il(t),children:s??El(t)})}const Ht=25;function ah(t){return t.trim().toLocaleLowerCase().split(/\s+/).filter(Boolean)}function Co(t){let s=t;try{s=decodeURIComponent(t.replace(/\+/g," "))}catch{}let n="";const a=t.indexOf("?");return a>=0&&new URLSearchParams(t.slice(a+1)).forEach((r,o)=>{n+=` ${o} ${r}`}),`${t} ${s}${n}`}function ih(t,s=36,n=18){const a=[...t];return a.length<=s+n+1?t:`${a.slice(0,s).join("")}…${a.slice(-n).join("")}`}function In({value:t,headLength:s,tailLength:n,className:a,title:i}){const r=ih(t,s,n);return e.jsx("span",{className:a,title:i??t,children:r===t?t:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"sr-only",children:t}),e.jsx("span",{"aria-hidden":"true",children:r})]})})}function _n({rows:t,getSearchText:s,pageSize:n=Ht}){const[a,i]=d.useState(""),[r,o]=d.useState(1),l=d.useMemo(()=>ah(a),[a]),c=d.useMemo(()=>l.length===0||!s?t:t.filter(w=>{const b=s(w).toLocaleLowerCase();return l.every(A=>b.includes(A))}),[s,t,l]),u=Math.max(1,Math.ceil(c.length/n)),m=Math.min(Math.max(1,r),u),h=(m-1)*n,x=d.useMemo(()=>c.slice(h,h+n),[c,n,h]),N=d.useCallback(w=>{i(w),o(1)},[]),f=d.useCallback(w=>{o(Math.max(1,w))},[]);return{query:a,setQuery:N,page:m,setPage:f,rows:x,filteredRows:c,totalRows:c.length,totalPages:u,pageSize:n,rangeStart:c.length===0?0:h+1,rangeEnd:h+x.length,hasQuery:a.trim().length>0}}function Ys({value:t,onChange:s,label:n,placeholder:a="Filter rows",className:i}){return e.jsxs("div",{className:`relative ${i??""}`,children:[e.jsx(pi,{"aria-hidden":"true",className:"pointer-events-none absolute left-3 top-1/2 size-3.5 -translate-y-1/2 text-muted"}),e.jsx("input",{type:"search",value:t,onChange:r=>s(r.target.value),"aria-label":n,placeholder:a,autoComplete:"off",spellCheck:!1,className:"h-9 w-full rounded-md border border-default bg-surface/50 pl-9 pr-9 text-sm text-strong placeholder:text-muted outline-none transition focus:border-mono-500 focus:ring-1 focus:ring-mono-500 [&::-webkit-search-cancel-button]:appearance-none"}),t.trim().length>0?e.jsx("button",{type:"button",onClick:()=>s(""),"aria-label":`Clear ${n.toLocaleLowerCase()}`,className:"absolute right-2 top-1/2 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded text-muted transition-colors hover:bg-surface-hover hover:text-strong focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",children:e.jsx(Au,{"aria-hidden":"true",className:"size-3.5"})}):null]})}function Ts({page:t,pageSize:s=Ht,visibleRows:n,totalRows:a,hasNextPage:i,onPageChange:r,itemLabel:o="rows",className:l,disabled:c=!1}){if(n===0)return null;const u=(t-1)*s+1,m=u+n-1,h=a===void 0?void 0:Math.max(1,Math.ceil(a/s)),x=i??(h!==void 0&&t<h),N=t>1||x;return e.jsxs("div",{className:`mt-3 flex flex-wrap items-center justify-between gap-x-4 gap-y-2 text-xs text-secondary ${l??""}`,children:[e.jsxs("p",{className:"tabular-nums",children:[u.toLocaleString("en-US"),"–",m.toLocaleString("en-US"),a===void 0?`${x?"+":""} ${o}`:` of ${a.toLocaleString("en-US")} ${o}`]}),N?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>r(t-1),disabled:c||t<=1,className:"inline-flex items-center gap-1 rounded-md border border-base bg-bg px-2.5 py-1.5 text-strong transition hover:border-strong hover:text-primary disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-base disabled:hover:text-strong",children:[e.jsx($u,{"aria-hidden":"true",className:"size-3.5"}),"Previous"]}),e.jsx("span",{className:"tabular-nums",children:h===void 0?`Page ${t}`:`Page ${t} of ${h}`}),e.jsxs("button",{type:"button",onClick:()=>r(t+1),disabled:c||!x,className:"inline-flex items-center gap-1 rounded-md border border-base bg-bg px-2.5 py-1.5 text-strong transition hover:border-strong hover:text-primary disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-base disabled:hover:text-strong",children:["Next",e.jsx(qn,{"aria-hidden":"true",className:"size-3.5"})]})]}):null]})}function Zi({history:t,maxDots:s=12}){const n=t.slice(-s);if(n.length===0)return e.jsx("span",{className:"text-[11px] text-faint",children:"No data"});const a={cited:"bg-positive-400","not-cited":"bg-mono-600",lost:"bg-negative-400",emerging:"bg-caution-400 ring-1 ring-caution-300/60"},i={cited:"rounded-full","not-cited":"rounded-sm",lost:"rotate-45 rounded-[1px]",emerging:"rounded-full"},r=n.length-1,o=new Date(n[0].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),l=new Date(n[r].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),c=n.map((u,m)=>{const h=new Date(u.createdAt).toLocaleDateString();return`${m===r?"Latest run, ":""}${h}: ${u.citationState}${u.model?`, model ${u.model}`:""}`}).join("; ");return e.jsxs("div",{className:"flex items-center gap-1",role:"img","aria-label":`Citation history across ${n.length} runs. ${c}`,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((u,m)=>{const h=!!(u.model&&m>0&&n[m-1]?.model&&n[m-1].model!==u.model),x=m===r;return e.jsx("span",{className:`h-2.5 w-2.5 ${i[u.citationState]??"rounded-sm"} ${a[u.citationState]??"bg-mono-700"} ${h?"ring-1 ring-caution-300/80 ring-offset-1 ring-offset-bg":""} ${x?"outline outline-1 outline-offset-2 outline-mono-400":""}`,title:[u.citationState,new Date(u.createdAt).toLocaleDateString(),u.model?`model ${u.model}`:null,h?"model changed":null,x?"latest run":null].filter(Boolean).join(" · ")},`${u.runId}:${u.createdAt}`)})}),e.jsxs("span",{className:"text-[9px] shrink-0 text-secondary","aria-hidden":"true",children:[l," ",e.jsx("span",{className:"text-faint",children:"latest"})]})]})}function ei(t){const s=new Map;for(const a of t)for(const i of a.runHistory){const r=s.get(i.createdAt);r?r.states.push(i.citationState):s.set(i.createdAt,{states:[i.citationState],runId:i.runId})}return[...s.entries()].sort(([a],[i])=>a.localeCompare(i)).map(([a,{states:i,runId:r}])=>({runId:r,createdAt:a,citationState:i.includes("cited")?"cited":i.includes("emerging")?"emerging":"not-cited"}))}const rh=320;function oh(t){return[t.phrase,t.location??"",...t.rawItems.map(s=>s.provider)].join(" ")}function er(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 tr(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 sr(t,s){const n=s==="mentions"?"mentioned":"cited",a=s==="mentions"?"Mentioned":"Cited";if(t.length===0)return"Awaiting first run";if(t.length===1)return"First observation";const i=t[t.length-1].citationState,r=t[t.length-2].citationState;if(r!=="cited"&&i==="cited")return`Newly ${n}`;if(r==="cited"&&i!=="cited")return"Lost since last run";let o=0;for(let l=t.length-1;l>=0&&t[l].citationState===i;l--)o++;return i==="cited"?o<=1?`${a} in latest run`:`${a} for ${o} runs`:o<=1?`Not ${n} in latest run`:`Not ${n} across ${o} runs`}function lh(t,s){return t.map(n=>Ao(n,s))}function Ao(t,s){return s==="citations"?t:{...t,citationState:er(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:er(n,s)}))}}function nr(t,s){const n=s==="mentions"?"mention":"citation",a=s==="mentions"?"Mention":"Citation";if(t.length===0)return{key:s,label:`${a} pending`,tone:"pending"};const i=t[t.length-1].citationState,r=t.length>=2?t[t.length-2].citationState:null,o=i==="cited"||i==="emerging",l=r==="cited"||r==="emerging";return i==="lost"||r!==null&&l&&!o?{key:s,label:`Lost ${n}`,tone:"negative"}:i==="emerging"||r!==null&&!l&&o?{key:s,label:`New ${n}`,tone:"positive"}:r===null&&o?{key:s,label:`First ${n}`,tone:"positive"}:o?{key:s,label:s==="mentions"?"Still mentioned":"Still cited",tone:"neutral"}:{key:s,label:`No ${n}`,tone:"neutral"}}function ch(t){const s=ei(lh(t,"mentions")),n=ei(t);return[nr(s,"mentions"),nr(n,"citations")]}function dh({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 ar({items:t}){return e.jsx("div",{className:"mt-1 flex flex-wrap gap-1","aria-label":"Latest run mention and citation signals",children:ch(t).map(s=>e.jsx(dh,{signal:s},s.key))})}function uh({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:a}=to(),[i,r]=d.useState(new Set),[o,l]=d.useState("mentions"),[c,u]=d.useState(n),m=d.useMemo(()=>{const T=new Map;for(const P of t){const j=P.query,p=s?P.location??null:null,y=s?JSON.stringify([j,p]):j,v=T.get(y)??{key:y,phrase:j,location:p,items:[],rawItems:[]};v.items.push(Ao(P,o)),v.rawItems.push(P),T.set(y,v)}return[...T.values()]},[t,o,s]),h=_n({rows:m,getSearchText:oh}),x=h.rows.map(T=>T.key),N=x.length>0&&x.every(T=>i.has(T)),f=T=>{r(P=>{const j=new Set(P);return j.has(T)?j.delete(T):j.add(T),j})},w=o==="mentions"?"mentioned":"cited",b=o==="mentions"?"Mention History":"Citation History",A=o==="mentions"?"mentioned":"cited";return e.jsxs("div",{children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"View by"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-bg-elevated/60 border border-subtle",role:"tablist","aria-label":"Citation tracking view",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":o==="mentions",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${o==="mentions"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>l("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:()=>l("citations"),children:"Citations"})]}),e.jsx("span",{className:"text-[11px] text-muted",children:o==="mentions"?"Brand or domain in answer text":"Brand or domain in source links"}),e.jsxs("div",{className:"ml-auto flex items-center gap-3",children:[e.jsx("button",{type:"button",className:"text-[11px] text-secondary hover:text-strong",onClick:()=>{r(T=>{const P=new Set(T);for(const j of x)N?P.delete(j):P.add(j);return P})},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":c==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${c==="compact"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>u("compact"),children:"Compact"}),e.jsx("button",{type:"button",role:"tab","aria-selected":c==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${c==="detailed"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>u("detailed"),children:"Detailed"})]})]})]})]}),m.length>0?e.jsx(Ys,{value:h.query,onChange:h.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:b}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:h.rows.map(({key:T,phrase:P,location:j,items:p,rawItems:y})=>{const v=i.has(T),D=p.map(C=>C.citationState),q=D.includes("cited")?"cited":D.includes("emerging")?"emerging":D.includes("lost")?"lost":D.every(C=>C==="pending")?"pending":"not-cited",S=ei(p),k=p.filter(C=>C.citationState===Dl.cited||C.citationState==="emerging").length,F=sr(S,o);return e.jsxs(d.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(T),onKeyDown:C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),f(T))},tabIndex:0,role:"button","aria-expanded":v,children:[e.jsx("td",{children:e.jsx(qn,{size:14,className:`transition-transform duration-150 text-muted ${v?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-heading",children:P}),s&&e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-muted",children:j??"No location"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:p.map(C=>e.jsx(Zs,{provider:C.provider},C.id))})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Za,{state:q,label:tr(q,o)}),e.jsxs("span",{className:"text-[11px] text-muted",title:`${k} of ${p.length} engines ${A}`,children:[k,"/",p.length]})]})}),e.jsx("td",{children:e.jsx(Zi,{history:S})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:F}),e.jsx(ar,{items:y})]}),e.jsx("td",{})]}),v&&p.map((C,I)=>e.jsxs(d.Fragment,{children:[e.jsxs("tr",{className:"bg-surface",children:[e.jsx("td",{}),e.jsx("td",{className:"evidence-query-cell pl-5",children:e.jsx(Zs,{provider:C.provider})}),e.jsx("td",{children:e.jsx(Za,{state:C.citationState,label:tr(C.citationState,o)})}),e.jsx("td",{children:e.jsx(Zi,{history:C.runHistory})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:sr(C.runHistory,o)}),e.jsx(ar,{items:[y[I]??C]})]}),e.jsx("td",{children:e.jsx(L,{variant:"ghost",size:"sm",type:"button",onClick:me=>{me.stopPropagation(),a(C.id)},children:"View"})})]}),c==="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(ph,{item:C,onViewFull:()=>a(C.id)})})]})]},C.id))]},T)})})]})}),h.totalRows===0&&h.hasQuery?e.jsx("p",{className:"supporting-copy mt-3",children:"No tracked queries match this filter."}):null,e.jsx(Ts,{page:h.page,pageSize:h.pageSize,visibleRows:h.rows.length,totalRows:h.totalRows,onPageChange:h.setPage,itemLabel:h.hasQuery?"matches":"queries"}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",w==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function hh(t){const s=(t.matchedTerms??[]).filter(i=>i.trim().length>2),n=[...t.competitorDomains.flatMap(i=>{const r=Ml(i);return r.length>=4?[r]:[]}),...t.recommendedCompetitors??[]].filter(i=>i.trim().length>2),a=[];return s.length>0&&a.push({terms:s,className:"answer-highlight-brand"}),n.length>0&&a.push({terms:n,className:"answer-highlight-competitor"}),a}function mh(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 ph({item:t,onViewFull:s}){if(!(t.answerSnippet.trim().length>0))return e.jsx("p",{className:"text-[11px] text-muted italic",children:"No answer text captured for this run."});const{body:a,truncated:i}=mh(t.answerSnippet,rh),r=hh(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:Tl(a,r)}),(t.citedDomains.length>0||t.competitorDomains.length>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[t.citedDomains.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Cited:"}),t.citedDomains.slice(0,6).map(o=>e.jsx("span",{className:"rounded-full border border-mono-700/60 bg-bg-elevated/60 px-2 py-0.5 text-[11px] text-neutral",children:o},`c-${o}`)),t.citedDomains.length>6&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.citedDomains.length-6," more"]})]}),t.competitorDomains.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-negative-500/80",children:"Competitors:"}),t.competitorDomains.slice(0,4).map(o=>e.jsx("span",{className:"rounded-full border border-negative-900/40 bg-negative-950/30 px-2 py-0.5 text-[11px] text-negative",children:o},`co-${o}`)),t.competitorDomains.length>4&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.competitorDomains.length-4," more"]})]})]}),i&&e.jsx("button",{type:"button",className:"text-[11px] font-medium text-positive-400 hover:text-positive",onClick:o=>{o.stopPropagation(),s()},children:"View full answer →"})]})}function xh({competitors:t,onSelectCompetitor:s,onRemoveCompetitor:n,activeFilter:a}){if(t.length===0)return e.jsx("p",{className:"text-sm text-muted",children:"No competitors configured. Add competitors to track overlap."});const i=s!=null,r=n!=null;return e.jsx("div",{className:"competitor-table-wrap",children:e.jsxs("table",{className:"competitor-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Domain"}),e.jsx("th",{children:"Pressure"}),e.jsx("th",{children:"Citations"}),e.jsx("th",{children:"Queries"}),r&&e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{children:t.map(o=>{const l=a!=null&&a.toLowerCase()===o.domain.toLowerCase(),c=[i?"cursor-pointer hover:bg-mono-800/30 transition-colors":"",l?"bg-negative-950/20":""].filter(Boolean).join(" ");return e.jsxs("tr",{className:c,onClick:i?()=>s(o.domain):void 0,title:i?`Filter answers to queries where ${o.domain} surfaced`:void 0,children:[e.jsx("td",{className:"font-medium text-heading",children:o.domain}),e.jsx("td",{children:e.jsx(oe,{tone:_l(o.pressureLabel),children:o.pressureLabel})}),e.jsx("td",{className:"text-neutral tabular-nums",children:o.totalQueries>0?`${o.citationCount} / ${o.totalQueries}`:"—"}),e.jsx("td",{className:"text-muted text-xs",children:o.citedQueries.length>0?o.citedQueries.join(", "):"Not cited"}),r&&e.jsx("td",{className:"text-right",children:e.jsx("button",{type:"button",className:"rounded px-1.5 py-0.5 text-xs text-muted transition-colors hover:text-negative-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-negative-500","aria-label":`Remove competitor ${o.domain}`,title:`Remove ${o.domain}`,onClick:u=>{u.stopPropagation(),n(o.domain)},children:"Remove"})})]},o.id)})})]})})}function Hn({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 gh=6,ln="__other__",Xs="_socialTotal";function fh(t,s=gh){const n=new Map;for(const m of t)n.set(m.source,(n.get(m.source)??0)+m.sessions);const a=[...n.entries()].sort((m,h)=>h[1]!==m[1]?h[1]-m[1]:m[0].localeCompare(h[0])),i=a.slice(0,s),r=new Set(i.map(([m])=>m)),o=Math.max(0,a.length-s),l=new Map;for(const m of t){let h=l.get(m.date);h||(h={date:m.date,[Xs]:0},l.set(m.date,h));const x=r.has(m.source)?m.source:ln;h[x]=(h[x]??0)+m.sessions,h[Xs]=(h[Xs]??0)+m.sessions}const c=[...l.values()].sort((m,h)=>String(m.date).localeCompare(String(h.date))),u=i.map(([m])=>m);return o>0&&u.push(ln),{data:c,sources:u,otherCount:o}}function Js(t){return t.replace(/\+/g," ")}function $o(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const ir="_totalSessions",rr="_organicSessions";function bh(t,s){const n=new Map;for(const o of s)n.set(o.date,{[ir]:o.sessions,[rr]:o.organicSessions});for(const o of t.days){let l=n.get(o.date);l||(l={[ir]:0,[rr]:0},n.set(o.date,l));for(const c of o.bySource)l[c.source]=(l[c.source]??0)+c.sessions}const a=[...n.entries()].sort(([o],[l])=>o.localeCompare(l)).map(([o,l])=>({date:o,...l})),i=a.map(o=>o.date),r=i.length>0?{start:i[0],end:i[i.length-1]}:null;return{data:a,sources:t.sources,dateRange:r}}const yh=["7d","30d","90d","all"],ys=kt,ti=Ct.textDim,Po=Ct.textFaint,jn=25;function vh(t){return Co(t.landingPage)}const jh=25,Pa={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0};function Wn(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function Ro(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 Nh({projectName:t}){const{data:s,isLoading:n,isError:a}=Gu(t);if(n)return e.jsx(ye,{className:"p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading server activity…"})});if(a)return e.jsx(ye,{className:"p-5",children:e.jsx("div",{className:"text-sm text-negative-400",children:"Failed to load server activity."})});const i=s?.sources??[];return e.jsxs("section",{children:[e.jsx("div",{className:"flex items-baseline justify-between mb-3",children:e.jsxs("div",{children:[e.jsx("div",{className:"eyebrow",children:"Server activity (last 24h)"}),e.jsx("h2",{className:"text-lg font-semibold text-primary",children:"Server activity"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["Crawler, AI fetch, and referral activity from connected sources."," ",!ie()&&e.jsx(ts,{to:"/traffic",className:"text-link hover:underline",children:"Manage sources →"})]})]})}),i.length===0?e.jsx(ye,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-secondary",children:["No server traffic source connected yet."," ",!ie()&&e.jsxs(e.Fragment,{children:[e.jsx(ts,{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(ye,{className:"overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-bg-elevated/50 text-[10px] uppercase tracking-wide text-muted",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Source"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Status"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Crawler hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI sessions 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Last sync"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium","aria-label":"open"})]})}),e.jsx("tbody",{children:i.map(r=>e.jsxs("tr",{className:"border-t border-default",children:[e.jsx("td",{className:"px-4 py-3 text-heading",children:r.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(oe,{tone:Ou(r.status),children:r.status})}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:r.totals24h.crawlerHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:r.totals24h.aiUserFetchHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:r.totals24h.aiReferralHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right text-secondary text-xs",children:r.lastSyncedAt?Ro(r.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:ie()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(ts,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:r.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},r.id))})]})})]})}function wh({projectName:t}){return e.jsxs("div",{className:"space-y-10",children:[e.jsx(Nh,{projectName:t}),e.jsx(Sh,{projectName:t})]})}function Sh({projectName:t}){const s=Ss(),[n,a]=d.useState(null),[i,r]=d.useState(null),[o,l]=d.useState(!0),[c,u]=d.useState(!1),[m,h]=d.useState(!1),[x,N]=d.useState(null),[f,w]=d.useState(null),[b,A]=d.useState("sessions"),[T,P]=d.useState("desc"),[j,p]=d.useState("sessions"),[y,v]=d.useState("desc"),[D,q]=d.useState("sessions"),[S,k]=d.useState("desc"),[F,C]=d.useState("sessions"),[I,me]=d.useState("desc"),[pe,J]=d.useState(Pa),[ne,Z]=d.useState([]),[Q,V]=d.useState([]),[$,te]=d.useState(!1),[ce,re]=d.useState("30d");async function Y(K){l(!0),N(null);try{const Ie=await s.fetchQuery({...Gl({client:H,path:{name:t}}),staleTime:yn});if(K.current)return;if(a(Ie),!Ie.connected){r(null),J(Pa),Z([]),V([]),l(!1);return}const ve=ce==="all"?void 0:ce,[Ae,Ze,ms,dt]=await Promise.all([s.fetchQuery({...Ol({client:H,path:{name:t},query:ve?{window:ve}:void 0}),staleTime:yn}).then(ns=>ns),s.fetchQuery({...ql({client:H,path:{name:t},query:ve?{window:ve}:void 0}),staleTime:yn}).catch(()=>Pa),s.fetchQuery({...Fl({client:H,path:{name:t},query:ve?{window:ve}:void 0}),staleTime:yn}).catch(()=>[]),s.fetchQuery({...Ul({client:H,path:{name:t},query:ve?{window:ve}:void 0}),staleTime:yn}).catch(()=>[])]);if(K.current)return;r(Ae),J(Ze),Z(ms),V(dt),l(!1)}catch(Ie){if(K.current)return;N(Ie instanceof Error?Ie.message:"Failed to load GA4 data"),l(!1)}}d.useEffect(()=>{const K={current:!1};return Y(K),()=>{K.current=!0}},[t,ce,s]);async function fe(){u(!0),N(null),w(null);try{const K=await so(t);w(`Synced ${K.rowCount.toLocaleString()} page rows, ${K.aiReferralCount.toLocaleString()} AI and ${K.socialReferralCount.toLocaleString()} social referral rows (${K.days} days)`),await pt(s,"ga"),await Y({current:!1})}catch(K){N(K instanceof Error?K.message:"Sync failed")}finally{u(!1)}}async function U(){h(!0),N(null),w(null);try{await zl(t),await pt(s,"ga"),a({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),r(null),w("GA4 disconnected")}catch(K){N(K instanceof Error?K.message:"Disconnect failed")}finally{h(!1)}}function be(K){b===K?P(Ie=>Ie==="desc"?"asc":"desc"):(A(K),P("desc"))}function Ce(K){j===K?v(Ie=>Ie==="desc"?"asc":"desc"):(p(K),v("desc"))}function G(K){D===K?k(Ie=>Ie==="desc"?"asc":"desc"):(q(K),k("desc"))}const Ee=d.useMemo(()=>i?.topPages?[...i.topPages].sort((K,Ie)=>{const ve=K[b],Ae=Ie[b];return typeof ve=="string"&&typeof Ae=="string"?T==="asc"?ve.localeCompare(Ae):Ae.localeCompare(ve):T==="asc"?ve-Ae:Ae-ve}):[],[i?.topPages,b,T]),Re=d.useMemo(()=>i?.aiReferrals?[...i.aiReferrals].sort((K,Ie)=>{const ve=K[j],Ae=Ie[j];return typeof ve=="string"&&typeof Ae=="string"?y==="asc"?ve.localeCompare(Ae):Ae.localeCompare(ve):y==="asc"?ve-Ae:Ae-ve}):[],[i?.aiReferrals,j,y]),M=d.useMemo(()=>i?.aiReferralLandingPages?[...i.aiReferralLandingPages].sort((K,Ie)=>{const ve=K[F],Ae=Ie[F];return typeof ve=="string"&&typeof Ae=="string"?I==="asc"?ve.localeCompare(Ae):Ae.localeCompare(ve):I==="asc"?ve-Ae:Ae-ve}):[],[i?.aiReferralLandingPages,F,I]),de=_n({rows:M,getSearchText:vh,pageSize:jh}),ke=de.totalRows>0?`${de.totalRows.toLocaleString()} ${de.hasQuery?de.totalRows===1?"match":"matches":de.totalRows===1?"row":"rows"}`:de.hasQuery&&(i?.aiReferralLandingPages.length??0)>0?"0 matches":"No landing-page rows";function Oe(K){de.setPage(1),F===K?me(Ie=>Ie==="desc"?"asc":"desc"):(C(K),me("desc"))}const Me=d.useMemo(()=>i?.socialReferrals?[...i.socialReferrals].sort((K,Ie)=>{const ve=K[D],Ae=Ie[D];return typeof ve=="string"&&typeof Ae=="string"?S==="asc"?ve.localeCompare(Ae):Ae.localeCompare(ve):S==="asc"?ve-Ae:Ae-ve}):[],[i?.socialReferrals,D,S]),{socialChartData:W,socialChartSources:X,socialOtherCount:Ne}=d.useMemo(()=>{const K=fh(Q);return{socialChartData:K.data,socialChartSources:K.sources,socialOtherCount:K.otherCount}},[Q]),{chartData:O,chartSources:E,dateRange:z}=d.useMemo(()=>{const K=bh(pe,ne);return{chartData:K.data,chartSources:K.sources,dateRange:K.dateRange}},[pe,ne]);if(o&&!n)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!n?.connected)return ie()?e.jsx(ye,{className:"p-5",children:e.jsx("div",{className:"text-sm text-secondary",children:"No Google Analytics 4 property connected yet."})}):e.jsx(kh,{projectName:t,onConnected:()=>{(async()=>(await pt(s,"ga"),await Y({current:!1})))()}});const Se=i?.organicSharePctDisplay??"0%",Qe=i?.channelBreakdown?.organic.sharePctDisplay??Se,qe=i?.channelBreakdown?.organic.sessions??i?.totalOrganicSessions??0,Ye=i?.aiSessionsDeduped??0,$t=i?.channelBreakdown?.ai.sessions??i?.aiSessionsBySession??0,At=i?.channelBreakdown?.ai.sharePctDisplay??i?.aiSharePctBySessionDisplay??"0%",_e=i?.paidAiSessionsBySession??0,Ke=i?.paidAiSharePctBySessionDisplay??"0%",it=i?new Set(i.aiReferrals.map(K=>K.source.toLowerCase())).size:0,lt=Re[0]??null,ze=i?.totalDirectSessions??0,ct=i?.directSharePctDisplay??"0%",Pt=i?.channelBreakdown?.direct.sessions??ze,Ft=i?.channelBreakdown?.direct.sharePctDisplay??ct,Ge=i?.channelBreakdown?.other.sessions??i?.otherSessions??0,Be=i?.channelBreakdown?.other.sharePctDisplay??i?.otherSharePctDisplay??"0%",xt=i?.socialSessions??0,He=i?.socialSharePctDisplay??"0%",Ut=i?.channelBreakdown?.social.sessions??xt,Dt=i?.channelBreakdown?.social.sharePctDisplay??He,tt=i?new Set(i.socialReferrals.map(K=>K.source.toLowerCase())).size:0,Je=Me[0]??null;return e.jsxs(e.Fragment,{children:[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}),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})]})]})]}),!ie()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(L,{variant:"outline",size:"sm",disabled:c,onClick:Ue(fe),children:[e.jsx(Is,{className:`w-3.5 h-3.5 mr-1.5 ${c?"animate-spin":""}`}),c?"Syncing…":"Sync"]}),e.jsxs(L,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:m,onClick:Ue(U),children:[e.jsx(Pu,{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(at,{text:`Aggregated traffic metrics from Google Analytics 4. Sessions and users are summed across the selected period.${i?.periodStart&&i?.periodEnd?` Data available: ${new Date(i.periodStart+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})} – ${new Date(i.periodEnd+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}.`:""} Organic sessions are Google organic search sessions specifically.`})]})]}),e.jsx("div",{className:"segmented",role:"group","aria-label":"Traffic time period",children:yh.map(K=>e.jsx("button",{type:"button","aria-pressed":ce===K,className:`segmented-option ${ce===K?"segmented-option-active":""}`,onClick:()=>re(K),children:K==="all"?"All":K},K))})]}),i?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(Ra,{value:Wn(i.totalSessions),label:"Total Sessions",subtitle:i.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(Ra,{value:Wn(i.totalOrganicSessions),label:"Organic Sessions",subtitle:`${Se} of total`,tone:"positive"}),e.jsx(Ra,{value:Wn(i.totalUsers),label:"Total Users",subtitle:i.totalUsers.toLocaleString(),tone:"neutral"})]}):e.jsxs("div",{className:"surface-card rounded-lg p-6 text-center border border-default",children:[e.jsx("p",{className:"text-sm text-secondary mb-3",children:"No traffic data yet."}),!ie()&&e.jsxs(L,{variant:"outline",size:"sm",disabled:c,onClick:Ue(fe),children:[e.jsx(Is,{className:`w-3.5 h-3.5 mr-1.5 ${c?"animate-spin":""}`}),"Sync from GA4"]})]})]}),i&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Traffic Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Traffic by channel",e.jsx(at,{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."})]})]}),z&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(z.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(z.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),O.length>0&&e.jsxs(ye,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:E.length>0?"AI vs. total sessions":"All sessions (baseline)"}),E.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),E.length===0&&e.jsx("p",{className:"text-xs text-muted",children:"No AI referrals detected yet"})]}),e.jsx("div",{className:"h-64",children:e.jsx(sn,{width:"100%",height:"100%",children:e.jsxs(nn,{data:O,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(an,{dataKey:"date",tick:Ot,tickLine:!1,axisLine:{stroke:us},tickFormatter:Ja}),e.jsx(rn,{tick:Ot,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(on,{...Ds,labelFormatter:pa,formatter:(K,Ie)=>{const ve=typeof K=="number"?K.toLocaleString():String(K??0),Ae=String(Ie??"");return Ae==="_totalSessions"?[ve,"Total Sessions"]:Ae==="_organicSessions"?[ve,"Organic Sessions"]:[ve,Ae]}}),e.jsx(yo,{wrapperStyle:{fontSize:11,color:Ct.text},formatter:K=>K==="_totalSessions"?"Total Sessions":K==="_organicSessions"?"Organic Sessions":K}),e.jsx(Qs,{type:"monotone",dataKey:"_totalSessions",stroke:Ct.textFaint,fill:Ct.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),E.map((K,Ie)=>e.jsx(Qs,{type:"monotone",dataKey:K,stackId:"ai",stroke:ys[Ie%ys.length],fill:ys[Ie%ys.length],fillOpacity:.4,strokeWidth:1.5},K))]})})})]}),e.jsxs(ye,{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(Vt,{label:"Organic",value:Qe,hint:`${qe.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(Vt,{label:"Social",value:Dt,hint:`${Ut.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(Vt,{label:"Direct",value:Ft,hint:`${Pt.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(Vt,{label:"Known AI referrers (lower bound)",value:At,hint:_e>0?`${$t.toLocaleString()} sessions · ${_e.toLocaleString()} paid`:`${$t.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(Vt,{label:"Other channels",value:Be,hint:`${Ge.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."})]}),lt&&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:lt.source})," via ",lt.medium,", accounting for ",lt.sessions.toLocaleString()," sessions.",_e>0&&e.jsxs("span",{children:[" Paid AI: ",_e.toLocaleString()," sessions (",Ke,")."]})]})]}),e.jsxs(ye,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Detail"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Known AI referrers by source"})]}),e.jsx("p",{className:"text-xs text-muted",children:i.aiReferrals.length>0?`${it} unique sources, ${i.aiReferrals.length} rows`:"No source rows"})]}),i.aiReferrals.length>0?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(Et,{label:"Source",sortKey:"source",current:j,dir:y,onSort:Ce,align:"left"}),e.jsx(Et,{label:"Medium",sortKey:"medium",current:j,dir:y,onSort:Ce,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(Et,{label:"Sessions",sortKey:"sessions",current:j,dir:y,onSort:Ce,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:Re.map(K=>e.jsx(Ah,{referral:K,totalSessions:Ye},`${K.source}:${K.medium}:${K.sourceDimension}`))})]})}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No AI referrer sessions detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"AI engines that preserve a referrer (Perplexity, copy/paste from ChatGPT, etc.) will appear here. Most AI traffic strips the referrer — see the Direct cell above for the upper bound."})]})]}),e.jsxs(ye,{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:ke})]}),i.aiReferralLandingPages.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Ys,{value:de.query,onChange:de.setQuery,label:"Filter landing page URLs or query parameters",placeholder:"Filter URL or query parameters",className:"mb-4 max-w-md"}),de.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(Et,{label:"Landing Page",sortKey:"landingPage",current:F,dir:I,onSort:Oe,align:"left"}),e.jsx(Et,{label:"Source",sortKey:"source",current:F,dir:I,onSort:Oe,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(Et,{label:"Sessions",sortKey:"sessions",current:F,dir:I,onSort:Oe,align:"right"})]})}),e.jsx("tbody",{children:de.rows.map(K=>e.jsx($h,{row:K},`${K.landingPage}:${K.source}:${K.medium}:${K.sourceDimension}`))})]})}),e.jsx(Ts,{page:de.page,pageSize:de.pageSize,visibleRows:de.rows.length,totalRows:de.totalRows,onPageChange:de.setPage,itemLabel:de.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:()=>de.setQuery(""),className:"mt-2 text-xs text-link hover:underline focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",children:"Clear filter"})]})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No AI landing pages detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"Known-AI landing pages appear after a GA4 sync records visits from AI referrers."})]})]})]})]}),i&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Social Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Social Media Traffic",e.jsx(at,{text:"Tracks sessions classified as social traffic by GA4's default channel grouping (Organic Social and Paid Social). Google maintains the source-to-channel mapping."})]})]}),W.length>0&&e.jsxs(ye,{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"})]}),Ne>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",X.length-1," sources · ",Ne," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(sn,{width:"100%",height:"100%",children:e.jsxs(nn,{data:W,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(an,{dataKey:"date",tick:Ot,tickLine:!1,axisLine:{stroke:us},tickFormatter:Ja}),e.jsx(rn,{tick:Ot,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(on,{...Ds,labelFormatter:pa,formatter:(K,Ie)=>{const ve=typeof K=="number"?K.toLocaleString():String(K??0),Ae=String(Ie??"");if(Ae===Xs)return[ve,"Total Social"];if(Ae===ln){const Ze=`Other (${Ne} source${Ne===1?"":"s"})`;return[ve,Ze]}return[ve,Js(Ae)]}}),e.jsx(Qs,{type:"monotone",dataKey:Xs,stroke:Po,fill:Ct.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),X.map((K,Ie)=>{const Ae=K===ln?ti:ys[Ie%ys.length];return e.jsx(Qs,{type:"monotone",dataKey:K,stackId:"social",stroke:Ae,fill:Ae,fillOpacity:.4,strokeWidth:1.5},K)})]})})}),e.jsx(Rh,{sources:X,otherCount:Ne})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.5fr)]",children:[e.jsxs(ye,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Summary"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social media visits"})]}),i.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(Vt,{label:"Social Sessions",value:Wn(xt),hint:`${xt.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(Vt,{label:"Share of Traffic",value:He,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(Vt,{label:"Platforms",value:String(tt),hint:`${i.socialReferrals.length} source rows`,tone:"neutral",tooltip:"Number of distinct social media platforms detected. Each unique source/medium combination counts as one source row."})]}),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:$o(Js(Je.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:Je.medium,children:["via ",Js(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(Vt,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(Vt,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(Vt,{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(ye,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Breakdown"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Source / medium"})]}),e.jsx("p",{className:"text-xs text-muted",children:i.socialReferrals.length>0?Me.length>jn&&!$?`Top ${jn} of ${Me.length}`:`${Me.length} rows`:"No source rows"})]}),i.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm table-fixed",children:[e.jsxs("colgroup",{children:[e.jsx("col",{className:"w-[32%]"}),e.jsx("col",{className:"w-[22%]"}),e.jsx("col",{className:"w-[12%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[12%]"})]}),e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(Et,{label:"Source",sortKey:"source",current:D,dir:S,onSort:G,align:"left"}),e.jsx(Et,{label:"Medium",sortKey:"medium",current:D,dir:S,onSort:G,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(Et,{label:"Sessions",sortKey:"sessions",current:D,dir:S,onSort:G,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(Et,{label:"Users",sortKey:"users",current:D,dir:S,onSort:G,align:"right"})]})}),e.jsx("tbody",{children:($?Me:Me.slice(0,jn)).map(K=>e.jsx(Ph,{referral:K,totalSessions:xt},`${K.source}:${K.medium}:${K.channelGroup}`))})]})}),Me.length>jn&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>te(K=>!K),className:"rounded-md border border-base px-3 py-1.5 text-xs text-secondary transition-colors hover:border-strong hover:text-strong",children:$?`Show top ${jn}`:`Show all ${Me.length} sources`})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No social media sessions detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"When visitors arrive from Facebook, X/Twitter, LinkedIn, or other social platforms, their sessions will be broken down here by source and medium."})]})]})]})]})]}),i&&i.topPages.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Page Performance"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Top Landing Pages",e.jsx(at,{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(Et,{label:"Landing Page",sortKey:"landingPage",current:b,dir:T,onSort:be,align:"left"}),e.jsx(Et,{label:"Sessions",sortKey:"sessions",current:b,dir:T,onSort:be,align:"right"}),e.jsx(Et,{label:"Organic",sortKey:"organicSessions",current:b,dir:T,onSort:be,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"})]})}),e.jsx("tbody",{children:Ee.map(K=>e.jsx(Ch,{page:K},K.landingPage))})]})})]})]}),e.jsxs("div",{className:"mt-6 flex items-center justify-between text-xs text-muted",children:[e.jsx("span",{children:i?.lastSyncedAt?`Last synced ${Ro(i.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:i?`${i.topPages.length} pages · ${i.aiReferrals.length} AI rows · ${i.socialReferrals.length} social rows`:""})]})]})}function kh({projectName:t,onConnected:s}){const[n,a]=d.useState(""),[i,r]=d.useState(null),[o,l]=d.useState(null),[c,u]=d.useState(!1),[m,h]=d.useState(null),x=d.useRef(null),N=d.useCallback(w=>{const b=w.target.files?.[0];if(!b)return;h(null),r(b.name);const A=new FileReader;A.onload=()=>{const T=A.result;try{const P=JSON.parse(T);if(!P.client_email||!P.private_key){h("JSON file is missing required fields: client_email and private_key. Make sure you downloaded a service account key (not an OAuth client)."),l(null);return}l(T)}catch{h("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),l(null)}},A.onerror=()=>{h("Failed to read file."),l(null)},A.readAsText(b)},[]);async function f(){if(h(null),!n.trim()){h("Property ID is required.");return}if(!o){h("Please upload a service account key file.");return}u(!0);try{await Bl(t,{propertyId:n.trim(),keyJson:o});try{await so(t)}catch{}s()}catch(w){h(w instanceof Error?w.message:"Failed to connect GA4")}finally{u(!1)}}return e.jsxs(ye,{className:"surface-card p-6",children:[e.jsx("h3",{className:"text-base font-semibold text-primary mb-1",children:"Connect Google Analytics 4"}),e.jsx("p",{className:"text-sm text-secondary mb-5",children:"Connect a GA4 property to see traffic data for this project. You'll need a service account key file from Google Cloud Console."}),m&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative",children:m}),e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{htmlFor:"ga4-property-id",className:"block text-xs font-medium text-secondary mb-1.5",children:"GA4 Property ID"}),e.jsx("input",{id:"ga4-property-id",type:"text",placeholder:"e.g. 123456789",value:n,onChange:w=>a(w.target.value),className:"w-full rounded-lg bg-bg-elevated/60 border border-default px-3 py-2 text-sm text-strong placeholder-mono-600 focus:outline-none focus:ring-1 focus:ring-mono-600"}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:"Find this in GA4 → Admin → Property Settings. It's a numeric ID, not the Measurement ID (G-XXXXXX)."})]}),e.jsxs("div",{className:"mb-5",children:[e.jsx("label",{className:"block text-xs font-medium text-secondary mb-1.5",children:"Service Account Key File"}),e.jsx("input",{ref:x,type:"file",accept:".json,application/json",onChange:N,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>x.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(Ru,{className:"w-4 h-4 shrink-0"}),i?e.jsx("span",{className:"text-strong truncate",children:i}):e.jsx("span",{children:"Upload .json key file"})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Download from Google Cloud Console → IAM & Admin → Service Accounts → Keys → Add Key → JSON. The service account must have ",e.jsx("span",{className:"text-secondary",children:"Viewer"})," access on the GA4 property."]})]}),e.jsx(L,{variant:"default",size:"sm",disabled:c||!n.trim()||!o,onClick:Ue(f),children:c?"Connecting & syncing…":"Connect GA4"})]})}function Et({label:t,sortKey:s,current:n,dir:a,onSort:i,align:r}){const o=n===s;return e.jsx("th",{className:`py-1 ${r==="right"?"text-right":"text-left"}`,children:e.jsxs("button",{type:"button",className:"font-medium cursor-pointer select-none hover:text-neutral transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-400 rounded",onClick:()=>i(s),"aria-label":`Sort by ${t}${o?` (currently ${a==="asc"?"ascending":"descending"})`:""}`,children:[t,o&&e.jsx("span",{className:"ml-0.5",children:a==="asc"?"↑":"↓"})]})})}const Lo={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function Ra({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 ${Lo[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Vt({value:t,label:s,hint:n,tone:a,tooltip:i}){return e.jsxs("div",{className:"rounded-lg border border-default bg-bg/40 px-4 py-3 flex flex-col",children:[e.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1 flex items-center gap-1",children:[s,i&&e.jsx(at,{text:i})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${Lo[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Ch({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 Eo={session:"Session",first_user:"First Visit",manual_utm:"UTM"},Io={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 Ah({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=Eo[t.sourceDimension]??t.sourceDimension,i=Io[t.sourceDimension]??"",r=t.trafficClass==="paid"?"Paid":"Organic",o=t.trafficClass==="paid"?"Paid AI traffic inferred from paid/cpc/sponsored UTM values or a GA4 paid channel group":"AI traffic without a paid attribution signal";return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 text-strong max-w-[220px] truncate",title:t.source,children:t.source}),e.jsx("td",{className:"py-1.5 text-muted max-w-[180px] truncate",title:t.medium,children:t.medium}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:`inline-block text-[10px] px-1.5 py-0.5 rounded-full border ${t.trafficClass==="paid"?"border-caution-700 text-caution-300":"border-strong text-secondary"}`,title:o,children:r})}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:i,children:a})}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[n,"%"]})]})}function $h({row:t}){const s=Eo[t.sourceDimension]??t.sourceDimension,n=Io[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(In,{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 Ph({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=t.channelGroup==="Paid Social"?"Paid":"Organic",i=Js(t.source),r=Js(t.medium);return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 pr-3 text-strong truncate",title:t.source,children:i}),e.jsx("td",{className:"py-1.5 pr-3 text-muted truncate",title:t.medium,children:r}),e.jsx("td",{className:"py-1.5 pr-3",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:`GA4 channel group: ${t.channelGroup}`,children:a})}),e.jsx("td",{className:"py-1.5 text-right text-info-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[n,"%"]}),e.jsx("td",{className:"py-1.5 text-right text-strong tabular-nums",children:t.users.toLocaleString()})]})}function Rh({sources:t,otherCount:s}){const n=[{key:Xs,color:Po,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const i=t[a];if(i===ln)n.push({key:ln,color:ti,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const r=Js(i);n.push({key:i,color:ys[a%ys.length]??ti,label:$o(r,32),tooltip:r})}}return e.jsx("div",{className:"mt-3 flex flex-wrap gap-x-4 gap-y-1.5 text-[11px] text-secondary",children:n.map(a=>e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 max-w-[260px]",title:a.tooltip,children:[e.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-sm shrink-0",style:{backgroundColor:a.color},"aria-hidden":"true"}),e.jsx("span",{className:"truncate",children:a.label})]},a.key))})}function Lh(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 Eh=["7d","30d","90d","all"],Yn=500,fs=25,Ih="canonry:google-oauth-complete";function or(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function lr(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 cr(t){return t.isPending?"Processing":Number(t.errors??0)>0?"Errors":Number(t.warnings??0)>0?"Warnings":"Success"}function Dh({projectName:t,refreshNonce:s}){const n=Ss(),[a,i]=d.useState(!1),[r,o]=d.useState([]),[l,c]=d.useState([]),[u,m]=d.useState([]),[h,x]=d.useState(null),[N,f]=d.useState([]),[w,b]=d.useState([]),[A,T]=d.useState(null),[P,j]=d.useState(""),[p,y]=d.useState(""),[v,D]=d.useState("30"),[q,S]=d.useState(!1),[k,F]=d.useState("30d"),[C,I]=d.useState({startDate:"",endDate:"",query:"",page:""}),[me,pe]=d.useState(0),[J,ne]=d.useState(!1),[Z,Q]=d.useState(0),[V,$]=d.useState(!1),[te,ce]=d.useState(""),[re,Y]=d.useState(!0),[fe,U]=d.useState(!1),[be,Ce]=d.useState(!1),[G,Ee]=d.useState(!1),[Re,M]=d.useState(!1),[de,ke]=d.useState(!1),[Oe,Me]=d.useState(!1),[W,X]=d.useState(null),[Ne,O]=d.useState(!1),[E,z]=d.useState(!1),[Se,Qe]=d.useState(null),[qe,Ye]=d.useState(null),[$t,At]=d.useState([]),[_e,Ke]=d.useState(new Set),[it,lt]=d.useState({}),[ze,ct]=d.useState(new Set),[Pt,Ft]=d.useState(""),[Ge,Be]=d.useState(null),[xt,He]=d.useState(""),[Ut,Dt]=d.useState(!1),[tt,Je]=d.useState(!1),[K,Ie]=d.useState(!1),[ve,Ae]=d.useState(!1),[Ze,ms]=d.useState("indexed"),[dt,ns]=d.useState(null),Wt=!!(C.query.trim()||C.page.trim()||dt),pn=dt!==null,_s=d.useMemo(()=>{if(!dt)return u;const{key:g,dir:B}=dt;return[...u].sort((ue,ge)=>{const Fe=g===Ls.CTR?Number.isFinite(ue.ctr)?ue.ctr:0:ue[g],Ve=g===Ls.CTR?Number.isFinite(ge.ctr)?ge.ctr:0:ge[g];return B==="asc"?Fe-Ve:Ve-Fe})},[u,dt]),Yt=_n({rows:_s,pageSize:Ht}),Gs=V?Yt.rows:_s,Xt=_n({rows:(Se??[]).filter(g=>g.path.toLowerCase().includes(Pt.trim().toLowerCase())),pageSize:Ht}),[jt,Os]=d.useState([]),[vt,ht]=d.useState(null),[xn,qs]=d.useState(1),as=d.useMemo(()=>{if(jt.length<2)return null;const g=jt[jt.length-1],B=jt[jt.length-2];return{indexed:g.indexed-B.indexed,notIndexed:g.notIndexed-B.notIndexed}},[jt]);d.useEffect(()=>{qs(1)},[W,Ze,vt]);const ps=d.useMemo(()=>vt?(W?.reasonGroups??[]).find(g=>g.reason===vt):void 0,[W,vt]),Jt=d.useMemo(()=>W?Ze==="indexed"?W.indexed:Ze==="deindexed"?W.deindexed:Ze==="notIndexed"?vt?ps?.urls??[]:(W.reasonGroups??[]).length===0?W.notIndexed:[]:[]:[],[W,Ze,vt,ps]),gn=Math.max(1,Math.ceil(Jt.length/fs)),R=Math.min(Math.max(1,xn),gn),xe=(R-1)*fs,Pe=d.useMemo(()=>W?.indexed.slice(xe,xe+fs)??[],[W,xe]),zt=d.useMemo(()=>W?.notIndexed.slice(xe,xe+fs)??[],[W,xe]),Rt=d.useMemo(()=>W?.deindexed.slice(xe,xe+fs)??[],[W,xe]),_=d.useMemo(()=>(ps?.urls??[]).slice(xe,xe+fs),[ps,xe]),[ae,je]=d.useState(!1),[he,se]=d.useState(null),[Le,Bt]=d.useState(null),[gt,Lt]=d.useState(null);function xs(g,B){const ue=qu(g),ge=Lh(ue);ge?(Bt(ge),se(null)):(Bt(null),se(ue.message||B))}const ft=r.find(g=>g.connectionType==="gsc"),ks=(ft?.scopes??[]).includes("https://www.googleapis.com/auth/webmasters"),va=$t.length>0?$t:(Se??[]).map(g=>g.path),Di=va.filter(g=>Se?.some(B=>B.path===g&&B.isSitemapsIndex)).length,yl=Di===1?"Resubmit sitemap index":Di>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",vl=u.length>0||N.length>0||w.length>0,ja=Kl(),Na=Vl();async function Ti(g,B=!1){if(!g){c([]),j("");return}Ce(!0);try{const{sites:ue}=await n.fetchQuery({...ic({client:H,path:{name:t}}),staleTime:B?0:bt});c(ue),j(g.propertyId??ue[0]?.siteUrl??""),Bt(null)}catch(ue){c([]),xs(ue,"Failed to load Search Console properties")}finally{Ce(!1)}}async function fn(g){M(!0);const B=g??me;try{const ue=Wt?Yn:Ht,ge=Wt?0:B,Fe={limit:String(ue)};C.startDate&&(Fe.startDate=C.startDate),C.endDate&&(Fe.endDate=C.endDate),C.query&&(Fe.query=C.query),C.page&&(Fe.page=C.page),ge>0&&(Fe.offset=String(ge)),k&&k!=="all"&&!C.startDate&&(Fe.window=k);const Ve=await n.fetchQuery({...Hl({client:H,path:{name:t},query:Fe}),staleTime:bt}),We=Ve.rows;Wt?(ne(!1),m(We),Q(We.length),$(!0)):(ne(ge+We.length<Ve.totalMatching),m(We),Q(0),$(!1))}catch(ue){m([]),ne(!1),Q(0),se(ue instanceof Error?ue.message:"Failed to load GSC performance data")}finally{M(!1)}}async function wa(){try{const g={};C.startDate&&(g.startDate=C.startDate),C.endDate&&(g.endDate=C.endDate),k&&k!=="all"&&!C.startDate&&(g.window=k);const B=await n.fetchQuery({...Wl({client:H,path:{name:t},query:g}),staleTime:bt});x(B)}catch{x(null)}}async function zn(g=!1){ke(!0);try{const B=te.trim()||void 0,ue={limit:"20"};B&&(ue.url=B);const[ge,Fe]=await Promise.all([n.fetchQuery({...nc({client:H,path:{name:t},query:ue}),staleTime:g?0:bt}),n.fetchQuery({...ac({client:H,path:{name:t}}),staleTime:g?0:bt})]);f(ge),b(Fe)}catch(B){f([]),b([]),se(B instanceof Error?B.message:"Failed to load GSC inspection history")}finally{ke(!1)}}async function Mi(g=!1){O(!0);try{const[B,ue]=await Promise.all([n.fetchQuery({...ao({client:H,path:{name:t}}),staleTime:g?0:bt}),n.fetchQuery({...Jl({client:H,path:{name:t}}),staleTime:g?0:bt}).catch(()=>[])]);X(B),Os(ue)}catch(B){X(null),Os([]),se(B instanceof Error?B.message:"Failed to load coverage data")}finally{O(!1)}}async function _i(g){je(!0),se(null);try{const B=await Vi(t,{urls:g}),{succeeded:ue,failed:ge,total:Fe}=B.summary;$e({title:"Indexing requested",detail:ge===0?`${ue} URL${ue!==1?"s":""} submitted for indexing.`:`${ue}/${Fe} submitted successfully, ${ge} failed.`,tone:ge===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(B){se(B instanceof Error?B.message:"Failed to request indexing")}finally{je(!1)}}async function jl(){je(!0),se(null);try{const g=await Vi(t,{urls:[],allUnindexed:!0}),{succeeded:B,failed:ue,total:ge}=g.summary;$e({title:"Indexing requested",detail:ue===0?`${B} unindexed URL${B!==1?"s":""} submitted for indexing.`:`${B}/${ge} submitted successfully, ${ue} failed.`,tone:ue===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(g){se(g instanceof Error?g.message:"Failed to request indexing")}finally{je(!1)}}async function Sa(){z(!0),se(null);try{const g=await ka(t);n.setQueryData(Zl({client:H,path:{name:t}}),g),Qe(g.sitemaps),Ye(g.summary),At(g.preferredSubmissionUrls),Ke(new Set),lt({}),g.sitemaps.length===0&&Lt("No sitemaps found in this GSC property. Submit one here to start Google processing it.")}catch(g){se(g instanceof Error?g.message:"Failed to list sitemaps")}finally{z(!1)}}async function Nl(g){const B=_e.has(g);if(Ke(ue=>{const ge=new Set(ue);return B?ge.delete(g):ge.add(g),ge}),!(B||it[g])){ct(ue=>new Set(ue).add(g));try{const ue=await ka(t,g);lt(ge=>({...ge,[g]:ue.sitemaps}))}catch(ue){se(ue instanceof Error?ue.message:"Failed to load sitemap files")}finally{ct(ue=>{const ge=new Set(ue);return ge.delete(g),ge})}}}async function Fs(g){if(!ks||g.length===0)return;const B=[...new Set(g)];Je(!0),se(null),Be({completed:0,total:B.length});let ue=0,ge=0,Fe=0,Ve=null;try{for(let rt=0;rt<B.length;rt+=50){const Te=B.slice(rt,rt+50);try{const Nt=await ec(t,Te);ue+=Nt.summary.accepted,ge+=Nt.summary.failed,Fe+=Te.length,Be({completed:Fe,total:B.length})}catch(Nt){Fe+=Te.length;const Kt=Te.length,Cs=B.length-Fe,Us=Nt instanceof Error?Nt.message:"The batch request failed",bn=`${ue} accepted, ${ge} failed, ${Kt} unconfirmed, ${Cs} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;Ve=`Sitemap submission stopped after a batch request failed. ${bn} ${Us}`,se(Ve),$e({title:"Sitemap resubmission partially completed",detail:bn,tone:"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"});return}}const We=B.length;$e({title:ge===0?"Sitemap submitted to Google":"Some sitemap submissions need attention",detail:ge===0?"Google accepted the sitemap submission/refetch request; indexing is not guaranteed.":`Google accepted ${ue}/${We} sitemap submissions; ${ge} failed. Indexing is not guaranteed.`,tone:ge===0?"positive":"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"}),He("")}catch(We){se(We instanceof Error?We.message:"Failed to submit sitemap to Google")}finally{Je(!1),Be(null),await Sa(),Ve&&se(Ve)}}async function wl(){Je(!0);const g=Se??[];try{const B=g.filter(ge=>ge.isSitemapsIndex),ue=[];for(let ge=0;ge<B.length;ge+=4)(await Promise.all(B.slice(ge,ge+4).map(async Ve=>{const We=it[Ve.path];if(We)return We;const rt=await ka(t,Ve.path);return lt(Te=>({...Te,[Ve.path]:rt.sitemaps})),rt.sitemaps}))).forEach((Ve,We)=>{ue.push(...Ve.length>0?Ve.map(rt=>rt.path):[B[ge+We].path])});await Fs([...g.filter(ge=>!ge.isSitemapsIndex).map(ge=>ge.path),...ue])}catch(B){se(B instanceof Error?B.message:"Failed to load sitemap files"),Je(!1)}}async function Gi(g){Dt(!0),se(null);try{await tc(t,"gsc",g),await pt(n,"google"),o(B=>B.map(ue=>ue.connectionType==="gsc"?{...ue,sitemapUrl:g}:ue)),$e({title:"Default sitemap updated",detail:g,tone:"positive",dedupeKey:`gsc:sitemap-default:${t}`,dedupeMode:"replace"})}catch(B){se(B instanceof Error?B.message:"Failed to set the default sitemap")}finally{Dt(!1)}}async function Oi(g){try{await Na.mutateAsync({projectName:t,projectLabel:t,opts:g?{sitemapUrl:g}:void 0})}catch{}}async function qi(){Y(!0),se(null);try{const[g,B]=await Promise.all([no().catch(()=>null),n.fetchQuery({...hi({client:H,path:{name:t}}),staleTime:bt}).catch(()=>[])]);i(!!g?.google?.configured),o(B);const ue=B.find(ge=>ge.connectionType==="gsc");await Promise.all([Ti(ue),fn(),wa(),zn(),Mi(),ue?.propertyId?Sa():Promise.resolve()])}finally{Y(!1)}}d.useEffect(()=>{qi()},[t,s]),d.useEffect(()=>{pe(0),fn(0),wa()},[k]);const Fi=d.useRef(!1);d.useEffect(()=>{if(!Fi.current){Fi.current=!0;return}pe(0),fn(0)},[pn]);async function Ui(){if(!a){se("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}U(!0),se(null),Lt(null);try{let g=function(Nt){if(Nt.source!==ge||Nt.origin!==Fe||!Nt.data||typeof Nt.data!="object")return;const Kt=Nt.data;Kt.type!==Ih||Kt.connectionType!=="gsc"||Te(!0)};const{authUrl:B,redirectUri:ue}=await Xl(t,"gsc");if(!B.startsWith("https://accounts.google.com/")){se("Unexpected OAuth redirect URL. Please try again.");return}const ge=window.open(B,"_blank","width=600,height=700");if(!ge){window.location.assign(B);return}const Fe=ue?new URL(ue).origin:window.location.origin;let Ve=!1,We=null;const rt=()=>{We!==null&&window.clearInterval(We),window.removeEventListener("message",g)},Te=async Nt=>{if(!Ve){Ve=!0,rt(),Lt(Nt?"Google connected. Refreshing access…":"Refreshing Google connection…");try{await pt(n,"google"),await qi()}finally{Lt(null)}}};window.addEventListener("message",g),Lt("Finish the Google consent flow in the popup. This page will refresh automatically."),We=window.setInterval(()=>{ge.closed&&Te(!1)},1e3)}catch(g){se(g instanceof Error?g.message:"Failed to start OAuth flow")}finally{U(!1)}}async function Sl(){se(null),Lt(null);try{await Yl(t,"gsc"),await pt(n,"google"),o(g=>g.filter(B=>B.connectionType!=="gsc")),c([]),j("")}catch(g){se(g instanceof Error?g.message:"Failed to disconnect")}}async function kl(){if(P){Ee(!0),se(null);try{await rc(t,"gsc",P),await pt(n,"google"),o(g=>g.map(B=>B.connectionType==="gsc"?{...B,propertyId:P}:B)),$e({title:"GSC property updated",detail:`${t} is now linked to ${P}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(g){se(g instanceof Error?g.message:"Failed to save GSC property")}finally{Ee(!1)}}}async function Cl(){se(null),Lt(null);try{await ja.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(v,10)||void 0,full:q||void 0}}),await pt(n,"gsc")}catch{}}async function zi(){if(p.trim()){Me(!0),se(null),Lt(null);try{const g=await sc(t,p.trim());await pt(n,"gsc"),T(g),y(""),await zn()}catch(g){se(g instanceof Error?g.message:"Failed to inspect URL")}finally{Me(!1)}}}return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search Console"}),e.jsx("h2",{children:"Google Search Console"})]})}),Le&&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:Le.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:Le.message}),(Ps(Le.enableUrl)||Ps(Le.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[Ps(Le.enableUrl)&&e.jsx("a",{href:Ps(Le.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 ↗"}),Ps(Le.indexingApiUrl)&&e.jsx("a",{href:Ps(Le.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:()=>Bt(null),children:"×"})]})}),he&&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:[he,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>se(null),children:"×"})]}),gt&&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:[gt,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>Lt(null),children:"×"})]}),re?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[ft?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:ft.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Coverage measured"," ",W?.lastInspectedAt?es(W.lastInspectedAt):"never"]}),e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:Ue(Sl),children:"Disconnect"})]}):e.jsxs(ye,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(oe,{tone:a?"caution":"negative",children:a?"Ready to connect":"App credentials missing"})]}),e.jsxs("div",{className:"mt-3 rounded-lg border border-default bg-surface px-4 py-5",children:[e.jsx("p",{className:"text-sm text-neutral",children:a?"Generate a Google OAuth link for this project and have the client sign in with a Google account that already has access to the correct Search Console property.":"Set Google OAuth client credentials first. Once configured, you can generate a consent link for this project domain."}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[a?e.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:fe,onClick:Ue(Ui),children:fe?"Opening…":"Connect Google Search Console"}):e.jsx(L,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(ts,{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."})]})]})]}),(ft||vl)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs(ye,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Performance"}),e.jsx("h3",{children:"Search performance"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"segmented",role:"group","aria-label":"Performance time period",children:Eh.map(g=>e.jsx("button",{type:"button","aria-pressed":k===g,className:`segmented-option ${k===g?"segmented-option-active":""}`,onClick:()=>{F(g),pe(0),Yt.setPage(1)},children:g==="all"?"All":g},g))}),e.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:Re,onClick:()=>{pe(0),Yt.setPage(1),fn(0),wa()},children:Re?"Loading…":"Apply filters"})]})]}),h&&h.daily.length>0&&(()=>{const g=h.daily,B=Math.max(...g.map(et=>et.impressions),1),{clicks:ue,impressions:ge,ctr:Fe}=h.totals,Ve=(Fe*100).toFixed(1),We=700,rt=220,Te={top:12,bottom:36,left:48,right:12},Nt=We-Te.left-Te.right,Kt=rt-Te.top-Te.bottom,Cs=Nt/g.length,Us=Math.max(Math.min(Cs*.35,24),4),bn=Math.max(Us*.15,1),Al=et=>{if(et<=0)return 1;const is=Math.pow(10,Math.floor(Math.log10(et))),Tt=et/is,gs=Tt<=1.5?1.5:Tt<=3?3:Tt<=5?5:10;return Math.ceil(gs*is)},Bn=4,Kn=Math.ceil(Al(B)/Bn)*Bn,$l=Array.from({length:Bn+1},(et,is)=>Kn/Bn*is),Pl=et=>et>=1e3?`${(et/1e3).toFixed(et>=1e4?0:1)}k`:String(et);return e.jsxs("div",{className:"mt-3",children:[e.jsxs("div",{className:"flex items-center gap-5 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-sm bg-positive-500"}),e.jsxs("span",{className:"text-xs text-secondary",children:["Clicks ",e.jsx("span",{className:"text-strong tabular-nums font-medium",children:ue.toLocaleString()})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-sm bg-chart-series-2"}),e.jsxs("span",{className:"text-xs text-secondary",children:["Impressions ",e.jsx("span",{className:"text-strong tabular-nums font-medium",children:ge.toLocaleString()})]})]}),e.jsxs("span",{className:"text-xs text-muted",children:["CTR ",e.jsxs("span",{className:"text-caution-400 tabular-nums font-medium",children:[Ve,"%"]})]})]}),e.jsx("div",{className:"relative w-full",style:{aspectRatio:`${We} / ${rt}`},children:e.jsxs("svg",{viewBox:`0 0 ${We} ${rt}`,className:"h-full w-full",children:[$l.map((et,is)=>{const Tt=Te.top+Kt-et/Kn*Kt;return e.jsxs("g",{children:[e.jsx("line",{x1:Te.left,y1:Tt,x2:We-Te.right,y2:Tt,stroke:Ct.gridLine,strokeWidth:"1"}),e.jsx("text",{x:Te.left-6,y:Tt+3.5,textAnchor:"end",fill:Ct.text,fontSize:"10",fontFamily:"inherit",children:Pl(et)})]},`t-${is}`)}),g.map((et,is)=>{const Tt=Te.left+Cs*is+Cs/2,gs=et.impressions/Kn*Kt,Vn=et.clicks/Kn*Kt;return e.jsxs("g",{children:[e.jsx("title",{children:`${et.date}
|
|
3
3
|
Clicks: ${et.clicks}
|
|
4
4
|
Impressions: ${et.impressions}
|
|
5
5
|
CTR: ${(et.ctr*100).toFixed(1)}%`}),e.jsx("rect",{x:Tt-Us-bn/2,y:Te.top+Kt-gs,width:Us,height:Math.max(gs,1),rx:2,fill:kt[1],opacity:.85}),e.jsx("rect",{x:Tt+bn/2,y:Te.top+Kt-Vn,width:Us,height:Math.max(Vn,1),rx:2,fill:cs.positiveDeep,opacity:.85})]},et.date)}),(()=>{const et=Math.min(g.length,7);return Array.from({length:et},(is,Tt)=>{const gs=g.length===1?0:Math.round(Tt/(et-1)*(g.length-1)),Vn=Te.left+Cs*gs+Cs/2;return e.jsx("text",{x:Vn,y:rt-8,textAnchor:"middle",fill:Ct.textDim,fontSize:"10",fontFamily:"inherit",children:g[gs].date.slice(5)},`xl-${gs}`)})})()]})})]})})(),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:C.startDate,onChange:g=>I(B=>({...B,startDate:g.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:C.endDate,onChange:g=>I(B=>({...B,endDate:g.target.value}))}),e.jsx(Ys,{value:C.query,onChange:g=>I(B=>({...B,query:g})),label:"Filter search queries",placeholder:"Contains query…"}),e.jsx(Ys,{value:C.page,onChange:g=>I(B=>({...B,page:g})),label:"Filter page URLs",placeholder:"Contains page URL…"})]}),e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Query and page filters match case-insensitive substrings. Click Apply filters to run. Filtering and sorting examine up to ",Yn.toLocaleString()," matching rows while the table stays at ",Ht," rows per page."]}),u.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Date"}),e.jsx("th",{className:"text-left",children:"Query"}),e.jsx("th",{className:"text-left",children:"Page"}),Object.values(Ls).map(g=>e.jsx("th",{className:"text-right","aria-sort":dt?.key===g?dt.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:()=>{Yt.setPage(1),ns(B=>B?.key===g?B.dir==="desc"?{key:g,dir:"asc"}:null:{key:g,dir:"desc"})},children:[Ql[g],dt?.key===g?dt.dir==="desc"?" ↓":" ↑":""]})},g))]})}),e.jsx("tbody",{children:Gs.map((g,B)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:g.date}),e.jsx("td",{className:"max-w-xs truncate text-strong",children:g.query}),e.jsx("td",{className:"max-w-xs text-secondary",children:e.jsx(In,{value:g.page})}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:g.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:g.impressions.toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[(Number.isFinite(g.ctr)?g.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:g.position.toFixed(1)})]},`${g.date}:${g.query}:${g.page}:${B}`))})]})}),e.jsx(Ts,{page:V?Yt.page:Math.floor(me/Ht)+1,pageSize:Ht,visibleRows:Gs.length,totalRows:V?Z:void 0,hasNextPage:V?void 0:J,disabled:Re,itemLabel:V?"matches":"rows",onPageChange:g=>{if(V){Yt.setPage(g);return}const B=(g-1)*Ht;pe(B),fn(B)}}),V&&Z>=Yn?e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Results are capped at ",Yn.toLocaleString(),"; narrow the filters to search beyond this set."]}):null]}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No performance rows match the current filters yet."})]}),e.jsxs(ye,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Coverage"}),e.jsx("h3",{children:"Index coverage"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[W&&W.notIndexed.length>0&&e.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:ae,onClick:()=>{jl()},children:ae?"Requesting…":`Request indexing (${W.notIndexed.length})`}),e.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:Ne,onClick:()=>{Mi(!0)},children:Ne?"Loading…":"Reload saved coverage"})]})]}),W&&W.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const g=W.summary.indexed+W.summary.notIndexed,B=g>0?W.summary.indexed/g:0,ue=g>0?W.summary.notIndexed/g:0,ge=54,Fe=2*Math.PI*ge,Ve=Fe*(1-B),We=Fe*ue,rt=Fe*B;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:ge,fill:"none",stroke:Ct.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:ge,fill:"none",stroke:cs.positiveDeep,strokeWidth:"14",strokeDasharray:Fe,strokeDashoffset:Ve,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),W.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:ge,fill:"none",stroke:Ct.textFaint,strokeWidth:"14",strokeDasharray:`${We} ${Fe-We}`,strokeDashoffset:-rt,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:[(B*100).toFixed(0),"%"]}),e.jsx("span",{className:"text-xs uppercase tracking-widest text-muted mt-0.5",children:"Indexed"})]})]}),e.jsxs("div",{className:"mt-4 flex items-center justify-center gap-8",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-positive-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:W.summary.indexed.toLocaleString()}),e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:"Indexed"})]})]}),e.jsx("div",{className:"h-8 w-px bg-mono-800"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-mono-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:W.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:["Not indexed",(W.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-faint",children:["· ",(W.reasonGroups??[]).length," ",(W.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),W.summary.deindexed>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-8 w-px bg-mono-800"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-negative-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:W.summary.deindexed.toLocaleString()}),e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:"Deindexed"})]})]})]})]})]})})()}),e.jsx("div",{className:"mt-3 flex border-b border-default",role:"tablist","aria-label":"Coverage status",children:["indexed","notIndexed","deindexed"].map(g=>{const B=g==="indexed"?W.indexed.length:g==="notIndexed"?W.notIndexed.length:W.deindexed.length,ue=g==="indexed"?"Indexed":g==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",role:"tab","aria-selected":Ze===g,className:`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${Ze===g?"border-accent text-heading":"border-transparent text-secondary hover:border-mono-600 hover:text-strong"}`,onClick:()=>{ms(g),ht(null)},children:[ue," (",B,")"]},g)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[Ze==="indexed"&&W.indexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Verdict"}),e.jsx("th",{className:"text-left",children:"Last Crawl"}),e.jsx("th",{className:"text-left",children:"Mobile"})]})}),e.jsx("tbody",{children:Pe.map(g=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:g.url}),e.jsx("td",{className:"text-secondary",children:g.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:g.crawlTime?g.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:g.isMobileFriendly===!0?"Yes":g.isMobileFriendly===!1?"No":"—"})]},g.id))})]}),Ze==="notIndexed"&&!vt&&(W.reasonGroups??[]).length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Reason"}),e.jsx("th",{className:"text-right",children:"Pages"})]})}),e.jsx("tbody",{children:(W.reasonGroups??[]).map(g=>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(g.reason),onKeyDown:B=>{(B.key==="Enter"||B.key===" ")&&(B.preventDefault(),ht(g.reason))},tabIndex:0,role:"button","aria-label":`View ${g.reason} pages`,children:[e.jsx("td",{className:"text-strong",children:g.reason}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:g.count})]},g.reason))})]}),Ze==="notIndexed"&&!vt&&(W.reasonGroups??[]).length===0&&W.notIndexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Indexing State"}),e.jsx("th",{className:"text-left",children:"Coverage"})]})}),e.jsx("tbody",{children:zt.map(g=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:g.url}),e.jsx("td",{className:"text-secondary",children:g.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:g.coverageState??"Unknown"})]},g.id))})]}),Ze==="notIndexed"&&vt&&(()=>{const g=(W.reasonGroups??[]).find(B=>B.reason===vt);return g?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:g.reason}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[g.count," affected page",g.count!==1?"s":""]})]}),e.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:ae,onClick:()=>{_i(g.urls.map(B=>B.url))},children:ae?"Requesting…":`Request indexing (${g.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:_.map(B=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:B.url}),e.jsx("td",{className:"text-secondary",children:B.crawlTime?B.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-strong transition-colors",disabled:ae,onClick:()=>{_i([B.url])},title:"Request indexing",children:"Index"})})]},B.id))})]})]}):null})(),Ze==="deindexed"&&W.deindexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Previous"}),e.jsx("th",{className:"text-left",children:"Current"}),e.jsx("th",{className:"text-left",children:"Detected"})]})}),e.jsx("tbody",{children:Rt.map((g,B)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:g.url}),e.jsx("td",{className:"text-secondary",children:g.previousState}),e.jsx("td",{className:"text-secondary",children:g.currentState}),e.jsx("td",{className:"text-secondary",children:g.transitionDate.split("T")[0]})]},`${g.url}-${B}`))})]}),(Ze==="indexed"&&W.indexed.length===0||Ze==="notIndexed"&&!vt&&W.notIndexed.length===0||Ze==="deindexed"&&W.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),e.jsx(Ts,{page:R,pageSize:fs,visibleRows:Math.min(fs,Jt.length-xe),totalRows:Jt.length,onPageChange:qs,itemLabel:"URLs"})]}),e.jsx("p",{className:"mt-3 text-xs text-muted",children:"Google's Indexing API is intended for eligible JobPosting and BroadcastEvent pages. Sitemap resubmission is the general-site bulk path."}),e.jsxs("div",{className:"mt-4 border-t border-default pt-3",children:[e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between text-left text-xs text-secondary hover:text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400","aria-expanded":ve,onClick:()=>Ae(g=>!g),children:[e.jsx("span",{children:"Coverage history"}),e.jsx("span",{children:ve?"Hide snapshots":jt.length>0?`View ${jt.length} snapshots`:"View history"})]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["Current: ",W.summary.indexed.toLocaleString()," indexed, ",W.summary.notIndexed.toLocaleString()," not indexed.",as&&e.jsxs(e.Fragment,{children:[" Since the last snapshot: ",as.indexed>=0?"+":"",as.indexed.toLocaleString()," indexed, ",as.notIndexed>=0?"+":"",as.notIndexed.toLocaleString()," not indexed."]})]}),ve&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:jt.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:jt.map(g=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:g.date}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:g.indexed.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:g.notIndexed.toLocaleString()})]},g.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:Ne?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),e.jsxs(ye,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Sitemaps"}),e.jsx("h3",{children:"Sitemap operations"})]}),e.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:E||!ft?.propertyId,onClick:()=>{Sa()},children:E?"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:xt,onChange:g=>He(g.target.value),onKeyDown:g=>g.key==="Enter"&&void Fs([xt.trim()])}),e.jsx(L,{type:"button",size:"sm",disabled:!ks||tt||!xt.trim(),onClick:()=>{Fs([xt.trim()])},children:tt?"Submitting…":"Submit sitemap to Google"})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(L,{type:"button",size:"sm",variant:"outline",disabled:!ks||tt||va.length===0,onClick:()=>{Fs(va)},children:tt?"Resubmitting…":yl}),e.jsx(L,{type:"button",size:"sm",variant:"outline",disabled:!ks||tt||!Se?.length,onClick:()=>{wl()},children:"Resubmit all files"}),qe&&e.jsxs("span",{className:"text-xs text-muted",children:["Top level: ",qe.indexes," index",qe.indexes===1?"":"es",", ",qe.files," file",qe.files===1?"":"s"]}),Ge&&e.jsxs("span",{className:"text-xs text-secondary",children:["Submitting ",Ge.completed,"/",Ge.total]})]}),e.jsx("p",{className:"mt-2 text-xs text-muted",children:"Google is asked to refetch these sitemaps. Indexing is not guaranteed."}),!ks&&ft&&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:Ue(Ui),children:"Reconnect"})]}),Se&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:Se.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Ys,{value:Pt,onChange:g=>{Ft(g),Xt.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:Xt.rows.flatMap(g=>{const B=or(g),ue=lr(g),ge=cr(g),Fe=it[g.path]??[],Ve=_e.has(g.path),We=e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs text-strong",children:e.jsx(In,{value:g.path})}),e.jsx("td",{className:"text-secondary",children:g.isSitemapsIndex?e.jsx("button",{type:"button",className:"text-secondary hover:text-strong","aria-expanded":Ve,"aria-label":`${Ve?"Collapse":"Expand"} files in ${g.path}`,onClick:()=>{Nl(g.path)},children:ze.has(g.path)?"Loading…":`${Ve?"▾":"▸"} Index${it[g.path]?` (${Fe.length})`:""}`}):"Sitemap"}),e.jsx("td",{className:"text-secondary",children:ge}),e.jsx("td",{className:"text-secondary",children:g.lastSubmitted?g.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:g.lastDownloaded?g.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:B.toLocaleString()}),e.jsx("td",{className:"max-w-48 text-secondary",children:ue||"—"}),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:!ks||tt,onClick:()=>{Fs([g.path])},children:g.lastSubmitted?"Resubmit to Google":"Submit to Google"}),ft?.sitemapUrl===g.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:Ut,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{Gi(g.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Na.isPending,onClick:()=>{Oi(g.path)},children:"Inspect URLs"})]})})]},g.path),rt=g.isSitemapsIndex&&Ve?Fe.map(Te=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs pl-6 text-secondary",children:e.jsx(In,{value:Te.path})}),e.jsx("td",{className:"text-secondary",children:"File"}),e.jsx("td",{className:"text-secondary",children:cr(Te)}),e.jsx("td",{className:"text-secondary",children:Te.lastSubmitted?Te.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:Te.lastDownloaded?Te.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:or(Te).toLocaleString()}),e.jsx("td",{className:"text-secondary",children:lr(Te)||"—"}),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:!ks||tt,onClick:()=>{Fs([Te.path])},children:"Resubmit"}),ft?.sitemapUrl===Te.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:Ut,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{Gi(Te.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Na.isPending,onClick:()=>{Oi(Te.path)},children:"Inspect URLs"})]})})]},`${g.path}:${Te.path}`)):[];return[We,...rt]})})]}),e.jsx(Ts,{page:Xt.page,pageSize:Ht,visibleRows:Xt.rows.length,totalRows:Xt.totalRows,onPageChange:Xt.setPage,itemLabel:"sitemaps"})]}):e.jsx("p",{className:"text-sm text-muted",children:"No sitemaps found for this property."})})]}),e.jsxs(ye,{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:p,onChange:g=>y(g.target.value),onKeyDown:g=>g.key==="Enter"&&void zi()}),e.jsx(L,{type:"button",size:"sm",disabled:Oe||!ft?.propertyId||!p.trim(),onClick:Ue(zi),children:Oe?"Inspecting…":"Inspect URL"})]}),A&&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:A.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:A.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:Ki(A.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:es(A.crawlTime)})]})]})]}),e.jsxs(ye,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Inspection log"})]}),e.jsx(L,{type:"button",variant:"outline",size:"sm",disabled:de,onClick:()=>{zn(!0)},children:de?"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:te,onChange:g=>ce(g.target.value)}),e.jsx(L,{type:"button",size:"sm",variant:"outline",disabled:de,onClick:()=>{zn(!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(g=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:g.url}),e.jsx("td",{className:"text-neutral",children:g.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:g.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:g.coverageState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:Ki(g.isMobileFriendly??null)}),e.jsx("td",{className:"text-secondary",children:es(g.inspectedAt)})]},g.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No inspection history yet."})]}),e.jsxs(ye,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Deindexed"}),e.jsx("h3",{children:"Recent indexing losses"})]})}),w.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Previous"}),e.jsx("th",{className:"text-left",children:"Current"}),e.jsx("th",{className:"text-left",children:"Changed at"})]})}),e.jsx("tbody",{children:w.map(g=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:g.url}),e.jsx("td",{className:"text-secondary",children:g.previousState??"Unknown"}),e.jsx("td",{className:"text-neutral",children:g.currentState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:es(g.transitionDate)})]},`${g.url}:${g.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No deindexed transitions recorded."})]})]}),ft&&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:()=>Ie(g=>!g),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 ${K?"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"})]})}),K&&e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(ye,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Property"}),e.jsx("h3",{children:"Pick the Search Console property"})]})}),e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:`gsc-property-${t}`,children:"Property URL"}),e.jsx("select",{id:`gsc-property-${t}`,className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none",value:P,disabled:be||l.length===0,onChange:g=>j(g.target.value),children:l.length===0?e.jsx("option",{value:"",children:be?"Loading properties…":"No properties available"}):l.map(g=>e.jsxs("option",{value:g.siteUrl,children:[g.siteUrl," · ",g.permissionLevel]},g.siteUrl))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(L,{type:"button",size:"sm",variant:"outline",disabled:be,onClick:()=>{Ti(ft,!0)},children:be?"Refreshing…":"Refresh properties"}),e.jsx(L,{type:"button",size:"sm",disabled:!P||G,onClick:Ue(kl),children:G?"Saving…":"Save property"})]}),e.jsx("p",{className:"text-xs text-muted",children:"The selected property is used for future syncs and URL inspections for this project."})]})]}),e.jsxs(ye,{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:v,onChange:g=>D(g.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:q,onChange:g=>S(g.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(L,{type:"button",size:"sm",disabled:ja.isPending||!ft.propertyId,onClick:Ue(Cl),children:ja.isPending?"Queueing…":"Queue sync"}),!ft.propertyId&&e.jsx("p",{className:"text-xs text-caution-400",children:"Select a Search Console property before queueing a sync."})]})]})]})})]})]})]})}const Th=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function Mh({projectName:t,projectId:s}){const n=Ss(),[a,i]=d.useState(null),[r,o]=d.useState(null),[l,c]=d.useState(!1),u=De(hi({client:H,path:{name:t}})),m=u.data?.find(U=>U.connectionType==="gbp"),h=!!m,x=a?{locationName:a}:void 0,N=De({...oc({client:H,path:{name:t}}),enabled:h}),f=De({...lc({client:H,path:{name:t},query:x}),enabled:h}),w=De({...cc({client:H,path:{name:t},query:x}),enabled:h}),b=De({...dc({client:H,path:{name:t},query:x}),enabled:h}),A=De({...uc({client:H,path:{name:t},query:x}),enabled:h}),T=De({...hc({client:H,path:{name:t},query:x}),enabled:h}),P=De({queryKey:["gbp-section-insights",t],queryFn:()=>mc(t),enabled:h});function j(){pt(n,"gbp")}const p=Mn({...xc(),onSuccess:U=>{pc({id:U.runId,projectId:s,kind:ws["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),$e({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),y=d.useSyncExternalStore(io,ha,ha),v=Object.values(y.runs).some(U=>U.kind===ws["gbp-sync"]&&U.projectId===s),D=p.isPending||v,q=Mn({...gc(),onSuccess:()=>j()});if(d.useEffect(()=>{if(!a||!N.data)return;const U=N.data.locations.filter(be=>be.selected);(U.length<=1||!U.some(be=>be.locationName===a))&&i(null)},[a,N.data]),d.useEffect(()=>{if(!r||!N.data)return;(a?[a]:N.data.locations.filter(be=>be.selected).map(be=>be.locationName)).includes(r)||o(null)},[r,N.data,a]),u.isLoading)return null;if(!m){const U=[{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(ye,{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:U.map((be,Ce)=>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:Ce+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:be.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:be.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:be.note})]})]},be.title))})]})})}const S=f.data,k=N.data?.locations??[],F=k.filter(U=>U.selected),C=w.data?.keywords??[],I=b.data?.lodging??[],me=A.data?.placeActions??[],pe=T.data?.places??[],J=k.length>0?k[0].accountName:m.domain,ne=a?k.find(U=>U.locationName===a)?.displayName??null:null,Z=a?k.filter(U=>U.locationName===a):F,Q=new Set(Z.map(U=>U.locationName)),V=I.filter(U=>Q.has(U.locationName)),$=me.filter(U=>Q.has(U.locationName)),te=pe.filter(U=>Q.has(U.locationName)),ce=new Set(F.map(U=>U.locationName)),re=a?C:C.filter(U=>ce.has(U.locationName)),Y=!a&&F.length>1,fe=(P.data??[]).filter(U=>!U.dismissed&&Th.has(U.type)&&(!ne||U.query===ne||U.query===a||U.title.startsWith(ne)));return e.jsx("section",{className:"page-section-divider",children:e.jsxs(ye,{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(at,{text:"How AI answer engines and Maps surface this business: performance, search terms, and how your public listing compares to the profile you control."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oe,{tone:"positive",children:"Connected"}),!ie()&&e.jsx(nt,{type:"button",variant:"outline",size:"sm",disabled:D,onClick:()=>p.mutate({client:H,path:{name:t},body:{}}),children:D?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-muted",children:[J?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-secondary",children:J})," · "]}):null,N.data?`${N.data.totalSelected} of ${N.data.totalDiscovered} locations tracked`:"Loading locations…"]}),F.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:U=>i(U.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"}),F.map(U=>e.jsx("option",{value:U.locationName,children:U.displayName},U.id))]})]}),F.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:[fe.length>0&&e.jsxs("div",{className:"mb-6 grid gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Needs attention"}),fe.map(U=>e.jsx("div",{className:["insight-card",Wh(U.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:[U.title,U.recommendation?.reason&&e.jsx(at,{text:U.recommendation.reason})]})},U.id))]}),S&&e.jsx(Zh,{performance:S.performance,freshness:S.freshness,timeseries:S.timeseries}),S?.profileCompleteness&&e.jsx(_h,{summary:S.profileCompleteness}),Z.length>0&&e.jsx(Gh,{locations:Z,lodging:V,places:te,placeActions:$,expandedLocation:r,onToggleExpanded:U=>{o(be=>be===U?null:U)}}),e.jsxs("div",{className:"mb-2",children:[e.jsxs("div",{className:"section-head section-head-inline mb-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search terms"}),w.data&&w.data.total>0&&e.jsxs("span",{className:"text-[11px] text-faint",children:[w.data.thresholdedPct,"% privacy-thresholded"]})]}),re.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"}),Y&&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:re.slice(0,25).map(U=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-neutral",children:U.keyword}),Y&&e.jsx("td",{className:"text-muted",children:k.find(be=>be.locationName===U.locationName)?.displayName??U.locationName}),e.jsx("td",{className:"text-right font-mono text-strong",children:U.valueCount!==null?U.valueCount.toLocaleString():e.jsxs("span",{className:"text-muted",title:"Privacy floor — Google withheld the exact count",children:["<",U.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-faint",children:[U.periodStart,"–",U.periodEnd]})]},`${U.locationName}:${U.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:()=>c(U=>!U),"aria-expanded":l,children:[e.jsx("span",{"aria-hidden":"true",children:l?"▾":"▸"})," Manage locations (",k.length,")"]}),l&&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"}),!ie()&&e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:k.map(U=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:U.displayName}),e.jsx("td",{className:"text-muted",children:U.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(oe,{tone:U.selected?"positive":"neutral",children:U.selected?"Tracked":"Not tracked"})}),!ie()&&e.jsx("td",{className:"text-right",children:e.jsx(nt,{type:"button",variant:"outline",size:"sm",disabled:q.isPending,onClick:()=>q.mutate({client:H,path:{name:t,locationName:U.locationName},body:{selected:!U.selected}}),children:U.selected?"Untrack":"Track"})})]},U.id))})]})})]})]})})}function _h({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:Nn(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:Nn(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:Nn(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:Nn(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:Nn(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(at,{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 ${Hh(a.tone)}`,children:a.value}),a.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-faint",children:a.detail})]},a.label))})]})}function Gh({locations:t,lodging:s,places:n,placeActions:a,expandedLocation:i,onToggleExpanded:r}){const o=new Map(s.map(u=>[u.locationName,u])),l=new Map(n.map(u=>[u.locationName,u])),c=new Map;for(const u of a){const m=c.get(u.locationName)??[];m.push(u),c.set(u.locationName,m)}return e.jsxs("div",{className:"mb-6",children:[e.jsxs("div",{className:"section-head section-head-inline mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Source evidence"}),e.jsx(at,{text:ie()?"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(u=>{const m=o.get(u.locationName)??null,h=l.get(u.locationName)??null,x=c.get(u.locationName)??[],N=i===u.locationName;return e.jsxs(d.Fragment,{children:[e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-strong",children:u.displayName}),e.jsx("p",{className:"mt-1 text-xs text-faint",children:u.primaryCategoryDisplayName??"Primary category not returned"}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[e.jsx(oe,{tone:u.selected?"positive":"neutral",children:u.selected?"Tracked":"Not tracked"}),u.openStatus&&u.openStatus!=="OPEN"&&e.jsx(oe,{tone:u.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:Do(u.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(qh,{location:u})}),e.jsx("td",{children:e.jsx(Fh,{lodging:m})}),e.jsx("td",{children:e.jsx(zh,{place:h,mapsUri:u.mapsUri})}),e.jsx("td",{children:e.jsx(Kh,{actions:x})}),e.jsx("td",{className:"text-right",children:e.jsx(L,{type:"button",variant:"outline",size:"sm",onClick:()=>r(u.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(Qh,{location:u,lodging:m,place:h,placeActions:x})})})]},u.id)})})]})})]})}function Oh(t){return[{label:"Description",tone:Rs(t.description)?"positive":"neutral",value:Rs(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:Rs(t.primaryPhone)?"positive":"neutral",value:Rs(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:Rs(t.websiteUri)?"positive":"neutral",value:Rs(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 qh({location:t}){const s=Oh(t);return e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>e.jsxs(oe,{tone:n.tone,children:[n.label," ",n.value]},n.label))})}function Fh({lodging:t}){return e.jsx(yi,{...Uh(t)})}function Uh(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 zh({place:t,mapsUri:s}){return e.jsx(yi,{...Bh(t,s)})}function Bh(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 Kh({actions:t}){return e.jsx(yi,{...Vh(t)})}function Vh(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 yi({tone:t,label:s,detail:n}){return e.jsxs("div",{children:[e.jsx(oe,{tone:t,children:s}),e.jsx("p",{className:"mt-1.5 text-xs leading-5 text-faint",children:n})]})}function Qh({location:t,lodging:s,place:n,placeActions:a}){const i=s?Xh(s.attributes):[];return e.jsxs("div",{className:"grid gap-5 text-xs lg:grid-cols-3",children:[e.jsxs(La,{title:"Owner profile · Business Information",children:[e.jsx(wt,{label:"Primary category",value:t.primaryCategoryDisplayName??"Not returned"}),e.jsx(wt,{label:"Secondary categories",value:t.additionalCategories.length>0?t.additionalCategories.join(", "):"Not returned"}),e.jsx(wt,{label:"Description",value:Rs(t.description)?t.description:"Not returned"}),e.jsx(wt,{label:"Hours",value:t.regularHours?"Returned by Google":"Not returned"}),e.jsx(wt,{label:"Service area",value:t.serviceArea?"Returned by Google":"Not returned"}),e.jsx(wt,{label:"Phone",value:t.primaryPhone??"Not returned"}),e.jsx(wt,{label:"Website",value:t.websiteUri??"Not returned"}),e.jsx(wt,{label:"Open status",value:Do(t.openStatus)}),e.jsx(wt,{label:"Opening date",value:t.openingDate??"Not returned"})]}),e.jsx(La,{title:"Hotel data · Lodging API",children:s?e.jsxs(e.Fragment,{children:[e.jsx(wt,{label:"Last checked",value:dr(s.syncedAt)}),e.jsx(wt,{label:"Groups returned",value:String(s.populatedGroupCount)}),e.jsx(wt,{label:"Populated groups",value:i.length>0?i.join(", "):"None returned"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Lodging API snapshot was stored for this location."})}),e.jsxs(La,{title:"Public listing + CTAs",children:[n?e.jsxs(e.Fragment,{children:[e.jsx(wt,{label:"Places tier",value:n.tier}),e.jsx(wt,{label:"Last checked",value:dr(n.syncedAt)}),e.jsx(wt,{label:"Public signals",value:n.amenities.length>0?n.amenities.join(", "):"No supported signals detected"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Places Details snapshot was stored for this location."}),t.mapsUri&&e.jsx("a",{href:t.mapsUri,target:"_blank",rel:"noopener noreferrer",className:"inline-block text-muted hover:text-neutral",children:"View on Google Maps →"}),e.jsx("div",{className:"mt-3 border-t border-default pt-3",children:a.length===0?e.jsx("p",{className:"leading-5 text-muted",children:"No placeActionLinks returned."}):e.jsx("div",{className:"grid gap-2",children:a.map(r=>e.jsxs("div",{className:"grid gap-0.5",children:[e.jsxs("span",{className:"font-medium text-neutral",children:[xa(r.placeActionType),r.isPreferred?" · preferred":""]}),e.jsxs("span",{className:"text-faint",children:[xa(r.providerType),r.uri?` · ${Yh(r.uri)}`:""]})]},r.placeActionLinkName))})})]})]})}function La({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 wt({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 Nn(t,s,n){return t===s?"positive":t===0?n:"caution"}function Hh(t){switch(t){case"positive":return"text-positive";case"caution":return"text-caution";case"negative":return"text-negative";case"neutral":return"text-neutral"}}function Wh(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function Rs(t){return typeof t=="string"&&t.trim().length>0}function Do(t){return t?xa(t):"Not returned"}function xa(t){return t?t.toLowerCase().split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"Unknown"}function Yh(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function dr(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Xh(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&Jh(n)).map(([s])=>xa(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function Jh(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function Zh({performance:t,freshness:s,timeseries:n}){const a=t.totals,i=fc.filter(f=>(a[f]??0)>0),r=bc.filter(f=>(a[f]??0)>0),o=Object.keys(a).filter(f=>(a[f]??0)>0&&yc(f)==="other").sort((f,w)=>(a[w]??0)-(a[f]??0)),l=Object.keys(a).filter(f=>(a[f]??0)===0).sort(),c=n.map(f=>{const w={date:f.date};for(const[b,A]of Object.entries(f.metrics))w[b]=A;return w}),u=n.find(f=>f.pending)?.date,m=n.length>0?n[n.length-1].date:void 0,h=c.length>0,x=s.dataThroughDate?`Data through ${pa(s.dataThroughDate)}${s.pendingDays>0?` · ${s.pendingDays}d pending`:""}`:null,N=[...i,...o];return e.jsxs("div",{className:"mb-6 grid gap-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Profile actions · daily"}),x&&e.jsx("span",{className:"text-[11px] text-muted",children:x})]}),!h||i.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No profile action activity yet — run a sync."}):e.jsxs(e.Fragment,{children:[e.jsx(ur,{data:c,metrics:i,kind:"line",firstPending:u,lastDate:m}),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:[ma(f)," ",e.jsx("span",{className:"font-mono text-heading",children:(a[f]??0).toLocaleString()})]},f))})]})]}),h&&r.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(ur,{data:c,metrics:r,kind:"area",firstPending:u,lastDate:m})]}),l.length>0&&e.jsxs("p",{className:"text-xs text-faint",children:["Not active: ",l.map(f=>ma(f)).join(", ")]})]})}function ur({data:t,metrics:s,kind:n,firstPending:a,lastDate:i}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(sn,{width:"100%",height:"100%",children:e.jsxs(nn,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(fi,{stroke:xi,vertical:!1}),e.jsx(an,{dataKey:"date",tick:Ot,tickLine:!1,axisLine:{stroke:us},tickFormatter:Ja,minTickGap:24}),e.jsx(rn,{tick:Ot,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(on,{...Ds,labelFormatter:pa,formatter:(r,o)=>[typeof r=="number"?r.toLocaleString():String(r??0),ma(String(o??""))]}),e.jsx(yo,{wrapperStyle:{fontSize:11,color:Ct.text},formatter:r=>ma(r)}),a&&i&&e.jsx(Fu,{x1:a,x2:i,fill:Ct.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:Ct.textDim,fontSize:10}}),s.map((r,o)=>n==="line"?e.jsx(bi,{type:"monotone",dataKey:r,stroke:kt[o%kt.length],strokeWidth:2,dot:!1,isAnimationActive:!1},r):e.jsx(Qs,{type:"monotone",dataKey:r,stackId:"reach",stroke:kt[o%kt.length],fill:kt[o%kt.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},r))]})})})}function em(t){return gi(ss(String(t)))}function tm(t){return Ns(ss(String(t)))}function Ea({children:t,label:s="More info",placement:n="top",className:a}){const i=d.useId(),[r,o]=d.useState(!1);return e.jsxs("span",{className:`relative inline-flex ${a??""}`,children:[e.jsx("button",{type:"button","aria-label":s,"aria-describedby":r?i:void 0,className:"inline-flex h-4 w-4 items-center justify-center rounded-full text-muted hover:text-strong focus:text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),onFocus:()=>o(!0),onBlur:()=>o(!1),children:e.jsx(Eu,{className:"h-3.5 w-3.5","aria-hidden":!0})}),r&&e.jsx("span",{id:i,role:"tooltip",className:`absolute z-50 w-64 rounded border border-strong bg-bg-elevated px-3 py-2 text-xs font-normal leading-relaxed text-strong shadow-lg ${n==="top"?"bottom-full mb-2":"top-full mt-2"} left-1/2 -translate-x-1/2 whitespace-normal`,children:t})]})}const Xn=Ht;function zs(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function Ia(t){return t.toLocaleString()}function sm(t){const s=Number(t);return Number.isFinite(s)?`${(s*100).toFixed(1)}%`:"—"}function nm(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 am(t){const s=t.filter(n=>n.kind===ws["backlink-extract"]&&!ro(n.status));return s.length===0?null:s.reduce((n,a)=>n.createdAt>a.createdAt?n:a)}function im(t,s){const n=new Date(t??s).getTime(),a=Math.max(0,Math.floor((Date.now()-n)/1e3));if(a<60)return`${a}s`;const i=Math.floor(a/60),r=a%60;return r===0?`${i}m`:`${i}m ${r}s`}function rm({projectName:t}){const[s,n]=d.useState(null),[a,i]=d.useState(null),[r,o]=d.useState([]),[l,c]=d.useState(null),[u,m]=d.useState(null),[h,x]=d.useState(null),[N,f]=d.useState(Date.now()),[w,b]=d.useState(0),[A,T]=d.useState(!0),[P,j]=d.useState(!1),[p,y]=d.useState(null),v=d.useCallback(async()=>{T(!0),y(null);try{const[J,ne,Z,Q,V]=await Promise.all([vc().catch(()=>null),jc(t,{excludeCrawlers:!0}).catch(()=>null),Nc(t,{limit:Xn,offset:w,excludeCrawlers:!0}).catch(te=>{if(te instanceof en&&te.code==="NOT_FOUND")return null;throw te}),wc(t).catch(()=>[]),Sc(t).catch(()=>[])]);c(J),n(ne),i(Z),o(Q);const $=am(V);m($)}catch(J){y(J instanceof Error?J.message:"Failed to load backlinks")}finally{T(!1)}},[t,w]);d.useEffect(()=>{v()},[v]),d.useEffect(()=>{if(!u)return;const J=u.id;let ne=!1;const Z=async()=>{try{const V=await Ya(J);if(ne)return;ro(V.status)?(m(null),x(V),await v()):m($=>$?.id===V.id?{...$,...V}:$)}catch{}},Q=window.setInterval(()=>{Z()},3e3);return()=>{ne=!0,window.clearInterval(Q)}},[u,v]),d.useEffect(()=>{if(!u)return;const J=window.setInterval(()=>f(Date.now()),1e3);return()=>window.clearInterval(J)},[u]),d.useEffect(()=>{if(!h||h.status==="failed")return;const J=window.setTimeout(()=>x(null),1e4);return()=>window.clearTimeout(J)},[h]);async function D(){j(!0),y(null);try{const J=await Cc(t);m(J)}catch(J){J instanceof en&&J.code==="MISSING_DEPENDENCY"?y("DuckDB is not installed. Visit the Backlinks admin page to install it."):y(J instanceof Error?J.message:"Failed to trigger extract")}finally{j(!1)}}const q=d.useMemo(()=>r.slice().sort((J,ne)=>J.queriedAt.localeCompare(ne.queriedAt)).map(J=>({date:J.queriedAt,linkingDomains:J.totalLinkingDomains})),[r]),S=a?.rows??[],k=a?.total??0,F=s?.excludedLinkingDomains??0,C=Math.floor(w/Xn)+1;return d.useEffect(()=>{w>0&&w>=k&&b(0)},[w,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"})]})}),p&&e.jsx(ye,{className:"surface-card p-4 mb-4 border-negative-800/60",children:e.jsx("p",{className:"text-sm text-negative",children:p})}),u&&e.jsx(ye,{className:"surface-card p-4 mb-4 border-info-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(It,{className:"h-5 w-5 text-info-400 animate-spin shrink-0 mt-0.5","aria-hidden":!0}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"Extract running"}),e.jsx(oe,{tone:"neutral",children:u.status}),e.jsxs("span",{className:"text-sm text-secondary tabular-nums",children:[im(u.startedAt??null,u.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."})]})]})}),h&&!u&&e.jsx(ye,{className:`surface-card p-4 mb-4 ${h.status==="failed"?"border-negative-800/60":"border-positive-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[h.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(xo,{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 ${h.status==="failed"?"text-negative":"text-positive"}`,children:h.status==="failed"?"Extract failed":"Extract complete"}),h.error?e.jsx("p",{className:"text-sm text-secondary mt-1",children:kc(h.error)}):h.status!=="failed"?e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),I()]});function I(){return A?e.jsx(ye,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading backlinks…"})}):me()}function me(){const J=s!==null&&s.totalLinkingDomains>0,ne=h?.status==="failed",Z=s!==null&&s.totalLinkingDomains===0&&!ne,Q=l?.status==="ready",V=l?.status==="failed",$=l&&(l.status==="downloading"||l.status==="querying"||l.status==="queued");return J?pe(e.jsxs(e.Fragment,{children:[!ie()&&e.jsxs(e.Fragment,{children:[e.jsxs(L,{type:"button",variant:"outline",size:"sm",disabled:P||u!==null,onClick:Ue(D),children:[e.jsx(go,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":P?"Queuing…":"Re-run extract"]}),e.jsx(Ea,{label:"About re-running",children:"Re-queries the current release for this project without downloading it again."})]}),!ie()&&e.jsx(L,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:zs("/backlinks"),children:"Open admin"})})]})):e.jsx(ye,{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(Lu,{className:"h-5 w-5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1",children:[!l&&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."}),!ie()&&e.jsx("div",{className:"mt-4",children:e.jsx(L,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:zs("/backlinks"),children:"Set up backlinks"})})})]}),$&&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 (",l.status,l.phaseDetail?` — ${l.phaseDetail}`:"","). Backlinks will appear here once it finishes."]}),!ie()&&e.jsx("div",{className:"mt-4",children:e.jsx(L,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:zs("/backlinks"),children:"View sync status"})})})]}),V&&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:l.error??"The workspace release sync failed. Retry from the Backlinks admin page."}),!ie()&&e.jsx("div",{className:"mt-4",children:e.jsx(L,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:zs("/backlinks"),children:"Go to Backlinks admin"})})})]}),Q&&!$&&!Z&&!ne&&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:l.release})," is ready. Run an extract for this project."]}),!ie()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(L,{type:"button",size:"sm",disabled:P||u!==null,onClick:Ue(D),children:[e.jsx(Ms,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":P?"Queuing…":"Run extract"]}),e.jsx(Ea,{label:"About extraction",children:"Queries the current release for this project without downloading it again."})]})]}),ne&&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."}),!ie()&&e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(L,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:zs("/backlinks"),children:"Go to Backlinks admin"})})})]}),Z&&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."]}),!ie()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(L,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:zs("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(L,{type:"button",variant:"outline",size:"sm",disabled:P||u!==null,onClick:Ue(D),children:[e.jsx(Ms,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":P?"Queuing…":"Re-run extract"]}),e.jsxs(Ea,{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 pe(J){if(!s)return null;const ne="Linking hosts",Z="linking hosts",Q="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:Ia(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 ",Z]}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:Ia(s.totalHosts)})}),e.jsxs("p",{className:"metric-card-sub",children:["aggregate ",Z," 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:sm(s.top10HostsShare)})}),e.jsxs("p",{className:"metric-card-sub",children:["share of ",Z," 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"})," · ",Q," ",e.jsx("code",{className:"text-secondary",children:s.release})," · queried ",nm(s.queriedAt),F>0&&e.jsxs(e.Fragment,{children:[" · ",F," excluded domain",F===1?"":"s"]})]}),q.length>=2&&e.jsxs(ye,{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(sn,{width:"100%",height:"100%",children:e.jsxs(nn,{data:q,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:kt[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:kt[0],stopOpacity:0})]})}),e.jsx(an,{dataKey:"date",tick:Ot,stroke:us,tickFormatter:em}),e.jsx(rn,{tick:Ot,stroke:us,allowDecimals:!1}),e.jsx(on,{contentStyle:Ds.contentStyle,labelStyle:Ds.labelStyle,itemStyle:Ds.itemStyle,labelFormatter:tm}),e.jsx(Qs,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:kt[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(ye,{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:ne})]})}),e.jsxs("tbody",{children:[S.map(V=>e.jsxs("tr",{className:"border-b border-mono-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-strong",children:V.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-secondary tabular-nums",children:Ia(V.numHosts)})]},V.linkingDomain)),S.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-muted",colSpan:2,children:F>0&&k===0?`Every referring domain in this ${Q} was a crawler/proxy host (${F} hidden).`:`No referring domains in this ${Q}.`})})]})]})}),e.jsx(Ts,{page:C,pageSize:Xn,visibleRows:S.length,totalRows:k,onPageChange:V=>b((V-1)*Xn)})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:J})]})}}function om({projectName:t}){const s=De({...Ac({client:H,path:{name:t}}),staleTime:oo}),n=s.data??null,a=s.error;if(s.isLoading&&!n)return null;if(a)return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsx("h2",{children:"Citation + answer-mention coverage"})]})}),e.jsx("p",{className:"text-sm text-negative-400",children:a instanceof Error?a.message:String(a)})]});if(!n)return null;if(n.status==="no-data")return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsx("h2",{children:"Citation + answer-mention coverage"})]})}),e.jsx("p",{className:"text-sm text-muted",children:n.reason==="no-queries"?"Add queries to start tracking AI citations.":"Run a sweep to see which engines cite this project."})]});const{providersCiting:i,providersMentioning:r,providersConfigured:o}=n.summary;return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsxs("h2",{className:"flex items-center gap-2",children:["Cited by ",i," of ",o," engines",e.jsx(at,{text:"An engine is ‘citing’ when our domain appears in its grounding source list (the structured citation/search-result attribution it returns alongside the answer). Counts each configured engine that cites the project on at least one tracked query in the latest snapshot per (query × provider)."})]}),e.jsxs("p",{className:"text-base text-neutral flex items-center gap-2",children:["Mentioned in ",r," of ",o," engine answers",e.jsx(at,{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(lm,{data:n}),e.jsx(cm,{data:n}),n.competitorGaps.length>0&&e.jsx(mm,{data:n})]})}function lm({data:t}){const{totalQueries:s,queriesCitedAndMentioned:n,queriesCitedOnly:a,queriesMentionedOnly:i,queriesInvisible:r}=t.summary;return e.jsxs("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4 mb-4",children:[e.jsx(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:`${i} / ${s}`,helper:"Named in answer, no source link",tone:i>0?"caution":"neutral"}),e.jsx(Jn,{label:"Invisible",value:`${r} / ${s}`,helper:"No engine cites or mentions",tone:r>0?"negative":"neutral"})]})}function Jn({label:t,value:s,helper:n,tone:a}){const i=a==="positive"?"text-positive":a==="positive-dim"?"text-positive-400/70":a==="caution"?"text-caution":a==="negative"?"text-negative":"text-heading";return e.jsxs("div",{className:"rounded-md border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:t}),e.jsx("p",{className:`mt-1 text-2xl font-semibold tabular-nums ${i}`,children:s}),e.jsx("p",{className:"text-[11px] text-muted",children:n})]})}function cm({data:t}){const s=d.useMemo(()=>{const n=new Set;for(const a of t.byQuery)for(const i of a.providers)n.add(i.provider);return Array.from(n).sort()},[t.byQuery]);return t.byQuery.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No query coverage rows."}):e.jsxs("div",{children:[e.jsx(dm,{}),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(Zs,{provider:n})},n)),e.jsx("th",{className:"text-right",children:"Cite"}),e.jsx("th",{className:"text-right",children:"Ment"})]})}),e.jsx("tbody",{children:t.byQuery.map(n=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:n.query}),s.map(a=>{const i=n.providers.find(r=>r.provider===a);return e.jsx("td",{className:"text-center",children:i==null?e.jsx(fo,{className:"inline h-3.5 w-3.5 text-mono-700","aria-label":"no data"}):e.jsx(um,{provider:i})},a)}),e.jsx("td",{className:"text-right tabular-nums",children:e.jsxs("span",{className:n.totalProviders>0&&n.citedCount===n.totalProviders?"text-positive":n.citedCount>0?"text-positive-400/70":"text-muted",children:[n.citedCount,"/",n.totalProviders]})}),e.jsx("td",{className:"text-right tabular-nums",children:e.jsxs("span",{className:n.totalProviders>0&&n.mentionedCount===n.totalProviders?"text-info-300":n.mentionedCount>0?"text-info-400/70":"text-muted",children:[n.mentionedCount,"/",n.totalProviders]})})]},n.queryId))})]})})]})}function dm(){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(Hs,{active:!0,tone:"cited"}),e.jsx("span",{children:"cited (in sources)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Hs,{active:!0,tone:"mentioned"}),e.jsx("span",{children:"mentioned (in answer)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Hs,{active:!1,tone:"cited"}),e.jsx(Hs,{active:!1,tone:"mentioned"}),e.jsx("span",{children:"neither"})]})]})}function um({provider:t}){const s=hm(t);return e.jsxs("span",{className:"inline-flex items-center justify-center gap-1",title:s,children:[e.jsx(Hs,{active:t.cited,tone:"cited"}),e.jsx(Hs,{active:t.mentioned,tone:"mentioned"})]})}function hm(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 Hs({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 mm({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(at,{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(Zs,{provider:s.provider})}),e.jsx("td",{className:"text-neutral",children:s.citingCompetitors.join(", ")})]},`${s.queryId}::${s.provider}`))})]})})]})}const Fn="__cited__",Un="__mentioned__",Gt="__mentionShare__";function To(t){const s=t,{dataStartDate:n,dataEndDate:a}=s;return typeof n!="string"||typeof a!="string"?null:{start:ss(n),end:ss(a),sweepCount:s.sweepCount??1}}function ga(t){const s=To(t);if(!s)return"Sweep date unavailable";const n=Ns(s.start),a=Ns(s.end);return n===a?n:`${n} – ${a} · ${s.sweepCount} sweeps combined`}function pm(t){const s=To(t);return s?gi(s.start):""}function cn(t){return t.trim().toLowerCase()}function si(t){return Math.round(t*1e3)/10}function ni(t){return t.byProvider??{}}function xm(t,s,n){const a=t.buckets.length>0,i=t.buckets.length===1;if(n==="overall"){const c=s==="cited"?Fn:Un,u=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(h=>({date:h.startDate,[c]:si(h[u])})),series:[c],hasData:a,singleBucket:i}}const r=s==="mentioned"?"mentionRate":"citationRate",o=[...new Set(t.buckets.flatMap(c=>Object.keys(ni(c))))].sort();return{rows:t.buckets.map(c=>{const u={date:c.startDate},m=ni(c);for(const h of o){const x=m[h];u[h]=x?si(x[r]):null}return u}),series:o,hasData:a,singleBucket:i}}function Mo(t){const s=t;return Object.hasOwn(s,"modelEvidenceByProvider")?s.modelEvidenceByProvider??{}:null}function gm(t){const s=t;return Object.hasOwn(s,"modelAttribution")?s.modelAttribution??{}:null}function fm(t){return t.servedModelAttribution??{}}function bm(t){return t.modelServiceMismatch??{}}function ym(t){return t.modelPointerChanges??{}}function vm(t){return t.length>0?t.join(", "):null}function hr(t,s){const n=cn(s);return Object.entries(t).find(([a])=>cn(a)===n)?.[1]}function rs(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 jm(t,s){for(let n=t.length-1;n>=0;n-=1){const a=t[n];if(!hr(ni(a),s))continue;const i=Mo(a);return i?hr(i,s)??null:null}return null}function Nm(t){const s=new Map;for(const[n,a]of Object.entries(t))for(const i of a.events){const r=s.get(i.bucketStartDate)??[];r.push({provider:n,event:i}),s.set(i.bucketStartDate,r)}return[...s.entries()].sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>({bucketStartDate:n,events:[...a].sort((i,r)=>i.provider.localeCompare(r.provider)||i.event.observedAt.localeCompare(r.event.observedAt))}))}function wm(t){const s={},n=[];for(const[a,i]of Object.entries(t)){const r=i.events.filter(o=>!o.fromPreWindowAnchor);for(const o of i.events)o.fromPreWindowAnchor&&n.push({provider:a,event:o});r.length>0&&(s[a]={...i,events:r})}return{buckets:Nm(s),beforeWindow:n.sort((a,i)=>a.event.observedAt.localeCompare(i.event.observedAt)||a.provider.localeCompare(i.provider))}}function Sm(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 km(t){const s=[];for(const[n,a]of Object.entries(t)){const i=a.eventTotal??a.events.length;i>a.events.length&&s.push({provider:n,shown:a.events.length,total:i})}return s.sort((n,a)=>n.provider.localeCompare(a.provider))}function Cm(t){const s=t.buckets.map(a=>{const i=a.mentionShare;return{date:a.startDate,[Gt]:i?.rate==null?null:si(i.rate)}}),n=s.map(a=>a[Gt]).filter(a=>typeof a=="number"&&Number.isFinite(a));return{rows:s,series:[Gt],hasData:n.length>0,singleBucket:n.length===1}}function Am(t,s,n){return s==="mentionShare"?Cm(t):xm(t,s,n)}function mr(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 pr(t){const[,s,n]=t.slice(0,10).split("-");return!s||!n?t:`${s}/${n}`}function xr(t){return t>0?`+${t}`:`${t}`}function $m(t){if(t.length===0)return null;if(t.length<=2)return`Query set changed: ${t.map(n=>`${xr(n.delta)} on ${pr(n.date)}`).join(", ")}`;const s=[...t].sort((n,a)=>a.date.localeCompare(n.date))[0];return`Query set changed ${t.length} times (latest ${xr(s.delta)} on ${pr(s.date)})`}const Pm=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],Rm=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],Lm=[{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."}],vi=kt[2],Em="var(--chart-tooltip-bg)",Im={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",local:"Local"};function ls(t){const s=cn(t);return Im[s]??t.charAt(0).toUpperCase()+t.slice(1)}function vs(t){return Math.round(t*10)/10}function Dm(t){return t===Fn||t===Un||t===Gt}function _o(t){return t===Fn?"Cited":t===Un?"Mentioned":t===Gt?"Mention share":ls(t)}function $n(t,s){return t===Fn?cs.positive:t===Un?kt[1]:t===Gt?vi:_u(cn(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 Mm(t){return t.map(s=>s.trim().toLowerCase()).filter(Boolean).sort().join(`
|
|
6
6
|
`)}function da(t){return t==="cited"?"Cited":t==="mentionShare"?"Mention share":"Mentioned"}function Gn(t){return t==="cited"?"citationRate":"mentionRate"}function Go(t,s){return s==="cited"?t.cited:t.mentionedCount}function Oo(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 qo(t,s){if(s===void 0)return null;const n=String(s);return t.find(a=>a.startDate===n)??null}function ai(t){const s=Mo(t);if(s===null)return"Model attribution unavailable for this bucket.";const n=Object.entries(s).sort(([a],[i])=>cn(a).localeCompare(cn(i))).map(([a,i])=>`${ls(a)}: ${rs(i)}`);return n.length>0?`Model evidence: ${n.join("; ")}`:"No model evidence in this bucket."}function _m(t){return t.some(({event:s})=>s.to.status==="mixed")?cs.caution:t.some(({event:s})=>s.to.status==="unknown")?cs.negative:t.every(({event:s})=>s.from.status==="known"&&s.to.status==="known")?kt[4]:cs.positive}function Gm(t,s,n){const a=qo(t,s);return a?ga(a):Ns(ss(n))}function Om({partition:t,available:s,counts:n,truncated:a,incompleteHistory:i,served:r,mismatch:o,buckets:l}){const c=d.useId(),u=Object.entries(r).sort(([h],[x])=>h.localeCompare(x)),m=t.buckets.length>0||t.beforeWindow.length>0;return e.jsxs("aside",{className:"trend-model-evidence","aria-labelledby":"trend-model-evidence-title","aria-describedby":c,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:c,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?m?e.jsxs(e.Fragment,{children:[t.buckets.length>0&&e.jsx("ul",{className:"trend-model-evidence-list",children:t.buckets.flatMap(({bucketStartDate:h,events:x})=>x.map(({provider:N,event:f})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:Gm(l,h,f.observedAt)}),e.jsxs("span",{children:[ls(N),": ",rs(f.from)," → ",rs(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:h,event:x})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsxs("span",{className:"trend-model-evidence-date",children:["on or before ",Ns(ss(x.observedAt))]}),e.jsxs("span",{children:[ls(h),": ",rs(x.from)," → ",rs(x.to),x.anchorObservedAt?` (last seen ${rs(x.from)} on ${Ns(ss(x.anchorObservedAt))})`:""]})]},`before-${h}-${x.observedAt}`))})]}),a.map(h=>e.jsxs("p",{className:"trend-model-evidence-note",children:[ls(h.provider),": showing the most recent ",h.shown," of ",h.total," changes."]},`truncated-${h.provider}`)),i.map(h=>e.jsxs("p",{className:"trend-model-evidence-note",children:["We did not look far enough back to be sure this is every ",ls(h)," change."]},`incomplete-${h}`))]}):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."}),u.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:u.map(([h,x])=>{const N=vm(x.latestServedModelIds),f=o[h];return e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:Ns(ss(x.latestObservation.observedAt))}),e.jsxs("span",{children:[ls(h),": ",N??rs(x.latestObservation.state),f?` — not the ${rs(f.configured)} you selected`:""]})]},`served-${h}`)})})]})]})}function gr(t){return t===null?"no data":`${t}%`}function Da(t){return t==null?"undefined":`${vs(t*100)}%`}function qm({active:t,label:s,payload:n,metric:a,mode:i,buckets:r}){if(!t)return null;const o=qo(r,s);if(!o)return null;if(a==="mentionShare"){const c=o.mentionShare.projectMentionSnapshots,u=o.mentionShare.competitorMentionSnapshots,m=c+u,h=o.mentionShare.rate==null?null:vs(o.mentionShare.rate*100);return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:ga(o)}),e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch trend-tooltip-swatch-ring",style:{borderColor:vi},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:"Mention share"}),e.jsx("span",{className:"trend-tooltip-value",children:gr(h)})]}),m>0?e.jsxs("p",{className:"trend-tooltip-detail",children:["You ",c," / ",m," brand mentions. Competitors ",u,"."]}):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:ai(o)})]})}const l=i==="byProvider"?(n??[]).filter(c=>c.dataKey!==void 0):[{dataKey:a==="cited"?Fn:Un,value:vs(o[Gn(a)]*100)}];return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:ga(o)}),l.map((c,u)=>{const m=String(c.dataKey??c.name??""),h=i==="byProvider"?Oo(o,m,a):null,x=h?.count??Go(o,a),N=h?.total??o.total,f=typeof c.value=="number"?c.value:vs(h?h.rate*100:o[Gn(a)]*100),w=c.color??$n(m,u);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:w},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:_o(m)}),e.jsx("span",{className:"trend-tooltip-value",children:gr(f)})]}),e.jsxs("p",{className:"trend-tooltip-detail",children:[x," / ",N," snapshots, ",a==="cited"?"source links":"answer text"]})]},`${m}-${u}`)}),e.jsx("p",{className:"trend-tooltip-detail",children:ai(o)})]})}function Fm({buckets:t,metric:s,mode:n,series:a}){return e.jsxs("table",{className:"sr-only",children:[e.jsxs("caption",{children:[da(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(i=>{let r;if(s==="mentionShare"){const o=i.mentionShare.projectMentionSnapshots,l=i.mentionShare.competitorMentionSnapshots,c=o+l;r=c>0?`${Da(i.mentionShare.rate)} mention share, ${o} of ${c} brand mentions were you`:"mention share undefined, no project or competitor brand mentions"}else n==="byProvider"?r=a.map(o=>{const l=Oo(i,o,s);return l?`${ls(o)} ${Da(l.rate)} ${da(s).toLowerCase()}, ${l.count} of ${l.total} snapshots`:`${ls(o)} no data`}).join("; "):r=`${Da(i[Gn(s)])} ${da(s).toLowerCase()}, ${Go(i,s)} of ${i.total} snapshots`;return r+=`; ${ai(i)}`,e.jsxs("tr",{children:[e.jsx("th",{scope:"row",children:ga(i)}),e.jsx("td",{children:r})]},i.startDate)})})]})}function Ta({options:t,value:s,onChange:n,ariaLabel:a,className:i}){const r=d.useId();return e.jsx("div",{role:"group","aria-label":a,className:`segmented ${i??""}`,children:t.map(o=>{const l=s===o.value,c=o.description?`${r}-${o.value}-description`:void 0;return e.jsxs(d.Fragment,{children:[e.jsx("button",{type:"button","aria-pressed":l,"aria-describedby":c,className:`segmented-option ${l?"segmented-option-active":""}`,onClick:()=>n(o.value),children:o.label}),o.description&&e.jsx("span",{id:c,className:"sr-only",children:o.description})]},o.value)})})}function Um({projectName:t,competitorDomains:s=[],analyticsRevision:n="none"}){const[a,i]=d.useState("all"),[r,o]=d.useState("mentioned"),[l,c]=d.useState("byProvider"),u=d.useMemo(()=>Mm(s),[s]),m=De({queryKey:["analytics-metrics",t,a,u,n],queryFn:()=>$c(t,a),staleTime:oo}),h=m.data??null,x=m.error,N=r==="mentionShare"?"overall":l,f=d.useMemo(()=>h?Am(h,r,N):null,[h,r,N]),w=h?gm(h):null,b=d.useMemo(()=>wm(w??{}),[w]),A=d.useMemo(()=>Sm(w??{}),[w]),T=d.useMemo(()=>km(w??{}),[w]),P=d.useMemo(()=>Object.entries(w??{}).filter(([,Q])=>Q.anchorUnavailable).map(([Q])=>Q).sort(),[w]),j=d.useMemo(()=>h?fm(h):{},[h]),p=d.useMemo(()=>h?bm(h):{},[h]),y=d.useMemo(()=>h?Pc(ym(h)):null,[h]),v=r!=="mentionShare"&&N==="byProvider",D=da(r),q=r==="cited"?cs.positive:r==="mentionShare"?vi:kt[1],S=v?Ct.textDim:q,k=h?.buckets??[],F=d.useMemo(()=>{const Q=new Map(k.map(V=>[V.startDate,pm(V)]));return V=>Q.get(String(V))??""},[k]),C=r==="mentionShare"?f?mr(f.rows,Gt):null:k.length>0?vs(k[k.length-1][Gn(r)]*100):null,I=r==="mentionShare"?f?Tm(f.rows,Gt):null:k.length>0?vs(k[0][Gn(r)]*100):null,me=r==="mentionShare"?f?.rows.filter(Q=>typeof Q[Gt]=="number").length??0:k.length,pe=C!==null&&I!==null&&me>1?vs(C-I):null,J=s.length,ne=e.jsxs(e.Fragment,{children:[y?.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:y.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(at,{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."})]})]}),C!==null&&e.jsxs("div",{className:"visibility-trend-current",children:[e.jsx("span",{className:"visibility-trend-current-dot",style:{backgroundColor:S},"aria-hidden":"true"}),e.jsx("span",{className:"visibility-trend-current-label",children:D}),v&&e.jsx("span",{className:"visibility-trend-current-qualifier",children:"avg"}),e.jsxs("span",{className:"visibility-trend-current-value",children:[C,"%"]}),pe!==null&&e.jsxs("span",{className:`visibility-trend-current-delta ${pe>0?"text-positive-400":pe<0?"text-negative-400":"text-muted"}`,children:[pe>0?"+":"",pe.toFixed(1)," pts"]})]})]}),e.jsxs("div",{className:"visibility-trend-controls",children:[e.jsx(Ta,{options:Lm,value:r,onChange:o,ariaLabel:"Metric",className:"visibility-trend-metric-control"}),r!=="mentionShare"&&e.jsx(Ta,{options:Rm,value:l,onChange:c,ariaLabel:"Series"}),e.jsx(Ta,{options:Pm,value:a,onChange:i,ariaLabel:"Time window",className:"sm:ml-auto"})]}),y?.kind==="no-known-change"&&e.jsxs("p",{className:"mt-3 text-[11px] leading-snug text-muted",children:[y.text,e.jsx(at,{text:y.detail})]})]});let Z;if(x)Z=e.jsx("p",{className:"text-sm text-negative-400",children:x instanceof Error?x.message:String(x)});else if(m.isLoading&&!h)Z=e.jsx("div",{className:"visibility-trend-chart animate-pulse rounded-lg bg-bg-elevated/40","aria-hidden":"true"});else if(r==="mentionShare"&&J===0)Z=e.jsx("p",{className:"text-sm text-secondary",children:"Add tracked competitors to measure mention share over time."});else if(!h||!f)Z=null;else{const{rows:Q,series:V,hasData:$,singleBucket:te}=f,ce=$m(h.queryChanges);if(!$)Z=e.jsx("p",{className:"text-sm text-secondary",children:r==="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(v&&V.length===0)Z=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 re=`${D} rate across ${Q.length} ${Q.length===1?"sweep":"sweeps"}. Latest ${C}%${pe!==null?`, ${pe>=0?"up":"down"} ${Math.abs(pe).toFixed(1)} points over the period`:""}.`;Z=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"sr-only",children:re}),e.jsx(Fm,{buckets:k,metric:r,mode:N,series:V}),v&&V.length>0&&e.jsx("ul",{className:"trend-legend","aria-label":"Engines",children:V.map((Y,fe)=>{const U=mr(Q,Y),be=jm(k,Y),Ce=w===null?"Attribution unavailable":be?rs(be):"No observed model evidence";return e.jsxs("li",{className:"trend-legend-item",children:[e.jsx("span",{className:"trend-legend-swatch",style:{backgroundColor:$n(Y,fe)},"aria-hidden":"true"}),e.jsxs("span",{className:"trend-legend-label",children:[e.jsx("span",{className:"trend-legend-name",children:_o(Y)}),e.jsxs("span",{className:"trend-legend-model",children:[e.jsx("span",{"aria-hidden":"true",children:"· "}),Ce]})]}),U!==null&&e.jsxs("span",{className:"trend-legend-value",children:[U,"%"]})]},Y)})}),e.jsx("div",{className:"visibility-trend-chart",role:"img","aria-label":`${D} trend chart over ${Q.length} ${Q.length===1?"bucket":"buckets"}`,children:e.jsx(sn,{width:"100%",height:"100%",children:e.jsxs(nn,{data:Q,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(fi,{stroke:xi,vertical:!1}),e.jsx(an,{dataKey:"date",tick:Ot,tickLine:!1,axisLine:{stroke:us},tickFormatter:F,minTickGap:24}),e.jsx(rn,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:Y=>`${Y}%`,tick:Ot,tickLine:!1,axisLine:!1,width:40}),e.jsx(on,{cursor:{stroke:us,strokeWidth:1},content:e.jsx(qm,{metric:r,mode:N,buckets:k})}),b.buckets.map(({bucketStartDate:Y,events:fe})=>e.jsx(Uu,{x:Y,stroke:_m(fe),strokeDasharray:"4 4",strokeWidth:1.5,ifOverflow:"extendDomain"},`model-evidence-${Y}`)),V.map((Y,fe)=>e.jsx(bi,{type:"monotone",dataKey:Y,name:Y,stroke:$n(Y,fe),strokeDasharray:Y===Gt?"5 4":void 0,strokeWidth:Dm(Y)?2.5:2,dot:Y===Gt?{r:2.75,fill:"var(--chart-tooltip-bg)",stroke:$n(Y,fe),strokeWidth:1.5}:{r:2.5,fill:$n(Y,fe),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:Em},connectNulls:Y!==Gt,isAnimationActive:!1},Y))]})})}),e.jsx(Om,{partition:b,available:w!==null,counts:A,truncated:T,incompleteHistory:P,served:j,mismatch:p,buckets:k}),te&&e.jsx("p",{className:"visibility-trend-note",children:r==="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."}),ce&&e.jsx("p",{className:"visibility-trend-note",children:ce})]})}}return e.jsxs("section",{className:"visibility-trend",children:[ne,Z]})}const fr=new Set([En.queued,En.running]);function zm({projectName:t}){const s=Ss(),[n,a]=d.useState(""),[i,r]=d.useState(""),[o,l]=d.useState(""),[c,u]=d.useState("__default__"),[m,h]=d.useState(null),x=De({...Rc({client:H,path:{name:t}}),staleTime:6e4}),N=De({...lo({client:H}),staleTime:6e4}),f=De({...Lc({client:H,path:{name:t},query:{limit:20}}),refetchInterval:S=>S.state.data?.runs.some(k=>fr.has(k.status))?3e3:!1}),w=f.data?.runs??[];d.useEffect(()=>{!m&&w[0]&&h(w[0].id)},[w,m]);const b=w.find(S=>S.id===m)??null,A=De({...Ec({client:H,path:{name:t,runId:m??""}}),enabled:!!m,refetchInterval:b&&fr.has(b.status)?3e3:!1}),T=A.data??null,P=d.useMemo(()=>Vm(n),[n]),j=x.data?.locations??[],p=d.useMemo(()=>{const S=new Map((N.data?.providerCatalog??[]).map(k=>[k.name,k]));return(N.data?.providers??[]).filter(k=>k.configured&&S.get(k.name)?.mode==="api").map(k=>({...k,catalog:S.get(k.name)}))},[N.data]),y=!N.isLoading&&p.length===0,v=p.find(S=>S.name===i)??null;d.useEffect(()=>{i&&!v&&(r(""),l(""))},[i,v]);const D=Mn({...Ic(),onSuccess:async S=>{h(S.id),a(""),l(""),await Ym(s),$e({title:"Research batch saved",detail:`${S.totalQueries} quer${S.totalQueries===1?"y is":"ies are"} in research history. Nothing was added to tracked queries.`,tone:"positive",dedupeKey:`research:start:${S.id}`,dedupeMode:"replace"})},onError:S=>{$e({title:"Could not start research",detail:S instanceof Error?S.message:"Check the provider, model, and location, then try again.",tone:"negative"})}});function q(){if(P.length===0||P.length>50||y||D.isPending||ie())return;const S=c==="__default__"?void 0:c==="__none__"?null:j.find(k=>k.label===c)??void 0;D.mutate({client:H,path:{name:t},body:{queries:P,...i?{provider:i}:{},...i&&o.trim()?{model:o.trim()}:{},...S!==void 0?{location:S}:{}}})}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(ye,{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
|
|
7
7
|
e.g. What is the best way to choose an AEO platform?`,value:n,onChange:S=>a(S.target.value),"aria-describedby":"research-query-count"}),e.jsxs("span",{id:"research-query-count",className:`mt-1 block text-[11px] ${P.length>50?"text-negative":"text-faint"}`,children:[P.length," ",P.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:i,onChange:S=>{r(S.target.value),l("")},children:[e.jsx("option",{value:"",children:"Project default"}),p.map(S=>e.jsx("option",{value:S.name,children:S.displayName??S.name},S.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:c,onChange:S=>u(S.target.value),children:[e.jsx("option",{value:"__default__",children:"Project default"}),e.jsx("option",{value:"__none__",children:"No location"}),j.map(S=>e.jsx("option",{value:S.label,children:S.label},S.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:v?`Default: ${v.model??v.defaultModel??v.catalog.defaultModel}`:"Choose a provider to select an exact model",value:o,disabled:!v,onChange:S=>l(S.target.value)}),e.jsx("datalist",{id:"research-known-models",children:(v?.catalog.knownModels??[]).map(S=>e.jsx("option",{value:S.id,children:S.displayName},S.id))})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 border-t border-default pt-4",children:[!ie()&&e.jsxs(nt,{type:"button",size:"sm",disabled:P.length===0||P.length>50||y||D.isPending,onClick:q,children:[e.jsx(Ms,{size:14}),D.isPending?"Starting research…":`Run ${P.length||""} research ${P.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."})]}),y&&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(ye,{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(oe,{tone:"neutral",children:"Loading"})]}),w.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:w.map(S=>e.jsxs("tr",{className:m===S.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:()=>h(S.id),children:Qm(S.createdAt)})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:S.provider}),e.jsx("span",{className:"font-mono text-[11px] text-muted",children:S.requestedModel??S.resolvedModel})]}),e.jsx("td",{className:"text-secondary",children:S.location?.label??"No location"}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[S.completedQueries+S.failedQueries,"/",S.totalQueries]}),e.jsx("td",{children:e.jsx(oe,{tone:Fo(S.status),children:S.status})})]},S.id))})]})})]})]}),e.jsx(Bm,{detail:T,isLoading:A.isFetching})]})}function Bm({detail:t,isLoading:s}){const[n,a]=d.useState(null);d.useEffect(()=>{a(t?.queries[0]?.id??null)},[t?.id]);const i=t?.queries.find(r=>r.id===n)??t?.queries[0]??null;return e.jsxs(ye,{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 ${Hm(t.id)}`:"Choose a research batch"})]}),t&&e.jsx(oe,{tone:Fo(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(r=>e.jsxs("tr",{className:i?.id===r.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(r.id),children:r.query})}),e.jsx("td",{children:e.jsx(oe,{tone:Wm(r.status),children:r.status})}),e.jsx("td",{children:e.jsx(oe,{tone:r.answerMentioned===!0?"positive":r.answerMentioned===!1?"neutral":r.status===Es.failed?"negative":"caution",children:r.answerMentioned===null?r.status===Es.failed?"Unavailable":"Pending":r.answerMentioned?"Mentioned":"Not mentioned"})}),e.jsx("td",{children:e.jsx(oe,{tone:r.citationState==="cited"?"positive":r.citationState==="not-cited"?"neutral":r.status===Es.failed?"negative":"caution",children:r.citationState===null?r.status===Es.failed?"Unavailable":"Pending":r.citationState==="cited"?"Cited":"Not cited"})})]},r.id))})]})}),e.jsx(Km,{query:i,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 Km({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===Es.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 i=Ps(n.uri),r=n.title||n.uri;return e.jsxs("li",{className:"flex min-w-0 items-start gap-1.5 text-sm",children:[i?e.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",className:"truncate text-secondary hover:text-link focus:outline-none focus:underline",children:r}):e.jsx("span",{className:"truncate text-secondary",children:r}),i&&e.jsx(bo,{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 Vm(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 Qm(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 Hm(t){return t.length>8?t.slice(0,8):t}function Fo(t){return t===En.completed?"positive":t===En.partial?"caution":t===En.failed?"negative":"neutral"}function Wm(t){return t===Es.completed?"positive":t===Es.failed?"negative":"neutral"}async function Ym(t){await pt(t,"researchRuns")}const ii=new Set(["queued","seeding","probing"]);function Xm({projectName:t}){const[s,n]=d.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(Jm,{projectName:t}):e.jsx(zm,{projectName:t})})]})}function Jm({projectName:t}){const s=Ss(),[n,a]=d.useState(null),[i,r]=d.useState(""),[o,l]=d.useState("100"),c=De({...Dc({client:H,path:{name:t},query:{limit:"10"}}),refetchInterval:p=>p.state.data?.some(v=>ii.has(v.status))?3e3:!1}),u=c.data??[];d.useEffect(()=>{!n&&u[0]&&a(u[0].id)},[n,u]);const m=u.find(p=>p.id===n)??null,h=De({...Tc({client:H,path:{name:t,id:n??""}}),enabled:!!n,refetchInterval:m&&ii.has(m.status)?3e3:!1}),x=h.data??null,N=De({...Mc({client:H,path:{name:t,id:n??""}}),enabled:!!(n&&m?.status==="completed")}),f=Mn({mutationFn:()=>{const p={},y=i.trim();y&&(p.icpDescription=y);const v=Number.parseInt(o,10);return Number.isFinite(v)&&v>0&&(p.maxProbes=v),_c(t,p)},onSuccess:async p=>{a(p.sessionId),r(""),await yr(s,t,p.sessionId),$e({title:"Discovery started",detail:`Run ${Ma(p.sessionId)} is testing questions your customers might ask.`,tone:"neutral",dedupeKey:`discovery:start:${p.sessionId}`,dedupeMode:"replace"})},onError:p=>{$e({title:"Discovery failed to start",detail:p instanceof Error?p.message:"Could not start discovery.",tone:"negative"})}}),w=Mn({mutationFn:p=>{if(!n)throw new Error("Select a completed discovery session first.");return Gc(t,n,p)},onSuccess:async p=>{await yr(s,t,p.sessionId),s.invalidateQueries({queryKey:co({client:H})}),s.invalidateQueries({predicate:y=>Array.isArray(y.queryKey)&&y.queryKey[0]==="projects"&&y.queryKey.length>1}),$e({title:"Queries added",detail:sp(p),tone:"positive",dedupeKey:`discovery:promote:${p.sessionId}`,dedupeMode:"replace"})},onError:p=>{$e({title:"Could not add queries",detail:p instanceof Error?p.message:"Could not add queries from this run.",tone:"negative"})}}),b=x??m,A=N.data??null,T=(A?.queriesByBucket.cited.length??0)+(A?.queriesByBucket.aspirational.length??0),P=d.useMemo(()=>(x?.probes??[]).slice(0,30),[x?.probes]);async function j(){try{const p=await c.refetch();if(p.error)throw p.error;const y=p.data?.length??0;$e({title:"Discovery sessions refreshed",detail:`${y} recent session${y===1?"":"s"} loaded.`,tone:"positive",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}catch(p){$e({title:"Discovery refresh failed",detail:p instanceof Error?p.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:ie()?"Generate customer questions and check whether your site is already visible.":"Generate customer questions, check current visibility, then choose what to track."})]}),e.jsxs(L,{type:"button",variant:"outline",size:"sm",disabled:c.isFetching,onClick:()=>{j()},children:[e.jsx(Is,{className:`size-3.5 ${c.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(ye,{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(oe,{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:i,onChange:p=>r(p.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:p=>l(p.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."})]}),!ie()&&e.jsxs(nt,{type:"button",size:"sm",disabled:f.isPending,onClick:()=>f.mutate(),children:[e.jsx(Ms,{size:14}),f.isPending?"Starting…":"Find queries"]})]})]}),e.jsxs(ye,{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"})]}),c.isFetching&&e.jsx(oe,{tone:"neutral",children:"Loading"})]}),u.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:u.map(p=>e.jsxs("button",{type:"button",className:`w-full rounded-md border px-3 py-2 text-left transition-colors ${n===p.id?"border-mono-600 bg-bg-elevated/70":"border-default bg-bg/40 hover:border-strong hover:bg-bg-elevated/40"}`,onClick:()=>a(p.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:Ma(p.id)}),e.jsx(oe,{tone:br(p.status),children:p.status})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-sm text-secondary",children:[e.jsxs("span",{children:["Cited queries ",p.citedCount??0]}),e.jsxs("span",{children:["Worth tracking ",p.aspirationalCount??0]}),e.jsxs("span",{children:["Skip ",p.wastedCount??0]})]})]},p.id))})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(ye,{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:b?Ma(b.id):"No run selected"})]}),b&&e.jsx(oe,{tone:br(b.status),children:b.status})]}),b?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(bs,{label:"Questions tested",value:b.probeCount??0}),e.jsx(bs,{label:"Cited queries",value:b.citedCount??0,tone:"positive"}),e.jsx(bs,{label:"Worth tracking",value:b.aspirationalCount??0,tone:"caution"}),e.jsx(bs,{label:"Skip",value:b.wastedCount??0,tone:"negative"})]}),b.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:b.error}),b.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:b.warning}),b.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:b.icpDescription})]}),b.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:b.competitorMap.slice(0,8).map(p=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[p.domain," ",e.jsx("span",{className:"text-muted",children:p.hits})]},p.domain))})]})]}):e.jsx("p",{className:"text-sm text-secondary",children:"Start a run above, or pick one from Recent runs to see its progress."})]}),b?.status==="completed"&&e.jsxs(ye,{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"})]}),!ie()&&e.jsxs(nt,{type:"button",size:"sm",disabled:w.isPending||T===0,onClick:()=>w.mutate(void 0),children:[e.jsx(xo,{size:14}),w.isPending?"Adding…":"Add recommended queries"]})]}),N.isLoading?e.jsx("p",{className:"text-sm text-muted",children:"Loading recommendations…"}):A?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(bs,{label:"Queries to add",value:T,tone:"positive"}),e.jsx(bs,{label:"Cited queries",value:A.queriesByBucket.cited.length,tone:"positive"}),e.jsx(bs,{label:"Worth tracking",value:A.queriesByBucket.aspirational.length,tone:"caution"}),e.jsx(bs,{label:"Skip",value:A.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."}),A.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:A.suggestedCompetitors.map(p=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[p.domain," ",e.jsx("span",{className:"text-muted",children:p.hits})]},p.domain))})]})]}):e.jsx("p",{className:"text-sm text-muted",children:"No recommendations available for this run."})]}),e.jsxs(ye,{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"})]}),h.isFetching&&e.jsx(oe,{tone:"neutral",children:"Loading"})]}),P.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:P.map(p=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:p.query}),e.jsx("td",{children:e.jsx(oe,{tone:Zm(p.bucket),children:tp(p.bucket)})}),e.jsx("td",{className:"text-secondary",children:p.citedDomains.length>0?p.citedDomains.slice(0,3).join(", "):"-"})]},p.id))})]})})]})]})]})]})}function bs({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 br(t){return t==="completed"?"positive":t==="failed"?"negative":ii.has(t)?"caution":"neutral"}function Zm(t){return t==="cited"?"positive":t==="aspirational"?"caution":t==="wasted-surface"?"negative":"neutral"}const ep={cited:"Cited queries",aspirational:"Worth tracking","wasted-surface":"Skip"};function tp(t){return t?ep[t]:"Not classified"}function Ma(t){return t.length>8?t.slice(0,8):t}function sp(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 yr(t,s,n){await Promise.all([pt(t,"discovery"),t.invalidateQueries({queryKey:Oc({client:H})})])}var Zn={exports:{}},vr;function np(){if(vr)return Zn.exports;vr=1;var t=typeof Reflect=="object"?Reflect:null,s=t&&typeof t.apply=="function"?t.apply:function(p,y,v){return Function.prototype.apply.call(p,y,v)},n;t&&typeof t.ownKeys=="function"?n=t.ownKeys:Object.getOwnPropertySymbols?n=function(p){return Object.getOwnPropertyNames(p).concat(Object.getOwnPropertySymbols(p))}:n=function(p){return Object.getOwnPropertyNames(p)};function a(j){console&&console.warn&&console.warn(j)}var i=Number.isNaN||function(p){return p!==p};function r(){r.init.call(this)}Zn.exports=r,Zn.exports.once=A,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var o=10;function l(j){if(typeof j!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof j)}Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(j){if(typeof j!="number"||j<0||i(j))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+j+".");o=j}}),r.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},r.prototype.setMaxListeners=function(p){if(typeof p!="number"||p<0||i(p))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+p+".");return this._maxListeners=p,this};function c(j){return j._maxListeners===void 0?r.defaultMaxListeners:j._maxListeners}r.prototype.getMaxListeners=function(){return c(this)},r.prototype.emit=function(p){for(var y=[],v=1;v<arguments.length;v++)y.push(arguments[v]);var D=p==="error",q=this._events;if(q!==void 0)D=D&&q.error===void 0;else if(!D)return!1;if(D){var S;if(y.length>0&&(S=y[0]),S instanceof Error)throw S;var k=new Error("Unhandled error."+(S?" ("+S.message+")":""));throw k.context=S,k}var F=q[p];if(F===void 0)return!1;if(typeof F=="function")s(F,this,y);else for(var C=F.length,I=f(F,C),v=0;v<C;++v)s(I[v],this,y);return!0};function u(j,p,y,v){var D,q,S;if(l(y),q=j._events,q===void 0?(q=j._events=Object.create(null),j._eventsCount=0):(q.newListener!==void 0&&(j.emit("newListener",p,y.listener?y.listener:y),q=j._events),S=q[p]),S===void 0)S=q[p]=y,++j._eventsCount;else if(typeof S=="function"?S=q[p]=v?[y,S]:[S,y]:v?S.unshift(y):S.push(y),D=c(j),D>0&&S.length>D&&!S.warned){S.warned=!0;var k=new Error("Possible EventEmitter memory leak detected. "+S.length+" "+String(p)+" listeners added. Use emitter.setMaxListeners() to increase limit");k.name="MaxListenersExceededWarning",k.emitter=j,k.type=p,k.count=S.length,a(k)}return j}r.prototype.addListener=function(p,y){return u(this,p,y,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(p,y){return u(this,p,y,!0)};function m(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function h(j,p,y){var v={fired:!1,wrapFn:void 0,target:j,type:p,listener:y},D=m.bind(v);return D.listener=y,v.wrapFn=D,D}r.prototype.once=function(p,y){return l(y),this.on(p,h(this,p,y)),this},r.prototype.prependOnceListener=function(p,y){return l(y),this.prependListener(p,h(this,p,y)),this},r.prototype.removeListener=function(p,y){var v,D,q,S,k;if(l(y),D=this._events,D===void 0)return this;if(v=D[p],v===void 0)return this;if(v===y||v.listener===y)--this._eventsCount===0?this._events=Object.create(null):(delete D[p],D.removeListener&&this.emit("removeListener",p,v.listener||y));else if(typeof v!="function"){for(q=-1,S=v.length-1;S>=0;S--)if(v[S]===y||v[S].listener===y){k=v[S].listener,q=S;break}if(q<0)return this;q===0?v.shift():w(v,q),v.length===1&&(D[p]=v[0]),D.removeListener!==void 0&&this.emit("removeListener",p,k||y)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(p){var y,v,D;if(v=this._events,v===void 0)return this;if(v.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):v[p]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete v[p]),this;if(arguments.length===0){var q=Object.keys(v),S;for(D=0;D<q.length;++D)S=q[D],S!=="removeListener"&&this.removeAllListeners(S);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(y=v[p],typeof y=="function")this.removeListener(p,y);else if(y!==void 0)for(D=y.length-1;D>=0;D--)this.removeListener(p,y[D]);return this};function x(j,p,y){var v=j._events;if(v===void 0)return[];var D=v[p];return D===void 0?[]:typeof D=="function"?y?[D.listener||D]:[D]:y?b(D):f(D,D.length)}r.prototype.listeners=function(p){return x(this,p,!0)},r.prototype.rawListeners=function(p){return x(this,p,!1)},r.listenerCount=function(j,p){return typeof j.listenerCount=="function"?j.listenerCount(p):N.call(j,p)},r.prototype.listenerCount=N;function N(j){var p=this._events;if(p!==void 0){var y=p[j];if(typeof y=="function")return 1;if(y!==void 0)return y.length}return 0}r.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]};function f(j,p){for(var y=new Array(p),v=0;v<p;++v)y[v]=j[v];return y}function w(j,p){for(;p+1<j.length;p++)j[p]=j[p+1];j.pop()}function b(j){for(var p=new Array(j.length),y=0;y<p.length;++y)p[y]=j[y].listener||j[y];return p}function A(j,p){return new Promise(function(y,v){function D(S){j.removeListener(p,q),v(S)}function q(){typeof j.removeListener=="function"&&j.removeListener("error",D),y([].slice.call(arguments))}P(j,p,q,{once:!0}),p!=="error"&&T(j,D,{once:!0})})}function T(j,p,y){typeof j.on=="function"&&P(j,"error",p,y)}function P(j,p,y,v){if(typeof j.on=="function")v.once?j.once(p,y):j.on(p,y);else if(typeof j.addEventListener=="function")j.addEventListener(p,function D(q){v.once&&j.removeEventListener(p,D),y(q)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof j)}return Zn.exports}var ap=np();function ip(){const t=arguments[0];for(let s=1,n=arguments.length;s<n;s++)if(arguments[s])for(const a in arguments[s])t[a]=arguments[s][a];return t}let ut=ip;typeof Object.assign=="function"&&(ut=Object.assign);function qt(t,s,n,a){const i=t._nodes.get(s);let r=null;return i&&(a==="mixed"?r=i.out&&i.out[n]||i.undirected&&i.undirected[n]:a==="directed"?r=i.out&&i.out[n]:r=i.undirected&&i.undirected[n]),r}function yt(t){return typeof t=="object"&&t!==null}function Uo(t){let s;for(s in t)return!1;return!0}function Mt(t,s,n){Object.defineProperty(t,s,{enumerable:!1,configurable:!1,writable:!0,value:n})}function Qt(t,s,n){const a={enumerable:!0,configurable:!0};typeof n=="function"?a.get=n:(a.value=n,a.writable=!1),Object.defineProperty(t,s,a)}function jr(t){return!(!yt(t)||t.attributes&&!Array.isArray(t.attributes))}function rp(){let t=Math.floor(Math.random()*256)&255;return()=>t++}function ds(){const t=arguments;let s=null,n=-1;return{[Symbol.iterator](){return this},next(){let a=null;do{if(s===null){if(n++,n>=t.length)return{done:!0};s=t[n][Symbol.iterator]()}if(a=s.next(),a.done){s=null;continue}break}while(!0);return a}}}function un(){return{[Symbol.iterator](){return this},next(){return{done:!0}}}}class ji extends Error{constructor(s){super(),this.name="GraphError",this.message=s}}class le extends ji{constructor(s){super(s),this.name="InvalidArgumentsGraphError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,le.prototype.constructor)}}class ee extends ji{constructor(s){super(s),this.name="NotFoundGraphError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,ee.prototype.constructor)}}class we extends ji{constructor(s){super(s),this.name="UsageGraphError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,we.prototype.constructor)}}function zo(t,s){this.key=t,this.attributes=s,this.clear()}zo.prototype.clear=function(){this.inDegree=0,this.outDegree=0,this.undirectedDegree=0,this.undirectedLoops=0,this.directedLoops=0,this.in={},this.out={},this.undirected={}};function Bo(t,s){this.key=t,this.attributes=s,this.clear()}Bo.prototype.clear=function(){this.inDegree=0,this.outDegree=0,this.directedLoops=0,this.in={},this.out={}};function Ko(t,s){this.key=t,this.attributes=s,this.clear()}Ko.prototype.clear=function(){this.undirectedDegree=0,this.undirectedLoops=0,this.undirected={}};function hn(t,s,n,a,i){this.key=s,this.attributes=i,this.undirected=t,this.source=n,this.target=a}hn.prototype.attach=function(){let t="out",s="in";this.undirected&&(t=s="undirected");const n=this.source.key,a=this.target.key;this.source[t][a]=this,!(this.undirected&&n===a)&&(this.target[s][n]=this)};hn.prototype.attachMulti=function(){let t="out",s="in";const n=this.source.key,a=this.target.key;this.undirected&&(t=s="undirected");const i=this.source[t],r=i[a];if(typeof r>"u"){i[a]=this,this.undirected&&n===a||(this.target[s][n]=this);return}r.previous=this,this.next=r,i[a]=this,this.target[s][n]=this};hn.prototype.detach=function(){const t=this.source.key,s=this.target.key;let n="out",a="in";this.undirected&&(n=a="undirected"),delete this.source[n][s],delete this.target[a][t]};hn.prototype.detachMulti=function(){const t=this.source.key,s=this.target.key;let n="out",a="in";this.undirected&&(n=a="undirected"),this.previous===void 0?this.next===void 0?(delete this.source[n][s],delete this.target[a][t]):(this.next.previous=void 0,this.source[n][s]=this.next,this.target[a][t]=this.next):(this.previous.next=this.next,this.next!==void 0&&(this.next.previous=this.previous))};const Vo=0,Qo=1,op=2,Ho=3;function hs(t,s,n,a,i,r,o){let l,c,u,m;if(a=""+a,n===Vo){if(l=t._nodes.get(a),!l)throw new ee(`Graph.${s}: could not find the "${a}" node in the graph.`);u=i,m=r}else if(n===Ho){if(i=""+i,c=t._edges.get(i),!c)throw new ee(`Graph.${s}: could not find the "${i}" edge in the graph.`);const h=c.source.key,x=c.target.key;if(a===h)l=c.target;else if(a===x)l=c.source;else throw new ee(`Graph.${s}: the "${a}" node is not attached to the "${i}" edge (${h}, ${x}).`);u=r,m=o}else{if(c=t._edges.get(a),!c)throw new ee(`Graph.${s}: could not find the "${a}" edge in the graph.`);n===Qo?l=c.source:l=c.target,u=i,m=r}return[l,u,m]}function lp(t,s,n){t.prototype[s]=function(a,i,r){const[o,l]=hs(this,s,n,a,i,r);return o.attributes[l]}}function cp(t,s,n){t.prototype[s]=function(a,i){const[r]=hs(this,s,n,a,i);return r.attributes}}function dp(t,s,n){t.prototype[s]=function(a,i,r){const[o,l]=hs(this,s,n,a,i,r);return o.attributes.hasOwnProperty(l)}}function up(t,s,n){t.prototype[s]=function(a,i,r,o){const[l,c,u]=hs(this,s,n,a,i,r,o);return l.attributes[c]=u,this.emit("nodeAttributesUpdated",{key:l.key,type:"set",attributes:l.attributes,name:c}),this}}function hp(t,s,n){t.prototype[s]=function(a,i,r,o){const[l,c,u]=hs(this,s,n,a,i,r,o);if(typeof u!="function")throw new le(`Graph.${s}: updater should be a function.`);const m=l.attributes,h=u(m[c]);return m[c]=h,this.emit("nodeAttributesUpdated",{key:l.key,type:"set",attributes:l.attributes,name:c}),this}}function mp(t,s,n){t.prototype[s]=function(a,i,r){const[o,l]=hs(this,s,n,a,i,r);return delete o.attributes[l],this.emit("nodeAttributesUpdated",{key:o.key,type:"remove",attributes:o.attributes,name:l}),this}}function pp(t,s,n){t.prototype[s]=function(a,i,r){const[o,l]=hs(this,s,n,a,i,r);if(!yt(l))throw new le(`Graph.${s}: provided attributes are not a plain object.`);return o.attributes=l,this.emit("nodeAttributesUpdated",{key:o.key,type:"replace",attributes:o.attributes}),this}}function xp(t,s,n){t.prototype[s]=function(a,i,r){const[o,l]=hs(this,s,n,a,i,r);if(!yt(l))throw new le(`Graph.${s}: provided attributes are not a plain object.`);return ut(o.attributes,l),this.emit("nodeAttributesUpdated",{key:o.key,type:"merge",attributes:o.attributes,data:l}),this}}function gp(t,s,n){t.prototype[s]=function(a,i,r){const[o,l]=hs(this,s,n,a,i,r);if(typeof l!="function")throw new le(`Graph.${s}: provided updater is not a function.`);return o.attributes=l(o.attributes),this.emit("nodeAttributesUpdated",{key:o.key,type:"update",attributes:o.attributes}),this}}const fp=[{name:t=>`get${t}Attribute`,attacher:lp},{name:t=>`get${t}Attributes`,attacher:cp},{name:t=>`has${t}Attribute`,attacher:dp},{name:t=>`set${t}Attribute`,attacher:up},{name:t=>`update${t}Attribute`,attacher:hp},{name:t=>`remove${t}Attribute`,attacher:mp},{name:t=>`replace${t}Attributes`,attacher:pp},{name:t=>`merge${t}Attributes`,attacher:xp},{name:t=>`update${t}Attributes`,attacher:gp}];function bp(t){fp.forEach(function({name:s,attacher:n}){n(t,s("Node"),Vo),n(t,s("Source"),Qo),n(t,s("Target"),op),n(t,s("Opposite"),Ho)})}function yp(t,s,n){t.prototype[s]=function(a,i){let r;if(this.type!=="mixed"&&n!=="mixed"&&n!==this.type)throw new we(`Graph.${s}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new we(`Graph.${s}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);const o=""+a,l=""+i;if(i=arguments[2],r=qt(this,o,l,n),!r)throw new ee(`Graph.${s}: could not find an edge for the given path ("${o}" - "${l}").`)}else{if(n!=="mixed")throw new we(`Graph.${s}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(a=""+a,r=this._edges.get(a),!r)throw new ee(`Graph.${s}: could not find the "${a}" edge in the graph.`)}return r.attributes[i]}}function vp(t,s,n){t.prototype[s]=function(a){let i;if(this.type!=="mixed"&&n!=="mixed"&&n!==this.type)throw new we(`Graph.${s}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>1){if(this.multi)throw new we(`Graph.${s}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);const r=""+a,o=""+arguments[1];if(i=qt(this,r,o,n),!i)throw new ee(`Graph.${s}: could not find an edge for the given path ("${r}" - "${o}").`)}else{if(n!=="mixed")throw new we(`Graph.${s}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(a=""+a,i=this._edges.get(a),!i)throw new ee(`Graph.${s}: could not find the "${a}" edge in the graph.`)}return i.attributes}}function jp(t,s,n){t.prototype[s]=function(a,i){let r;if(this.type!=="mixed"&&n!=="mixed"&&n!==this.type)throw new we(`Graph.${s}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new we(`Graph.${s}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);const o=""+a,l=""+i;if(i=arguments[2],r=qt(this,o,l,n),!r)throw new ee(`Graph.${s}: could not find an edge for the given path ("${o}" - "${l}").`)}else{if(n!=="mixed")throw new we(`Graph.${s}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(a=""+a,r=this._edges.get(a),!r)throw new ee(`Graph.${s}: could not find the "${a}" edge in the graph.`)}return r.attributes.hasOwnProperty(i)}}function Np(t,s,n){t.prototype[s]=function(a,i,r){let o;if(this.type!=="mixed"&&n!=="mixed"&&n!==this.type)throw new we(`Graph.${s}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>3){if(this.multi)throw new we(`Graph.${s}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);const l=""+a,c=""+i;if(i=arguments[2],r=arguments[3],o=qt(this,l,c,n),!o)throw new ee(`Graph.${s}: could not find an edge for the given path ("${l}" - "${c}").`)}else{if(n!=="mixed")throw new we(`Graph.${s}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(a=""+a,o=this._edges.get(a),!o)throw new ee(`Graph.${s}: could not find the "${a}" edge in the graph.`)}return o.attributes[i]=r,this.emit("edgeAttributesUpdated",{key:o.key,type:"set",attributes:o.attributes,name:i}),this}}function wp(t,s,n){t.prototype[s]=function(a,i,r){let o;if(this.type!=="mixed"&&n!=="mixed"&&n!==this.type)throw new we(`Graph.${s}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>3){if(this.multi)throw new we(`Graph.${s}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);const l=""+a,c=""+i;if(i=arguments[2],r=arguments[3],o=qt(this,l,c,n),!o)throw new ee(`Graph.${s}: could not find an edge for the given path ("${l}" - "${c}").`)}else{if(n!=="mixed")throw new we(`Graph.${s}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(a=""+a,o=this._edges.get(a),!o)throw new ee(`Graph.${s}: could not find the "${a}" edge in the graph.`)}if(typeof r!="function")throw new le(`Graph.${s}: updater should be a function.`);return o.attributes[i]=r(o.attributes[i]),this.emit("edgeAttributesUpdated",{key:o.key,type:"set",attributes:o.attributes,name:i}),this}}function Sp(t,s,n){t.prototype[s]=function(a,i){let r;if(this.type!=="mixed"&&n!=="mixed"&&n!==this.type)throw new we(`Graph.${s}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new we(`Graph.${s}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);const o=""+a,l=""+i;if(i=arguments[2],r=qt(this,o,l,n),!r)throw new ee(`Graph.${s}: could not find an edge for the given path ("${o}" - "${l}").`)}else{if(n!=="mixed")throw new we(`Graph.${s}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(a=""+a,r=this._edges.get(a),!r)throw new ee(`Graph.${s}: could not find the "${a}" edge in the graph.`)}return delete r.attributes[i],this.emit("edgeAttributesUpdated",{key:r.key,type:"remove",attributes:r.attributes,name:i}),this}}function kp(t,s,n){t.prototype[s]=function(a,i){let r;if(this.type!=="mixed"&&n!=="mixed"&&n!==this.type)throw new we(`Graph.${s}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new we(`Graph.${s}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);const o=""+a,l=""+i;if(i=arguments[2],r=qt(this,o,l,n),!r)throw new ee(`Graph.${s}: could not find an edge for the given path ("${o}" - "${l}").`)}else{if(n!=="mixed")throw new we(`Graph.${s}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(a=""+a,r=this._edges.get(a),!r)throw new ee(`Graph.${s}: could not find the "${a}" edge in the graph.`)}if(!yt(i))throw new le(`Graph.${s}: provided attributes are not a plain object.`);return r.attributes=i,this.emit("edgeAttributesUpdated",{key:r.key,type:"replace",attributes:r.attributes}),this}}function Cp(t,s,n){t.prototype[s]=function(a,i){let r;if(this.type!=="mixed"&&n!=="mixed"&&n!==this.type)throw new we(`Graph.${s}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new we(`Graph.${s}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);const o=""+a,l=""+i;if(i=arguments[2],r=qt(this,o,l,n),!r)throw new ee(`Graph.${s}: could not find an edge for the given path ("${o}" - "${l}").`)}else{if(n!=="mixed")throw new we(`Graph.${s}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(a=""+a,r=this._edges.get(a),!r)throw new ee(`Graph.${s}: could not find the "${a}" edge in the graph.`)}if(!yt(i))throw new le(`Graph.${s}: provided attributes are not a plain object.`);return ut(r.attributes,i),this.emit("edgeAttributesUpdated",{key:r.key,type:"merge",attributes:r.attributes,data:i}),this}}function Ap(t,s,n){t.prototype[s]=function(a,i){let r;if(this.type!=="mixed"&&n!=="mixed"&&n!==this.type)throw new we(`Graph.${s}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new we(`Graph.${s}: cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.`);const o=""+a,l=""+i;if(i=arguments[2],r=qt(this,o,l,n),!r)throw new ee(`Graph.${s}: could not find an edge for the given path ("${o}" - "${l}").`)}else{if(n!=="mixed")throw new we(`Graph.${s}: calling this method with only a key (vs. a source and target) does not make sense since an edge with this key could have the other type.`);if(a=""+a,r=this._edges.get(a),!r)throw new ee(`Graph.${s}: could not find the "${a}" edge in the graph.`)}if(typeof i!="function")throw new le(`Graph.${s}: provided updater is not a function.`);return r.attributes=i(r.attributes),this.emit("edgeAttributesUpdated",{key:r.key,type:"update",attributes:r.attributes}),this}}const $p=[{name:t=>`get${t}Attribute`,attacher:yp},{name:t=>`get${t}Attributes`,attacher:vp},{name:t=>`has${t}Attribute`,attacher:jp},{name:t=>`set${t}Attribute`,attacher:Np},{name:t=>`update${t}Attribute`,attacher:wp},{name:t=>`remove${t}Attribute`,attacher:Sp},{name:t=>`replace${t}Attributes`,attacher:kp},{name:t=>`merge${t}Attributes`,attacher:Cp},{name:t=>`update${t}Attributes`,attacher:Ap}];function Pp(t){$p.forEach(function({name:s,attacher:n}){n(t,s("Edge"),"mixed"),n(t,s("DirectedEdge"),"directed"),n(t,s("UndirectedEdge"),"undirected")})}const Rp=[{name:"edges",type:"mixed"},{name:"inEdges",type:"directed",direction:"in"},{name:"outEdges",type:"directed",direction:"out"},{name:"inboundEdges",type:"mixed",direction:"in"},{name:"outboundEdges",type:"mixed",direction:"out"},{name:"directedEdges",type:"directed"},{name:"undirectedEdges",type:"undirected"}];function Lp(t,s,n,a){let i=!1;for(const r in s){if(r===a)continue;const o=s[r];if(i=n(o.key,o.attributes,o.source.key,o.target.key,o.source.attributes,o.target.attributes,o.undirected),t&&i)return o.key}}function Ep(t,s,n,a){let i,r,o,l=!1;for(const c in s)if(c!==a){i=s[c];do{if(r=i.source,o=i.target,l=n(i.key,i.attributes,r.key,o.key,r.attributes,o.attributes,i.undirected),t&&l)return i.key;i=i.next}while(i!==void 0)}}function _a(t,s){const n=Object.keys(t),a=n.length;let i,r=0;return{[Symbol.iterator](){return this},next(){do if(i)i=i.next;else{if(r>=a)return{done:!0};const o=n[r++];if(o===s){i=void 0;continue}i=t[o]}while(!i);return{done:!1,value:{edge:i.key,attributes:i.attributes,source:i.source.key,target:i.target.key,sourceAttributes:i.source.attributes,targetAttributes:i.target.attributes,undirected:i.undirected}}}}}function Ip(t,s,n,a){const i=s[n];if(!i)return;const r=i.source,o=i.target;if(a(i.key,i.attributes,r.key,o.key,r.attributes,o.attributes,i.undirected)&&t)return i.key}function Dp(t,s,n,a){let i=s[n];if(!i)return;let r=!1;do{if(r=a(i.key,i.attributes,i.source.key,i.target.key,i.source.attributes,i.target.attributes,i.undirected),t&&r)return i.key;i=i.next}while(i!==void 0)}function Ga(t,s){let n=t[s];if(n.next!==void 0)return{[Symbol.iterator](){return this},next(){if(!n)return{done:!0};const i={edge:n.key,attributes:n.attributes,source:n.source.key,target:n.target.key,sourceAttributes:n.source.attributes,targetAttributes:n.target.attributes,undirected:n.undirected};return n=n.next,{done:!1,value:i}}};let a=!1;return{[Symbol.iterator](){return this},next(){return a===!0?{done:!0}:(a=!0,{done:!1,value:{edge:n.key,attributes:n.attributes,source:n.source.key,target:n.target.key,sourceAttributes:n.source.attributes,targetAttributes:n.target.attributes,undirected:n.undirected}})}}}function Tp(t,s){if(t.size===0)return[];if(s==="mixed"||s===t.type)return Array.from(t._edges.keys());const n=s==="undirected"?t.undirectedSize:t.directedSize,a=new Array(n),i=s==="undirected",r=t._edges.values();let o=0,l,c;for(;l=r.next(),l.done!==!0;)c=l.value,c.undirected===i&&(a[o++]=c.key);return a}function Wo(t,s,n,a){if(s.size===0)return;const i=n!=="mixed"&&n!==s.type,r=n==="undirected";let o,l,c=!1;const u=s._edges.values();for(;o=u.next(),o.done!==!0;){if(l=o.value,i&&l.undirected!==r)continue;const{key:m,attributes:h,source:x,target:N}=l;if(c=a(m,h,x.key,N.key,x.attributes,N.attributes,l.undirected),t&&c)return m}}function Mp(t,s){if(t.size===0)return un();const n=s!=="mixed"&&s!==t.type,a=s==="undirected",i=t._edges.values();return{[Symbol.iterator](){return this},next(){let r,o;for(;;){if(r=i.next(),r.done)return r;if(o=r.value,!(n&&o.undirected!==a))break}return{value:{edge:o.key,attributes:o.attributes,source:o.source.key,target:o.target.key,sourceAttributes:o.source.attributes,targetAttributes:o.target.attributes,undirected:o.undirected},done:!1}}}}function Ni(t,s,n,a,i,r){const o=s?Ep:Lp;let l;if(n!=="undirected"&&(a!=="out"&&(l=o(t,i.in,r),t&&l)||a!=="in"&&(l=o(t,i.out,r,a?void 0:i.key),t&&l))||n!=="directed"&&(l=o(t,i.undirected,r),t&&l))return l}function _p(t,s,n,a){const i=[];return Ni(!1,t,s,n,a,function(r){i.push(r)}),i}function Gp(t,s,n){let a=un();return t!=="undirected"&&(s!=="out"&&typeof n.in<"u"&&(a=ds(a,_a(n.in))),s!=="in"&&typeof n.out<"u"&&(a=ds(a,_a(n.out,s?void 0:n.key)))),t!=="directed"&&typeof n.undirected<"u"&&(a=ds(a,_a(n.undirected))),a}function wi(t,s,n,a,i,r,o){const l=n?Dp:Ip;let c;if(s!=="undirected"&&(typeof i.in<"u"&&a!=="out"&&(c=l(t,i.in,r,o),t&&c)||typeof i.out<"u"&&a!=="in"&&(a||i.key!==r)&&(c=l(t,i.out,r,o),t&&c))||s!=="directed"&&typeof i.undirected<"u"&&(c=l(t,i.undirected,r,o),t&&c))return c}function Op(t,s,n,a,i){const r=[];return wi(!1,t,s,n,a,i,function(o){r.push(o)}),r}function qp(t,s,n,a){let i=un();return t!=="undirected"&&(typeof n.in<"u"&&s!=="out"&&a in n.in&&(i=ds(i,Ga(n.in,a))),typeof n.out<"u"&&s!=="in"&&a in n.out&&(s||n.key!==a)&&(i=ds(i,Ga(n.out,a)))),t!=="directed"&&typeof n.undirected<"u"&&a in n.undirected&&(i=ds(i,Ga(n.undirected,a))),i}function Fp(t,s){const{name:n,type:a,direction:i}=s;t.prototype[n]=function(r,o){if(a!=="mixed"&&this.type!=="mixed"&&a!==this.type)return[];if(!arguments.length)return Tp(this,a);if(arguments.length===1){r=""+r;const l=this._nodes.get(r);if(typeof l>"u")throw new ee(`Graph.${n}: could not find the "${r}" node in the graph.`);return _p(this.multi,a==="mixed"?this.type:a,i,l)}if(arguments.length===2){r=""+r,o=""+o;const l=this._nodes.get(r);if(!l)throw new ee(`Graph.${n}: could not find the "${r}" source node in the graph.`);if(!this._nodes.has(o))throw new ee(`Graph.${n}: could not find the "${o}" target node in the graph.`);return Op(a,this.multi,i,l,o)}throw new le(`Graph.${n}: too many arguments (expecting 0, 1 or 2 and got ${arguments.length}).`)}}function Up(t,s){const{name:n,type:a,direction:i}=s,r="forEach"+n[0].toUpperCase()+n.slice(1,-1);t.prototype[r]=function(u,m,h){if(!(a!=="mixed"&&this.type!=="mixed"&&a!==this.type)){if(arguments.length===1)return h=u,Wo(!1,this,a,h);if(arguments.length===2){u=""+u,h=m;const x=this._nodes.get(u);if(typeof x>"u")throw new ee(`Graph.${r}: could not find the "${u}" node in the graph.`);return Ni(!1,this.multi,a==="mixed"?this.type:a,i,x,h)}if(arguments.length===3){u=""+u,m=""+m;const x=this._nodes.get(u);if(!x)throw new ee(`Graph.${r}: could not find the "${u}" source node in the graph.`);if(!this._nodes.has(m))throw new ee(`Graph.${r}: could not find the "${m}" target node in the graph.`);return wi(!1,a,this.multi,i,x,m,h)}throw new le(`Graph.${r}: too many arguments (expecting 1, 2 or 3 and got ${arguments.length}).`)}};const o="map"+n[0].toUpperCase()+n.slice(1);t.prototype[o]=function(){const u=Array.prototype.slice.call(arguments),m=u.pop();let h;if(u.length===0){let x=0;a!=="directed"&&(x+=this.undirectedSize),a!=="undirected"&&(x+=this.directedSize),h=new Array(x);let N=0;u.push((f,w,b,A,T,P,j)=>{h[N++]=m(f,w,b,A,T,P,j)})}else h=[],u.push((x,N,f,w,b,A,T)=>{h.push(m(x,N,f,w,b,A,T))});return this[r].apply(this,u),h};const l="filter"+n[0].toUpperCase()+n.slice(1);t.prototype[l]=function(){const u=Array.prototype.slice.call(arguments),m=u.pop(),h=[];return u.push((x,N,f,w,b,A,T)=>{m(x,N,f,w,b,A,T)&&h.push(x)}),this[r].apply(this,u),h};const c="reduce"+n[0].toUpperCase()+n.slice(1);t.prototype[c]=function(){let u=Array.prototype.slice.call(arguments);if(u.length<2||u.length>4)throw new le(`Graph.${c}: invalid number of arguments (expecting 2, 3 or 4 and got ${u.length}).`);if(typeof u[u.length-1]=="function"&&typeof u[u.length-2]!="function")throw new le(`Graph.${c}: missing initial value. You must provide it because the callback takes more than one argument and we cannot infer the initial value from the first iteration, as you could with a simple array.`);let m,h;u.length===2?(m=u[0],h=u[1],u=[]):u.length===3?(m=u[1],h=u[2],u=[u[0]]):u.length===4&&(m=u[2],h=u[3],u=[u[0],u[1]]);let x=h;return u.push((N,f,w,b,A,T,P)=>{x=m(x,N,f,w,b,A,T,P)}),this[r].apply(this,u),x}}function zp(t,s){const{name:n,type:a,direction:i}=s,r="find"+n[0].toUpperCase()+n.slice(1,-1);t.prototype[r]=function(c,u,m){if(a!=="mixed"&&this.type!=="mixed"&&a!==this.type)return!1;if(arguments.length===1)return m=c,Wo(!0,this,a,m);if(arguments.length===2){c=""+c,m=u;const h=this._nodes.get(c);if(typeof h>"u")throw new ee(`Graph.${r}: could not find the "${c}" node in the graph.`);return Ni(!0,this.multi,a==="mixed"?this.type:a,i,h,m)}if(arguments.length===3){c=""+c,u=""+u;const h=this._nodes.get(c);if(!h)throw new ee(`Graph.${r}: could not find the "${c}" source node in the graph.`);if(!this._nodes.has(u))throw new ee(`Graph.${r}: could not find the "${u}" target node in the graph.`);return wi(!0,a,this.multi,i,h,u,m)}throw new le(`Graph.${r}: too many arguments (expecting 1, 2 or 3 and got ${arguments.length}).`)};const o="some"+n[0].toUpperCase()+n.slice(1,-1);t.prototype[o]=function(){const c=Array.prototype.slice.call(arguments),u=c.pop();return c.push((h,x,N,f,w,b,A)=>u(h,x,N,f,w,b,A)),!!this[r].apply(this,c)};const l="every"+n[0].toUpperCase()+n.slice(1,-1);t.prototype[l]=function(){const c=Array.prototype.slice.call(arguments),u=c.pop();return c.push((h,x,N,f,w,b,A)=>!u(h,x,N,f,w,b,A)),!this[r].apply(this,c)}}function Bp(t,s){const{name:n,type:a,direction:i}=s,r=n.slice(0,-1)+"Entries";t.prototype[r]=function(o,l){if(a!=="mixed"&&this.type!=="mixed"&&a!==this.type)return un();if(!arguments.length)return Mp(this,a);if(arguments.length===1){o=""+o;const c=this._nodes.get(o);if(!c)throw new ee(`Graph.${r}: could not find the "${o}" node in the graph.`);return Gp(a,i,c)}if(arguments.length===2){o=""+o,l=""+l;const c=this._nodes.get(o);if(!c)throw new ee(`Graph.${r}: could not find the "${o}" source node in the graph.`);if(!this._nodes.has(l))throw new ee(`Graph.${r}: could not find the "${l}" target node in the graph.`);return qp(a,i,c,l)}throw new le(`Graph.${r}: too many arguments (expecting 0, 1 or 2 and got ${arguments.length}).`)}}function Kp(t){Rp.forEach(s=>{Fp(t,s),Up(t,s),zp(t,s),Bp(t,s)})}const Vp=[{name:"neighbors",type:"mixed"},{name:"inNeighbors",type:"directed",direction:"in"},{name:"outNeighbors",type:"directed",direction:"out"},{name:"inboundNeighbors",type:"mixed",direction:"in"},{name:"outboundNeighbors",type:"mixed",direction:"out"},{name:"directedNeighbors",type:"directed"},{name:"undirectedNeighbors",type:"undirected"}];function ya(){this.A=null,this.B=null}ya.prototype.wrap=function(t){this.A===null?this.A=t:this.B===null&&(this.B=t)};ya.prototype.has=function(t){return this.A!==null&&t in this.A||this.B!==null&&t in this.B};function wn(t,s,n,a,i){for(const r in a){const o=a[r],l=o.source,c=o.target,u=l===n?c:l;if(s&&s.has(u.key))continue;const m=i(u.key,u.attributes);if(t&&m)return u.key}}function Si(t,s,n,a,i){if(s!=="mixed"){if(s==="undirected")return wn(t,null,a,a.undirected,i);if(typeof n=="string")return wn(t,null,a,a[n],i)}const r=new ya;let o;if(s!=="undirected"){if(n!=="out"){if(o=wn(t,null,a,a.in,i),t&&o)return o;r.wrap(a.in)}if(n!=="in"){if(o=wn(t,r,a,a.out,i),t&&o)return o;r.wrap(a.out)}}if(s!=="directed"&&(o=wn(t,r,a,a.undirected,i),t&&o))return o}function Qp(t,s,n){if(t!=="mixed"){if(t==="undirected")return Object.keys(n.undirected);if(typeof s=="string")return Object.keys(n[s])}const a=[];return Si(!1,t,s,n,function(i){a.push(i)}),a}function Sn(t,s,n){const a=Object.keys(n),i=a.length;let r=0;return{[Symbol.iterator](){return this},next(){let o=null;do{if(r>=i)return t&&t.wrap(n),{done:!0};const l=n[a[r++]],c=l.source,u=l.target;if(o=c===s?u:c,t&&t.has(o.key)){o=null;continue}}while(o===null);return{done:!1,value:{neighbor:o.key,attributes:o.attributes}}}}}function Hp(t,s,n){if(t!=="mixed"){if(t==="undirected")return Sn(null,n,n.undirected);if(typeof s=="string")return Sn(null,n,n[s])}let a=un();const i=new ya;return t!=="undirected"&&(s!=="out"&&(a=ds(a,Sn(i,n,n.in))),s!=="in"&&(a=ds(a,Sn(i,n,n.out)))),t!=="directed"&&(a=ds(a,Sn(i,n,n.undirected))),a}function Wp(t,s){const{name:n,type:a,direction:i}=s;t.prototype[n]=function(r){if(a!=="mixed"&&this.type!=="mixed"&&a!==this.type)return[];r=""+r;const o=this._nodes.get(r);if(typeof o>"u")throw new ee(`Graph.${n}: could not find the "${r}" node in the graph.`);return Qp(a==="mixed"?this.type:a,i,o)}}function Yp(t,s){const{name:n,type:a,direction:i}=s,r="forEach"+n[0].toUpperCase()+n.slice(1,-1);t.prototype[r]=function(u,m){if(a!=="mixed"&&this.type!=="mixed"&&a!==this.type)return;u=""+u;const h=this._nodes.get(u);if(typeof h>"u")throw new ee(`Graph.${r}: could not find the "${u}" node in the graph.`);Si(!1,a==="mixed"?this.type:a,i,h,m)};const o="map"+n[0].toUpperCase()+n.slice(1);t.prototype[o]=function(u,m){const h=[];return this[r](u,(x,N)=>{h.push(m(x,N))}),h};const l="filter"+n[0].toUpperCase()+n.slice(1);t.prototype[l]=function(u,m){const h=[];return this[r](u,(x,N)=>{m(x,N)&&h.push(x)}),h};const c="reduce"+n[0].toUpperCase()+n.slice(1);t.prototype[c]=function(u,m,h){if(arguments.length<3)throw new le(`Graph.${c}: missing initial value. You must provide it because the callback takes more than one argument and we cannot infer the initial value from the first iteration, as you could with a simple array.`);let x=h;return this[r](u,(N,f)=>{x=m(x,N,f)}),x}}function Xp(t,s){const{name:n,type:a,direction:i}=s,r=n[0].toUpperCase()+n.slice(1,-1),o="find"+r;t.prototype[o]=function(u,m){if(a!=="mixed"&&this.type!=="mixed"&&a!==this.type)return;u=""+u;const h=this._nodes.get(u);if(typeof h>"u")throw new ee(`Graph.${o}: could not find the "${u}" node in the graph.`);return Si(!0,a==="mixed"?this.type:a,i,h,m)};const l="some"+r;t.prototype[l]=function(u,m){return!!this[o](u,m)};const c="every"+r;t.prototype[c]=function(u,m){return!this[o](u,(x,N)=>!m(x,N))}}function Jp(t,s){const{name:n,type:a,direction:i}=s,r=n.slice(0,-1)+"Entries";t.prototype[r]=function(o){if(a!=="mixed"&&this.type!=="mixed"&&a!==this.type)return un();o=""+o;const l=this._nodes.get(o);if(typeof l>"u")throw new ee(`Graph.${r}: could not find the "${o}" node in the graph.`);return Hp(a==="mixed"?this.type:a,i,l)}}function Zp(t){Vp.forEach(s=>{Wp(t,s),Yp(t,s),Xp(t,s),Jp(t,s)})}function ea(t,s,n,a,i){const r=a._nodes.values(),o=a.type;let l,c,u,m,h,x;for(;l=r.next(),l.done!==!0;){let N=!1;if(c=l.value,o!=="undirected"){m=c.out;for(u in m){h=m[u];do x=h.target,N=!0,i(c.key,x.key,c.attributes,x.attributes,h.key,h.attributes,h.undirected),h=h.next;while(h)}}if(o!=="directed"){m=c.undirected;for(u in m)if(!(s&&c.key>u)){h=m[u];do x=h.target,x.key!==u&&(x=h.source),N=!0,i(c.key,x.key,c.attributes,x.attributes,h.key,h.attributes,h.undirected),h=h.next;while(h)}}n&&!N&&i(c.key,null,c.attributes,null,null,null,null)}}function ex(t,s){const n={key:t};return Uo(s.attributes)||(n.attributes=ut({},s.attributes)),n}function tx(t,s,n){const a={key:s,source:n.source.key,target:n.target.key};return Uo(n.attributes)||(a.attributes=ut({},n.attributes)),t==="mixed"&&n.undirected&&(a.undirected=!0),a}function sx(t){if(!yt(t))throw new le('Graph.import: invalid serialized node. A serialized node should be a plain object with at least a "key" property.');if(!("key"in t))throw new le("Graph.import: serialized node is missing its key.");if("attributes"in t&&(!yt(t.attributes)||t.attributes===null))throw new le("Graph.import: invalid attributes. Attributes should be a plain object, null or omitted.")}function nx(t){if(!yt(t))throw new le('Graph.import: invalid serialized edge. A serialized edge should be a plain object with at least a "source" & "target" property.');if(!("source"in t))throw new le("Graph.import: serialized edge is missing its source.");if(!("target"in t))throw new le("Graph.import: serialized edge is missing its target.");if("attributes"in t&&(!yt(t.attributes)||t.attributes===null))throw new le("Graph.import: invalid attributes. Attributes should be a plain object, null or omitted.");if("undirected"in t&&typeof t.undirected!="boolean")throw new le("Graph.import: invalid undirectedness information. Undirected should be boolean or omitted.")}const ax=rp(),ix=new Set(["directed","undirected","mixed"]),Nr=new Set(["domain","_events","_eventsCount","_maxListeners"]),rx=[{name:t=>`${t}Edge`,generateKey:!0},{name:t=>`${t}DirectedEdge`,generateKey:!0,type:"directed"},{name:t=>`${t}UndirectedEdge`,generateKey:!0,type:"undirected"},{name:t=>`${t}EdgeWithKey`},{name:t=>`${t}DirectedEdgeWithKey`,type:"directed"},{name:t=>`${t}UndirectedEdgeWithKey`,type:"undirected"}],ox={allowSelfLoops:!0,multi:!1,type:"mixed"};function lx(t,s,n){if(n&&!yt(n))throw new le(`Graph.addNode: invalid attributes. Expecting an object but got "${n}"`);if(s=""+s,n=n||{},t._nodes.has(s))throw new we(`Graph.addNode: the "${s}" node already exist in the graph.`);const a=new t.NodeDataClass(s,n);return t._nodes.set(s,a),t.emit("nodeAdded",{key:s,attributes:n}),a}function wr(t,s,n){const a=new t.NodeDataClass(s,n);return t._nodes.set(s,a),t.emit("nodeAdded",{key:s,attributes:n}),a}function Yo(t,s,n,a,i,r,o,l){if(!a&&t.type==="undirected")throw new we(`Graph.${s}: you cannot add a directed edge to an undirected graph. Use the #.addEdge or #.addUndirectedEdge instead.`);if(a&&t.type==="directed")throw new we(`Graph.${s}: you cannot add an undirected edge to a directed graph. Use the #.addEdge or #.addDirectedEdge instead.`);if(l&&!yt(l))throw new le(`Graph.${s}: invalid attributes. Expecting an object but got "${l}"`);if(r=""+r,o=""+o,l=l||{},!t.allowSelfLoops&&r===o)throw new we(`Graph.${s}: source & target are the same ("${r}"), thus creating a loop explicitly forbidden by this graph 'allowSelfLoops' option set to false.`);const c=t._nodes.get(r),u=t._nodes.get(o);if(!c)throw new ee(`Graph.${s}: source node "${r}" not found.`);if(!u)throw new ee(`Graph.${s}: target node "${o}" not found.`);const m={key:null,undirected:a,source:r,target:o,attributes:l};if(n)i=t._edgeKeyGenerator();else if(i=""+i,t._edges.has(i))throw new we(`Graph.${s}: the "${i}" edge already exists in the graph.`);if(!t.multi&&(a?typeof c.undirected[o]<"u":typeof c.out[o]<"u"))throw new we(`Graph.${s}: an edge linking "${r}" to "${o}" already exists. If you really want to add multiple edges linking those nodes, you should create a multi graph by using the 'multi' option.`);const h=new hn(a,i,c,u,l);t._edges.set(i,h);const x=r===o;return a?(c.undirectedDegree++,u.undirectedDegree++,x&&(c.undirectedLoops++,t._undirectedSelfLoopCount++)):(c.outDegree++,u.inDegree++,x&&(c.directedLoops++,t._directedSelfLoopCount++)),t.multi?h.attachMulti():h.attach(),a?t._undirectedSize++:t._directedSize++,m.key=i,t.emit("edgeAdded",m),i}function cx(t,s,n,a,i,r,o,l,c){if(!a&&t.type==="undirected")throw new we(`Graph.${s}: you cannot merge/update a directed edge to an undirected graph. Use the #.mergeEdge/#.updateEdge or #.addUndirectedEdge instead.`);if(a&&t.type==="directed")throw new we(`Graph.${s}: you cannot merge/update an undirected edge to a directed graph. Use the #.mergeEdge/#.updateEdge or #.addDirectedEdge instead.`);if(l){if(c){if(typeof l!="function")throw new le(`Graph.${s}: invalid updater function. Expecting a function but got "${l}"`)}else if(!yt(l))throw new le(`Graph.${s}: invalid attributes. Expecting an object but got "${l}"`)}r=""+r,o=""+o;let u;if(c&&(u=l,l=void 0),!t.allowSelfLoops&&r===o)throw new we(`Graph.${s}: source & target are the same ("${r}"), thus creating a loop explicitly forbidden by this graph 'allowSelfLoops' option set to false.`);let m=t._nodes.get(r),h=t._nodes.get(o),x,N;if(!n&&(x=t._edges.get(i),x)){if((x.source.key!==r||x.target.key!==o)&&(!a||x.source.key!==o||x.target.key!==r))throw new we(`Graph.${s}: inconsistency detected when attempting to merge the "${i}" edge with "${r}" source & "${o}" target vs. ("${x.source.key}", "${x.target.key}").`);N=x}if(!N&&!t.multi&&m&&(N=a?m.undirected[o]:m.out[o]),N){const T=[N.key,!1,!1,!1];if(c?!u:!l)return T;if(c){const P=N.attributes;N.attributes=u(P),t.emit("edgeAttributesUpdated",{type:"replace",key:N.key,attributes:N.attributes})}else ut(N.attributes,l),t.emit("edgeAttributesUpdated",{type:"merge",key:N.key,attributes:N.attributes,data:l});return T}l=l||{},c&&u&&(l=u(l));const f={key:null,undirected:a,source:r,target:o,attributes:l};if(n)i=t._edgeKeyGenerator();else if(i=""+i,t._edges.has(i))throw new we(`Graph.${s}: the "${i}" edge already exists in the graph.`);let w=!1,b=!1;m||(m=wr(t,r,{}),w=!0,r===o&&(h=m,b=!0)),h||(h=wr(t,o,{}),b=!0),x=new hn(a,i,m,h,l),t._edges.set(i,x);const A=r===o;return a?(m.undirectedDegree++,h.undirectedDegree++,A&&(m.undirectedLoops++,t._undirectedSelfLoopCount++)):(m.outDegree++,h.inDegree++,A&&(m.directedLoops++,t._directedSelfLoopCount++)),t.multi?x.attachMulti():x.attach(),a?t._undirectedSize++:t._directedSize++,f.key=i,t.emit("edgeAdded",f),[i,!0,w,b]}function Bs(t,s){t._edges.delete(s.key);const{source:n,target:a,attributes:i}=s,r=s.undirected,o=n===a;r?(n.undirectedDegree--,a.undirectedDegree--,o&&(n.undirectedLoops--,t._undirectedSelfLoopCount--)):(n.outDegree--,a.inDegree--,o&&(n.directedLoops--,t._directedSelfLoopCount--)),t.multi?s.detachMulti():s.detach(),r?t._undirectedSize--:t._directedSize--,t.emit("edgeDropped",{key:s.key,attributes:i,source:n.key,target:a.key,undirected:r})}class Xe extends ap.EventEmitter{constructor(s){if(super(),s=ut({},ox,s),typeof s.multi!="boolean")throw new le(`Graph.constructor: invalid 'multi' option. Expecting a boolean but got "${s.multi}".`);if(!ix.has(s.type))throw new le(`Graph.constructor: invalid 'type' option. Should be one of "mixed", "directed" or "undirected" but got "${s.type}".`);if(typeof s.allowSelfLoops!="boolean")throw new le(`Graph.constructor: invalid 'allowSelfLoops' option. Expecting a boolean but got "${s.allowSelfLoops}".`);const n=s.type==="mixed"?zo:s.type==="directed"?Bo:Ko;Mt(this,"NodeDataClass",n);const a="geid_"+ax()+"_";let i=0;const r=()=>{let o;do o=a+i++;while(this._edges.has(o));return o};Mt(this,"_attributes",{}),Mt(this,"_nodes",new Map),Mt(this,"_edges",new Map),Mt(this,"_directedSize",0),Mt(this,"_undirectedSize",0),Mt(this,"_directedSelfLoopCount",0),Mt(this,"_undirectedSelfLoopCount",0),Mt(this,"_edgeKeyGenerator",r),Mt(this,"_options",s),Nr.forEach(o=>Mt(this,o,this[o])),Qt(this,"order",()=>this._nodes.size),Qt(this,"size",()=>this._edges.size),Qt(this,"directedSize",()=>this._directedSize),Qt(this,"undirectedSize",()=>this._undirectedSize),Qt(this,"selfLoopCount",()=>this._directedSelfLoopCount+this._undirectedSelfLoopCount),Qt(this,"directedSelfLoopCount",()=>this._directedSelfLoopCount),Qt(this,"undirectedSelfLoopCount",()=>this._undirectedSelfLoopCount),Qt(this,"multi",this._options.multi),Qt(this,"type",this._options.type),Qt(this,"allowSelfLoops",this._options.allowSelfLoops),Qt(this,"implementation",()=>"graphology")}_resetInstanceCounters(){this._directedSize=0,this._undirectedSize=0,this._directedSelfLoopCount=0,this._undirectedSelfLoopCount=0}hasNode(s){return this._nodes.has(""+s)}hasDirectedEdge(s,n){if(this.type==="undirected")return!1;if(arguments.length===1){const a=""+s,i=this._edges.get(a);return!!i&&!i.undirected}else if(arguments.length===2){s=""+s,n=""+n;const a=this._nodes.get(s);return a?a.out.hasOwnProperty(n):!1}throw new le(`Graph.hasDirectedEdge: invalid arity (${arguments.length}, instead of 1 or 2). You can either ask for an edge id or for the existence of an edge between a source & a target.`)}hasUndirectedEdge(s,n){if(this.type==="directed")return!1;if(arguments.length===1){const a=""+s,i=this._edges.get(a);return!!i&&i.undirected}else if(arguments.length===2){s=""+s,n=""+n;const a=this._nodes.get(s);return a?a.undirected.hasOwnProperty(n):!1}throw new le(`Graph.hasDirectedEdge: invalid arity (${arguments.length}, instead of 1 or 2). You can either ask for an edge id or for the existence of an edge between a source & a target.`)}hasEdge(s,n){if(arguments.length===1){const a=""+s;return this._edges.has(a)}else if(arguments.length===2){s=""+s,n=""+n;const a=this._nodes.get(s);return a?typeof a.out<"u"&&a.out.hasOwnProperty(n)||typeof a.undirected<"u"&&a.undirected.hasOwnProperty(n):!1}throw new le(`Graph.hasEdge: invalid arity (${arguments.length}, instead of 1 or 2). You can either ask for an edge id or for the existence of an edge between a source & a target.`)}directedEdge(s,n){if(this.type==="undirected")return;if(s=""+s,n=""+n,this.multi)throw new we("Graph.directedEdge: this method is irrelevant with multigraphs since there might be multiple edges between source & target. See #.directedEdges instead.");const a=this._nodes.get(s);if(!a)throw new ee(`Graph.directedEdge: could not find the "${s}" source node in the graph.`);if(!this._nodes.has(n))throw new ee(`Graph.directedEdge: could not find the "${n}" target node in the graph.`);const i=a.out&&a.out[n]||void 0;if(i)return i.key}undirectedEdge(s,n){if(this.type==="directed")return;if(s=""+s,n=""+n,this.multi)throw new we("Graph.undirectedEdge: this method is irrelevant with multigraphs since there might be multiple edges between source & target. See #.undirectedEdges instead.");const a=this._nodes.get(s);if(!a)throw new ee(`Graph.undirectedEdge: could not find the "${s}" source node in the graph.`);if(!this._nodes.has(n))throw new ee(`Graph.undirectedEdge: could not find the "${n}" target node in the graph.`);const i=a.undirected&&a.undirected[n]||void 0;if(i)return i.key}edge(s,n){if(this.multi)throw new we("Graph.edge: this method is irrelevant with multigraphs since there might be multiple edges between source & target. See #.edges instead.");s=""+s,n=""+n;const a=this._nodes.get(s);if(!a)throw new ee(`Graph.edge: could not find the "${s}" source node in the graph.`);if(!this._nodes.has(n))throw new ee(`Graph.edge: could not find the "${n}" target node in the graph.`);const i=a.out&&a.out[n]||a.undirected&&a.undirected[n]||void 0;if(i)return i.key}areDirectedNeighbors(s,n){s=""+s,n=""+n;const a=this._nodes.get(s);if(!a)throw new ee(`Graph.areDirectedNeighbors: could not find the "${s}" node in the graph.`);return this.type==="undirected"?!1:n in a.in||n in a.out}areOutNeighbors(s,n){s=""+s,n=""+n;const a=this._nodes.get(s);if(!a)throw new ee(`Graph.areOutNeighbors: could not find the "${s}" node in the graph.`);return this.type==="undirected"?!1:n in a.out}areInNeighbors(s,n){s=""+s,n=""+n;const a=this._nodes.get(s);if(!a)throw new ee(`Graph.areInNeighbors: could not find the "${s}" node in the graph.`);return this.type==="undirected"?!1:n in a.in}areUndirectedNeighbors(s,n){s=""+s,n=""+n;const a=this._nodes.get(s);if(!a)throw new ee(`Graph.areUndirectedNeighbors: could not find the "${s}" node in the graph.`);return this.type==="directed"?!1:n in a.undirected}areNeighbors(s,n){s=""+s,n=""+n;const a=this._nodes.get(s);if(!a)throw new ee(`Graph.areNeighbors: could not find the "${s}" node in the graph.`);return this.type!=="undirected"&&(n in a.in||n in a.out)||this.type!=="directed"&&n in a.undirected}areInboundNeighbors(s,n){s=""+s,n=""+n;const a=this._nodes.get(s);if(!a)throw new ee(`Graph.areInboundNeighbors: could not find the "${s}" node in the graph.`);return this.type!=="undirected"&&n in a.in||this.type!=="directed"&&n in a.undirected}areOutboundNeighbors(s,n){s=""+s,n=""+n;const a=this._nodes.get(s);if(!a)throw new ee(`Graph.areOutboundNeighbors: could not find the "${s}" node in the graph.`);return this.type!=="undirected"&&n in a.out||this.type!=="directed"&&n in a.undirected}inDegree(s){s=""+s;const n=this._nodes.get(s);if(!n)throw new ee(`Graph.inDegree: could not find the "${s}" node in the graph.`);return this.type==="undirected"?0:n.inDegree}outDegree(s){s=""+s;const n=this._nodes.get(s);if(!n)throw new ee(`Graph.outDegree: could not find the "${s}" node in the graph.`);return this.type==="undirected"?0:n.outDegree}directedDegree(s){s=""+s;const n=this._nodes.get(s);if(!n)throw new ee(`Graph.directedDegree: could not find the "${s}" node in the graph.`);return this.type==="undirected"?0:n.inDegree+n.outDegree}undirectedDegree(s){s=""+s;const n=this._nodes.get(s);if(!n)throw new ee(`Graph.undirectedDegree: could not find the "${s}" node in the graph.`);return this.type==="directed"?0:n.undirectedDegree}inboundDegree(s){s=""+s;const n=this._nodes.get(s);if(!n)throw new ee(`Graph.inboundDegree: could not find the "${s}" node in the graph.`);let a=0;return this.type!=="directed"&&(a+=n.undirectedDegree),this.type!=="undirected"&&(a+=n.inDegree),a}outboundDegree(s){s=""+s;const n=this._nodes.get(s);if(!n)throw new ee(`Graph.outboundDegree: could not find the "${s}" node in the graph.`);let a=0;return this.type!=="directed"&&(a+=n.undirectedDegree),this.type!=="undirected"&&(a+=n.outDegree),a}degree(s){s=""+s;const n=this._nodes.get(s);if(!n)throw new ee(`Graph.degree: could not find the "${s}" node in the graph.`);let a=0;return this.type!=="directed"&&(a+=n.undirectedDegree),this.type!=="undirected"&&(a+=n.inDegree+n.outDegree),a}inDegreeWithoutSelfLoops(s){s=""+s;const n=this._nodes.get(s);if(!n)throw new ee(`Graph.inDegreeWithoutSelfLoops: could not find the "${s}" node in the graph.`);return this.type==="undirected"?0:n.inDegree-n.directedLoops}outDegreeWithoutSelfLoops(s){s=""+s;const n=this._nodes.get(s);if(!n)throw new ee(`Graph.outDegreeWithoutSelfLoops: could not find the "${s}" node in the graph.`);return this.type==="undirected"?0:n.outDegree-n.directedLoops}directedDegreeWithoutSelfLoops(s){s=""+s;const n=this._nodes.get(s);if(!n)throw new ee(`Graph.directedDegreeWithoutSelfLoops: could not find the "${s}" node in the graph.`);return this.type==="undirected"?0:n.inDegree+n.outDegree-n.directedLoops*2}undirectedDegreeWithoutSelfLoops(s){s=""+s;const n=this._nodes.get(s);if(!n)throw new ee(`Graph.undirectedDegreeWithoutSelfLoops: could not find the "${s}" node in the graph.`);return this.type==="directed"?0:n.undirectedDegree-n.undirectedLoops*2}inboundDegreeWithoutSelfLoops(s){s=""+s;const n=this._nodes.get(s);if(!n)throw new ee(`Graph.inboundDegreeWithoutSelfLoops: could not find the "${s}" node in the graph.`);let a=0,i=0;return this.type!=="directed"&&(a+=n.undirectedDegree,i+=n.undirectedLoops*2),this.type!=="undirected"&&(a+=n.inDegree,i+=n.directedLoops),a-i}outboundDegreeWithoutSelfLoops(s){s=""+s;const n=this._nodes.get(s);if(!n)throw new ee(`Graph.outboundDegreeWithoutSelfLoops: could not find the "${s}" node in the graph.`);let a=0,i=0;return this.type!=="directed"&&(a+=n.undirectedDegree,i+=n.undirectedLoops*2),this.type!=="undirected"&&(a+=n.outDegree,i+=n.directedLoops),a-i}degreeWithoutSelfLoops(s){s=""+s;const n=this._nodes.get(s);if(!n)throw new ee(`Graph.degreeWithoutSelfLoops: could not find the "${s}" node in the graph.`);let a=0,i=0;return this.type!=="directed"&&(a+=n.undirectedDegree,i+=n.undirectedLoops*2),this.type!=="undirected"&&(a+=n.inDegree+n.outDegree,i+=n.directedLoops*2),a-i}source(s){s=""+s;const n=this._edges.get(s);if(!n)throw new ee(`Graph.source: could not find the "${s}" edge in the graph.`);return n.source.key}target(s){s=""+s;const n=this._edges.get(s);if(!n)throw new ee(`Graph.target: could not find the "${s}" edge in the graph.`);return n.target.key}extremities(s){s=""+s;const n=this._edges.get(s);if(!n)throw new ee(`Graph.extremities: could not find the "${s}" edge in the graph.`);return[n.source.key,n.target.key]}opposite(s,n){s=""+s,n=""+n;const a=this._edges.get(n);if(!a)throw new ee(`Graph.opposite: could not find the "${n}" edge in the graph.`);const i=a.source.key,r=a.target.key;if(s===i)return r;if(s===r)return i;throw new ee(`Graph.opposite: the "${s}" node is not attached to the "${n}" edge (${i}, ${r}).`)}hasExtremity(s,n){s=""+s,n=""+n;const a=this._edges.get(s);if(!a)throw new ee(`Graph.hasExtremity: could not find the "${s}" edge in the graph.`);return a.source.key===n||a.target.key===n}isUndirected(s){s=""+s;const n=this._edges.get(s);if(!n)throw new ee(`Graph.isUndirected: could not find the "${s}" edge in the graph.`);return n.undirected}isDirected(s){s=""+s;const n=this._edges.get(s);if(!n)throw new ee(`Graph.isDirected: could not find the "${s}" edge in the graph.`);return!n.undirected}isSelfLoop(s){s=""+s;const n=this._edges.get(s);if(!n)throw new ee(`Graph.isSelfLoop: could not find the "${s}" edge in the graph.`);return n.source===n.target}addNode(s,n){return lx(this,s,n).key}mergeNode(s,n){if(n&&!yt(n))throw new le(`Graph.mergeNode: invalid attributes. Expecting an object but got "${n}"`);s=""+s,n=n||{};let a=this._nodes.get(s);return a?(n&&(ut(a.attributes,n),this.emit("nodeAttributesUpdated",{type:"merge",key:s,attributes:a.attributes,data:n})),[s,!1]):(a=new this.NodeDataClass(s,n),this._nodes.set(s,a),this.emit("nodeAdded",{key:s,attributes:n}),[s,!0])}updateNode(s,n){if(n&&typeof n!="function")throw new le(`Graph.updateNode: invalid updater function. Expecting a function but got "${n}"`);s=""+s;let a=this._nodes.get(s);if(a){if(n){const r=a.attributes;a.attributes=n(r),this.emit("nodeAttributesUpdated",{type:"replace",key:s,attributes:a.attributes})}return[s,!1]}const i=n?n({}):{};return a=new this.NodeDataClass(s,i),this._nodes.set(s,a),this.emit("nodeAdded",{key:s,attributes:i}),[s,!0]}dropNode(s){s=""+s;const n=this._nodes.get(s);if(!n)throw new ee(`Graph.dropNode: could not find the "${s}" node in the graph.`);let a;if(this.type!=="undirected"){for(const i in n.out){a=n.out[i];do Bs(this,a),a=a.next;while(a)}for(const i in n.in){a=n.in[i];do Bs(this,a),a=a.next;while(a)}}if(this.type!=="directed")for(const i in n.undirected){a=n.undirected[i];do Bs(this,a),a=a.next;while(a)}this._nodes.delete(s),this.emit("nodeDropped",{key:s,attributes:n.attributes})}dropEdge(s){let n;if(arguments.length>1){const a=""+arguments[0],i=""+arguments[1];if(n=qt(this,a,i,this.type),!n)throw new ee(`Graph.dropEdge: could not find the "${a}" -> "${i}" edge in the graph.`)}else if(s=""+s,n=this._edges.get(s),!n)throw new ee(`Graph.dropEdge: could not find the "${s}" edge in the graph.`);return Bs(this,n),this}dropDirectedEdge(s,n){if(arguments.length<2)throw new we("Graph.dropDirectedEdge: it does not make sense to try and drop a directed edge by key. What if the edge with this key is undirected? Use #.dropEdge for this purpose instead.");if(this.multi)throw new we("Graph.dropDirectedEdge: cannot use a {source,target} combo when dropping an edge in a MultiGraph since we cannot infer the one you want to delete as there could be multiple ones.");s=""+s,n=""+n;const a=qt(this,s,n,"directed");if(!a)throw new ee(`Graph.dropDirectedEdge: could not find a "${s}" -> "${n}" edge in the graph.`);return Bs(this,a),this}dropUndirectedEdge(s,n){if(arguments.length<2)throw new we("Graph.dropUndirectedEdge: it does not make sense to drop a directed edge by key. What if the edge with this key is undirected? Use #.dropEdge for this purpose instead.");if(this.multi)throw new we("Graph.dropUndirectedEdge: cannot use a {source,target} combo when dropping an edge in a MultiGraph since we cannot infer the one you want to delete as there could be multiple ones.");const a=qt(this,s,n,"undirected");if(!a)throw new ee(`Graph.dropUndirectedEdge: could not find a "${s}" -> "${n}" edge in the graph.`);return Bs(this,a),this}clear(){this._edges.clear(),this._nodes.clear(),this._resetInstanceCounters(),this.emit("cleared")}clearEdges(){const s=this._nodes.values();let n;for(;n=s.next(),n.done!==!0;)n.value.clear();this._edges.clear(),this._resetInstanceCounters(),this.emit("edgesCleared")}getAttribute(s){return this._attributes[s]}getAttributes(){return this._attributes}hasAttribute(s){return this._attributes.hasOwnProperty(s)}setAttribute(s,n){return this._attributes[s]=n,this.emit("attributesUpdated",{type:"set",attributes:this._attributes,name:s}),this}updateAttribute(s,n){if(typeof n!="function")throw new le("Graph.updateAttribute: updater should be a function.");const a=this._attributes[s];return this._attributes[s]=n(a),this.emit("attributesUpdated",{type:"set",attributes:this._attributes,name:s}),this}removeAttribute(s){return delete this._attributes[s],this.emit("attributesUpdated",{type:"remove",attributes:this._attributes,name:s}),this}replaceAttributes(s){if(!yt(s))throw new le("Graph.replaceAttributes: provided attributes are not a plain object.");return this._attributes=s,this.emit("attributesUpdated",{type:"replace",attributes:this._attributes}),this}mergeAttributes(s){if(!yt(s))throw new le("Graph.mergeAttributes: provided attributes are not a plain object.");return ut(this._attributes,s),this.emit("attributesUpdated",{type:"merge",attributes:this._attributes,data:s}),this}updateAttributes(s){if(typeof s!="function")throw new le("Graph.updateAttributes: provided updater is not a function.");return this._attributes=s(this._attributes),this.emit("attributesUpdated",{type:"update",attributes:this._attributes}),this}updateEachNodeAttributes(s,n){if(typeof s!="function")throw new le("Graph.updateEachNodeAttributes: expecting an updater function.");if(n&&!jr(n))throw new le("Graph.updateEachNodeAttributes: invalid hints. Expecting an object having the following shape: {attributes?: [string]}");const a=this._nodes.values();let i,r;for(;i=a.next(),i.done!==!0;)r=i.value,r.attributes=s(r.key,r.attributes);this.emit("eachNodeAttributesUpdated",{hints:n||null})}updateEachEdgeAttributes(s,n){if(typeof s!="function")throw new le("Graph.updateEachEdgeAttributes: expecting an updater function.");if(n&&!jr(n))throw new le("Graph.updateEachEdgeAttributes: invalid hints. Expecting an object having the following shape: {attributes?: [string]}");const a=this._edges.values();let i,r,o,l;for(;i=a.next(),i.done!==!0;)r=i.value,o=r.source,l=r.target,r.attributes=s(r.key,r.attributes,o.key,l.key,o.attributes,l.attributes,r.undirected);this.emit("eachEdgeAttributesUpdated",{hints:n||null})}forEachAdjacencyEntry(s){if(typeof s!="function")throw new le("Graph.forEachAdjacencyEntry: expecting a callback.");ea(!1,!1,!1,this,s)}forEachAdjacencyEntryWithOrphans(s){if(typeof s!="function")throw new le("Graph.forEachAdjacencyEntryWithOrphans: expecting a callback.");ea(!1,!1,!0,this,s)}forEachAssymetricAdjacencyEntry(s){if(typeof s!="function")throw new le("Graph.forEachAssymetricAdjacencyEntry: expecting a callback.");ea(!1,!0,!1,this,s)}forEachAssymetricAdjacencyEntryWithOrphans(s){if(typeof s!="function")throw new le("Graph.forEachAssymetricAdjacencyEntryWithOrphans: expecting a callback.");ea(!1,!0,!0,this,s)}nodes(){return Array.from(this._nodes.keys())}forEachNode(s){if(typeof s!="function")throw new le("Graph.forEachNode: expecting a callback.");const n=this._nodes.values();let a,i;for(;a=n.next(),a.done!==!0;)i=a.value,s(i.key,i.attributes)}findNode(s){if(typeof s!="function")throw new le("Graph.findNode: expecting a callback.");const n=this._nodes.values();let a,i;for(;a=n.next(),a.done!==!0;)if(i=a.value,s(i.key,i.attributes))return i.key}mapNodes(s){if(typeof s!="function")throw new le("Graph.mapNode: expecting a callback.");const n=this._nodes.values();let a,i;const r=new Array(this.order);let o=0;for(;a=n.next(),a.done!==!0;)i=a.value,r[o++]=s(i.key,i.attributes);return r}someNode(s){if(typeof s!="function")throw new le("Graph.someNode: expecting a callback.");const n=this._nodes.values();let a,i;for(;a=n.next(),a.done!==!0;)if(i=a.value,s(i.key,i.attributes))return!0;return!1}everyNode(s){if(typeof s!="function")throw new le("Graph.everyNode: expecting a callback.");const n=this._nodes.values();let a,i;for(;a=n.next(),a.done!==!0;)if(i=a.value,!s(i.key,i.attributes))return!1;return!0}filterNodes(s){if(typeof s!="function")throw new le("Graph.filterNodes: expecting a callback.");const n=this._nodes.values();let a,i;const r=[];for(;a=n.next(),a.done!==!0;)i=a.value,s(i.key,i.attributes)&&r.push(i.key);return r}reduceNodes(s,n){if(typeof s!="function")throw new le("Graph.reduceNodes: expecting a callback.");if(arguments.length<2)throw new le("Graph.reduceNodes: missing initial value. You must provide it because the callback takes more than one argument and we cannot infer the initial value from the first iteration, as you could with a simple array.");let a=n;const i=this._nodes.values();let r,o;for(;r=i.next(),r.done!==!0;)o=r.value,a=s(a,o.key,o.attributes);return a}nodeEntries(){const s=this._nodes.values();return{[Symbol.iterator](){return this},next(){const n=s.next();if(n.done)return n;const a=n.value;return{value:{node:a.key,attributes:a.attributes},done:!1}}}}export(){const s=new Array(this._nodes.size);let n=0;this._nodes.forEach((i,r)=>{s[n++]=ex(r,i)});const a=new Array(this._edges.size);return n=0,this._edges.forEach((i,r)=>{a[n++]=tx(this.type,r,i)}),{options:{type:this.type,multi:this.multi,allowSelfLoops:this.allowSelfLoops},attributes:this.getAttributes(),nodes:s,edges:a}}import(s,n=!1){if(s instanceof Xe)return s.forEachNode((c,u)=>{n?this.mergeNode(c,u):this.addNode(c,u)}),s.forEachEdge((c,u,m,h,x,N,f)=>{n?f?this.mergeUndirectedEdgeWithKey(c,m,h,u):this.mergeDirectedEdgeWithKey(c,m,h,u):f?this.addUndirectedEdgeWithKey(c,m,h,u):this.addDirectedEdgeWithKey(c,m,h,u)}),this;if(!yt(s))throw new le("Graph.import: invalid argument. Expecting a serialized graph or, alternatively, a Graph instance.");if(s.attributes){if(!yt(s.attributes))throw new le("Graph.import: invalid attributes. Expecting a plain object.");n?this.mergeAttributes(s.attributes):this.replaceAttributes(s.attributes)}let a,i,r,o,l;if(s.nodes){if(r=s.nodes,!Array.isArray(r))throw new le("Graph.import: invalid nodes. Expecting an array.");for(a=0,i=r.length;a<i;a++){o=r[a],sx(o);const{key:c,attributes:u}=o;n?this.mergeNode(c,u):this.addNode(c,u)}}if(s.edges){let c=!1;if(this.type==="undirected"&&(c=!0),r=s.edges,!Array.isArray(r))throw new le("Graph.import: invalid edges. Expecting an array.");for(a=0,i=r.length;a<i;a++){l=r[a],nx(l);const{source:u,target:m,attributes:h,undirected:x=c}=l;let N;"key"in l?(N=n?x?this.mergeUndirectedEdgeWithKey:this.mergeDirectedEdgeWithKey:x?this.addUndirectedEdgeWithKey:this.addDirectedEdgeWithKey,N.call(this,l.key,u,m,h)):(N=n?x?this.mergeUndirectedEdge:this.mergeDirectedEdge:x?this.addUndirectedEdge:this.addDirectedEdge,N.call(this,u,m,h))}}return this}nullCopy(s){const n=new Xe(ut({},this._options,s));return n.replaceAttributes(ut({},this.getAttributes())),n}emptyCopy(s){const n=this.nullCopy(s);return this._nodes.forEach((a,i)=>{const r=ut({},a.attributes);a=new n.NodeDataClass(i,r),n._nodes.set(i,a)}),n}copy(s){if(s=s||{},typeof s.type=="string"&&s.type!==this.type&&s.type!=="mixed")throw new we(`Graph.copy: cannot create an incompatible copy from "${this.type}" type to "${s.type}" because this would mean losing information about the current graph.`);if(typeof s.multi=="boolean"&&s.multi!==this.multi&&s.multi!==!0)throw new we("Graph.copy: cannot create an incompatible copy by downgrading a multi graph to a simple one because this would mean losing information about the current graph.");if(typeof s.allowSelfLoops=="boolean"&&s.allowSelfLoops!==this.allowSelfLoops&&s.allowSelfLoops!==!0)throw new we("Graph.copy: cannot create an incompatible copy from a graph allowing self loops to one that does not because this would mean losing information about the current graph.");const n=this.emptyCopy(s),a=this._edges.values();let i,r;for(;i=a.next(),i.done!==!0;)r=i.value,Yo(n,"copy",!1,r.undirected,r.key,r.source.key,r.target.key,ut({},r.attributes));return n}toJSON(){return this.export()}toString(){return"[object Graph]"}inspect(){const s={};this._nodes.forEach((r,o)=>{s[o]=r.attributes});const n={},a={};this._edges.forEach((r,o)=>{const l=r.undirected?"--":"->";let c="",u=r.source.key,m=r.target.key,h;r.undirected&&u>m&&(h=u,u=m,m=h);const x=`(${u})${l}(${m})`;o.startsWith("geid_")?this.multi&&(typeof a[x]>"u"?a[x]=0:a[x]++,c+=`${a[x]}. `):c+=`[${o}]: `,c+=x,n[c]=r.attributes});const i={};for(const r in this)this.hasOwnProperty(r)&&!Nr.has(r)&&typeof this[r]!="function"&&typeof r!="symbol"&&(i[r]=this[r]);return i.attributes=this._attributes,i.nodes=s,i.edges=n,Mt(i,"constructor",this.constructor),i}}typeof Symbol<"u"&&(Xe.prototype[Symbol.for("nodejs.util.inspect.custom")]=Xe.prototype.inspect);rx.forEach(t=>{["add","merge","update"].forEach(s=>{const n=t.name(s),a=s==="add"?Yo:cx;t.generateKey?Xe.prototype[n]=function(i,r,o){return a(this,n,!0,(t.type||this.type)==="undirected",null,i,r,o,s==="update")}:Xe.prototype[n]=function(i,r,o,l){return a(this,n,!1,(t.type||this.type)==="undirected",i,r,o,l,s==="update")}})});bp(Xe);Pp(Xe);Kp(Xe);Zp(Xe);class Xo extends Xe{constructor(s){const n=ut({type:"directed"},s);if("multi"in n&&n.multi!==!1)throw new le("DirectedGraph.from: inconsistent indication that the graph should be multi in given options!");if(n.type!=="directed")throw new le('DirectedGraph.from: inconsistent "'+n.type+'" type in given options!');super(n)}}class Jo extends Xe{constructor(s){const n=ut({type:"undirected"},s);if("multi"in n&&n.multi!==!1)throw new le("UndirectedGraph.from: inconsistent indication that the graph should be multi in given options!");if(n.type!=="undirected")throw new le('UndirectedGraph.from: inconsistent "'+n.type+'" type in given options!');super(n)}}class Zo extends Xe{constructor(s){const n=ut({multi:!0},s);if("multi"in n&&n.multi!==!0)throw new le("MultiGraph.from: inconsistent indication that the graph should be simple in given options!");super(n)}}class ki extends Xe{constructor(s){const n=ut({type:"directed",multi:!0},s);if("multi"in n&&n.multi!==!0)throw new le("MultiDirectedGraph.from: inconsistent indication that the graph should be simple in given options!");if(n.type!=="directed")throw new le('MultiDirectedGraph.from: inconsistent "'+n.type+'" type in given options!');super(n)}}class el extends Xe{constructor(s){const n=ut({type:"undirected",multi:!0},s);if("multi"in n&&n.multi!==!0)throw new le("MultiUndirectedGraph.from: inconsistent indication that the graph should be simple in given options!");if(n.type!=="undirected")throw new le('MultiUndirectedGraph.from: inconsistent "'+n.type+'" type in given options!');super(n)}}function mn(t){t.from=function(s,n){const a=ut({},s.options,n),i=new t(a);return i.import(s),i}}mn(Xe);mn(Xo);mn(Jo);mn(Zo);mn(ki);mn(el);Xe.Graph=Xe;Xe.DirectedGraph=Xo;Xe.UndirectedGraph=Jo;Xe.MultiGraph=Zo;Xe.MultiDirectedGraph=ki;Xe.MultiUndirectedGraph=el;Xe.InvalidArgumentsGraphError=le;Xe.NotFoundGraphError=ee;Xe.UsageGraphError=we;const Ws={eligible:{property:"--chart-site-health-eligible",fallback:"#56b4e9"},hidden:{property:"--chart-site-health-hidden",fallback:"#e69f00"},failed:{property:"--chart-site-health-failed",fallback:"#d55e00"},unchecked:{property:"--chart-site-health-unchecked",fallback:"#a1a1aa"}},dx={property:"--chart-neutral-text-dim",fallback:"#71717a"},ux={eligible:Ws.eligible,hidden:Ws.hidden,failed:Ws.failed,unchecked:Ws.unchecked,dimmedNode:{property:"--chart-neutral-text-dim",fallback:"#71717a"},edge:dx,edgeDimmed:{property:"--chart-neutral-text-faint",fallback:"#52525b"},edgeActive:{property:"--chart-neutral-text",fallback:"#a1a1aa"},label:{property:"--chart-tooltip-label",fallback:"#e4e4e7"},background:{property:"--chart-tooltip-bg",fallback:"#18181b"}},hx=/^#(?:[\da-f]{3}|[\da-f]{4}|[\da-f]{6}|[\da-f]{8})$/i,mx=/^rgba?\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}(?:\s*,\s*(?:0|1|0?\.\d+))?\s*\)$/;function Sr(t){return hx.test(t)||mx.test(t)}const kr=50,px=8,Pn=.75;function dn(t,s){return t<s?-1:t>s?1:0}function xx(t){return Math.max(0,Math.min(1,t.linkScoreNormalized??0))}function fa(t){return t.healthState?t.healthState:qc(t)}function ua(t){switch(t){case"eligible":return"Technically eligible";case"hidden":return"Hidden or points elsewhere";case"failed":return"Fetch failed";case"unchecked":return"Not checked"}}function ri(t){switch(t){case"eligible":return"●";case"hidden":return"◆";case"failed":return"×";case"unchecked":return"○"}}function gx(t){const s=3+Math.sqrt(xx(t))*7;return t.depth===0||t.path.trim()==="/"?Math.max(9,s):s}function fx(t,s){switch(t){case"eligible":return s.eligible;case"hidden":return s.hidden;case"failed":return s.failed;case"unchecked":return s.unchecked}}function bx(t){return .35+Math.min(1.65,Math.log2(Math.max(1,t)+1)*.28)}function tl(t){return Number.isFinite(t.x)&&Number.isFinite(t.y)}function yx(t,s,n){const a=new ki({allowSelfLoops:!0}),i=new Map;for(const o of t)i.has(o.nodeKey)||i.set(o.nodeKey,o);for(const o of[...i.values()].sort((l,c)=>dn(l.nodeKey,c.nodeKey))){if(!tl(o))continue;const l=fa(o),c=fx(l,n),u=ri(l);a.addNode(o.nodeKey,{x:o.x,y:o.y,size:gx(o),color:c,baseColor:c,label:`${u} ${o.path||"/"}`,nodeKey:o.nodeKey,url:o.url,path:o.path,depth:o.depth,status:l,glyph:u,forceLabel:o.depth===0||o.path.trim()==="/",zIndex:o.depth===0?1:0})}const r=new Set;for(const o of[...s].sort((l,c)=>dn(l.edgeKey,c.edgeKey)))r.has(o.edgeKey)||!o.targetNodeKey||!a.hasNode(o.sourceNodeKey)||!a.hasNode(o.targetNodeKey)||(r.add(o.edgeKey),a.addDirectedEdgeWithKey(o.edgeKey,o.sourceNodeKey,o.targetNodeKey,{size:bx(o.occurrences),color:n.edge,baseColor:n.edge,followable:o.followable,occurrences:o.occurrences,type:"line",zIndex:0}));return{graph:a,layoutAvailable:t.length===0||a.order>0,omittedNodes:Math.max(0,t.length-a.order),omittedEdges:Math.max(0,s.length-a.size)}}function vx(t,s,n=kr){const a=s.trim().toLocaleLowerCase(),i=Math.max(0,Math.min(kr,Math.floor(n)));return[...t].sort((r,o)=>dn(r.path||r.url,o.path||o.url)||dn(r.nodeKey,o.nodeKey)).filter(r=>tl(r)?a?`${r.path}
|
|
8
8
|
${r.url}
|
|
9
|
-
${r.nodeKey}`.toLocaleLowerCase().includes(a):!0:!1).slice(0,i)}function jx(t,s,n,a){const r=!!(s&&t.hasNode(s))?s:null,o=n>Pn,l=new Set(r&&o?t.neighbors(r).filter(c=>c!==r).sort((c,u)=>{const m=t.getNodeAttributes(c),h=t.getNodeAttributes(u);return h.size-m.size||(m.depth??Number.MAX_SAFE_INTEGER)-(h.depth??Number.MAX_SAFE_INTEGER)||dn(m.path,h.path)||dn(c,u)}).slice(0,px):[]);return{nodeReducer:(c,u)=>r?c===r?{...u,size:u.size*1.35,forceLabel:!0,zIndex:3}:t.areNeighbors(c,r)?o?l.has(c)?{...u,forceLabel:!1}:{...u,forceLabel:!1,label:""}:u:{...u,color:a.dimmedNode,forceLabel:!1,label:"",zIndex:0}:o?u.depth===0||u.depth===1?{...u,forceLabel:!0}:{...u,forceLabel:!1,label:""}:u,edgeReducer:(c,u)=>{const[m,h]=t.extremities(c);return r&&(m===r||h===r)?{...u,color:a.edgeActive,size:Math.max(1.4,u.size),zIndex:2}:o?{...u,hidden:!0}:r?{...u,color:a.edgeDimmed,size:Math.min(.45,u.size),zIndex:0}:u}}}function Nx(t){return t==="layout-failed"?{heading:"Graph layout failed",detail:"This scan completed, but its graph layout could not be published. The page inventory remains available."}:{heading:"Graph layout unavailable",detail:"This scan does not have a published graph layout yet."}}class wx extends d.Component{state={failed:!1};static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(s){console.error("[SiteGraphSigma] WebGL renderer failed",s)}componentDidUpdate(s){this.state.failed&&s.resetToken!==this.props.resetToken&&this.setState({failed:!1})}render(){return this.state.failed?this.props.fallback:this.props.children}}const ta=220;function sa(t,s,n=`${s}s`){return`${t.toLocaleString()} ${t===1?s:n}`}function Sx(t,s,n){const i=window.getComputedStyle(t).getPropertyValue(s).trim();if(i&&!i.includes("var(")&&Sr(i))return i;const r=document.createElement("span");r.style.position="absolute",r.style.visibility="hidden",r.style.color=`var(${s})`,t.appendChild(r);const o=window.getComputedStyle(r).color.trim();return r.remove(),o&&!o.includes("var(")&&Sr(o)?o:n}function kx(t){const s=n=>{const a=ux[n];return Sx(t,a.property,a.fallback)};return{eligible:s("eligible"),hidden:s("hidden"),failed:s("failed"),unchecked:s("unchecked"),dimmedNode:s("dimmedNode"),edge:s("edge"),edgeDimmed:s("edgeDimmed"),edgeActive:s("edgeActive"),label:s("label"),background:s("background")}}function Cx(t,s,n,a,i,r){const o=Math.min(r,a/2,i/2);t.beginPath(),t.moveTo(s+o,n),t.lineTo(s+a-o,n),t.arcTo(s+a,n,s+a,n+o,o),t.lineTo(s+a,n+i-o),t.arcTo(s+a,n+i,s+a-o,n+i,o),t.lineTo(s+o,n+i),t.arcTo(s,n+i,s,n+i-o,o),t.lineTo(s,n+o),t.arcTo(s,n,s+o,n,o),t.closePath()}function Ax(t){return(s,n,a)=>{const i=typeof n.label=="string"?n.label:null,r=a.labelSize+10,o=n.x+n.size+7,l=n.y-r/2;if(s.save(),s.font=`${a.labelWeight} ${a.labelSize}px ${a.labelFont}`,s.fillStyle=t.background,s.strokeStyle=t.edgeActive,s.lineWidth=1.5,s.beginPath(),s.arc(n.x,n.y,n.size+3,0,Math.PI*2),s.fill(),s.stroke(),s.fillStyle=n.color,s.beginPath(),s.arc(n.x,n.y,n.size,0,Math.PI*2),s.fill(),i){const c=Math.ceil(s.measureText(i).width)+16;Cx(s,o,l,c,r,5),s.fillStyle=t.background,s.fill(),s.strokeStyle=t.edgeActive,s.lineWidth=1,s.stroke(),s.fillStyle=t.label,s.textBaseline="middle",s.fillText(i,o+8,n.y)}s.restore()}}function $x(){if(typeof document>"u")return!1;try{const t=document.createElement("canvas");return!!(t.getContext("webgl2")||t.getContext("webgl"))}catch{return!1}}function Px(){return e.jsx("div",{className:"flex h-full min-h-80 items-center justify-center px-6 text-center",children:e.jsxs("div",{className:"max-w-md",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"Interactive map unavailable"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"This browser could not start WebGL. The page inventory remains available for the complete crawl."})]})})}function Rx({reactSigma:t,graph:s,theme:n,selectedNodeKey:a,onSelectNodeKey:i,onHoverNode:r,onCameraReady:o}){const{useSigma:l,useRegisterEvents:c,useCamera:u}=t,m=l(),h=c(),{zoomIn:x,zoomOut:N,reset:f,gotoNode:w}=u(),[b,A]=d.useState(null),[T,P]=d.useState(()=>m.getCamera().getState().ratio>Pn),j=d.useRef(T),p=b??a;return d.useEffect(()=>(o({zoomIn:()=>x({duration:ta}),zoomOut:()=>N({duration:ta}),reset:()=>f({duration:ta}),gotoNode:y=>w(y,{duration:ta})}),()=>o(null)),[w,o,f,x,N]),d.useEffect(()=>{h({enterNode:({node:y,event:v})=>{A(y),r({nodeKey:y,left:Number.isFinite(v.x)?v.x+14:20,top:Number.isFinite(v.y)?v.y+14:20})},leaveNode:()=>{A(null),r(null)},clickNode:({node:y})=>i(y),clickStage:()=>r(null),updated:y=>{const v=y.ratio>Pn;j.current!==v&&(j.current=v,P(v))}})},[r,i,h]),d.useEffect(()=>{const y=jx(s,p,T?Pn+Number.EPSILON:Pn,n);m.setSetting("nodeReducer",y.nodeReducer),m.setSetting("edgeReducer",y.edgeReducer),m.refresh()},[p,s,T,m,n]),null}function Lx({nodes:t,edges:s,layoutState:n="ready",layoutUnavailableReason:a,selectedNodeKey:i,onSelectNode:r,ariaLabel:o,className:l}){const c=d.useRef(null),u=d.useRef(null),m=d.useRef(null),h=d.useId(),x=d.useId(),N=d.useId(),[f,w]=d.useState(null),[b,A]=d.useState(null),[T,P]=d.useState("checking"),[j,p]=d.useState(!1),[y,v]=d.useState(null),[D,q]=d.useState(null),[S,k]=d.useState(""),[F,C]=d.useState(!1),[I,me]=d.useState(0),[pe,J]=d.useState(""),ne=d.useRef(null),Z=d.useDeferredValue(S),Q=i===void 0?y:i,V=d.useMemo(()=>new Map(t.map(X=>[X.nodeKey,X])),[t]),$=Q?V.get(Q)??null:null,te=D?V.get(D.nodeKey)??null:null,ce=d.useMemo(()=>vx(t,Z),[Z,t]),re=t.some(X=>Number.isFinite(X.x)&&Number.isFinite(X.y)),Y=d.useMemo(()=>f?yx(t,s,f):null,[s,t,f]),fe=d.useMemo(()=>f?{allowInvalidContainer:!0,defaultNodeColor:f.unchecked,defaultEdgeColor:f.edge,defaultEdgeType:"line",enableCameraPanning:!0,enableCameraZooming:!0,enableCameraRotation:!1,enableEdgeEvents:!1,hideEdgesOnMove:!0,hideLabelsOnMove:!0,itemSizesReference:"screen",defaultDrawNodeHover:Ax(f),labelColor:{color:f.label},labelDensity:.2,labelFont:"Geist Sans, sans-serif",labelRenderedSizeThreshold:8,labelSize:13,labelWeight:"600",maxCameraRatio:12,minCameraRatio:.04,minEdgeThickness:.35,renderEdgeLabels:!1,renderLabels:!0,stagePadding:42,zIndex:!0}:null,[f]);d.useEffect(()=>{const X=c.current;if(!X)return;const Ne=()=>w(kx(X));if(Ne(),typeof MutationObserver>"u")return;const O=new MutationObserver(Ne);return O.observe(document.documentElement,{attributes:!0,attributeFilter:["class","data-theme","style"]}),()=>O.disconnect()},[]),d.useEffect(()=>{if(t.length===0||n==="unavailable"||!re){P("checking");return}P($x()?"ready":"unavailable")},[re,n,t.length]),d.useEffect(()=>{if(T!=="ready"){A(null);return}let X=!0;return Fc(()=>import("./react-sigma_core.esm.min-DnypJl5w.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13]),import.meta.url).then(Ne=>{X&&A(Ne)}).catch(()=>{X&&P("unavailable")}),()=>{X=!1}},[T]),d.useEffect(()=>{me(0)},[Z]);const U=d.useCallback(X=>{m.current=X,p(!!X)},[]),be=d.useCallback(X=>{q(X)},[]),Ce=d.useCallback((X,Ne)=>{const O=V.get(X);O&&(i===void 0&&v(X),r?.(O),Ne&&m.current?.gotoNode(X),J(`Focused ${O.path||"/"}`))},[V,r,i]),G=d.useCallback(X=>{Ce(X,!1)},[Ce]);d.useEffect(()=>{if(!j||!i||!V.has(i)){i||(ne.current=null);return}ne.current!==i&&(m.current?.gotoNode(i),ne.current=i)},[j,V,i]);const Ee=X=>{Ce(X.nodeKey,!0),k(X.path||X.url),C(!1)},Re=()=>{window.setTimeout(()=>{document.activeElement!==u.current&&C(!1)},0)},M=`Interactive site map showing ${sa(t.length,"page")} and ${sa(s.length,"internal link")}`,de=X=>`${x}-${X.replaceAll(/[^\w-]/g,"-")}`,ke=Nx(a);if(n==="unavailable")return e.jsx("section",{ref:c,role:"group","aria-label":o??M,className:vn("flex min-h-80 items-center justify-center rounded-lg border border-default bg-surface-inset px-6 text-center",l),children:e.jsxs("div",{className:"max-w-md",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:ke.heading}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:ke.detail})]})});if(t.length===0)return e.jsx("section",{ref:c,role:"group","aria-label":o??M,className:vn("flex min-h-80 items-center justify-center rounded-lg border border-default bg-surface-inset px-6 text-center",l),children:e.jsx("p",{className:"max-w-md text-sm text-secondary",children:"No page graph is available for this scan."})});if(!re)return e.jsx("section",{ref:c,role:"group","aria-label":o??M,className:vn("flex min-h-80 items-center justify-center rounded-lg border border-default bg-surface-inset px-6 text-center",l),children:e.jsxs("div",{className:"max-w-md",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:ke.heading}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:ke.detail})]})});const Oe=ce.at(I),Me=e.jsx(Px,{}),W=b?.SigmaContainer;return e.jsxs("section",{ref:c,role:"group","aria-label":o??M,"aria-describedby":N,className:vn("flex h-[clamp(460px,62vh,680px)] min-h-[460px] flex-col overflow-hidden rounded-lg border border-default bg-surface-inset",l),children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 border-b border-subtle bg-bg-elevated/70 px-3 py-2",children:[e.jsx("label",{htmlFor:h,className:"sr-only",children:"Focus a page in the site map"}),e.jsxs("div",{className:"relative min-w-56 max-w-lg flex-1",children:[e.jsx(pi,{className:"pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted","aria-hidden":"true"}),e.jsx("input",{id:h,ref:u,role:"combobox",type:"search",autoComplete:"off","aria-label":"Focus a page in the site map","aria-autocomplete":"list","aria-controls":x,"aria-expanded":F,"aria-activedescendant":F&&Oe?de(Oe.nodeKey):void 0,value:S,placeholder:$?`Focused: ${$.path||"/"}`:"Find a page",className:"h-10 w-full rounded-md border border-base bg-bg py-2 pl-9 pr-3 text-sm text-primary placeholder-mono-600 outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onFocus:()=>C(!0),onBlur:Re,onChange:X=>{k(X.target.value),C(!0)},onKeyDown:X=>{X.key==="ArrowDown"?(X.preventDefault(),C(!0),me(Ne=>Math.max(0,Math.min(ce.length-1,Ne+1)))):X.key==="ArrowUp"?(X.preventDefault(),me(Ne=>Math.max(0,Ne-1))):X.key==="Enter"&&F&&Oe?(X.preventDefault(),Ee(Oe)):X.key==="Escape"&&C(!1)}}),F&&e.jsxs("div",{className:"absolute left-0 right-0 top-[calc(100%+0.25rem)] z-30 overflow-hidden rounded-md border border-base bg-bg shadow-lg",children:[e.jsx("div",{id:x,role:"listbox","aria-label":"Matching pages",className:"max-h-72 overflow-auto py-1",children:ce.length>0?ce.map((X,Ne)=>{const O=fa(X);return e.jsxs("button",{id:de(X.nodeKey),type:"button",role:"option","aria-selected":Ne===I,tabIndex:-1,className:vn("flex min-h-11 w-full items-center justify-between gap-3 px-3 py-2 text-left text-sm outline-none",Ne===I?"bg-surface-active text-primary":"text-secondary hover:bg-surface-hover hover:text-primary"),onPointerDown:E=>E.preventDefault(),onMouseDown:E=>E.preventDefault(),onMouseEnter:()=>me(Ne),onClick:()=>Ee(X),children:[e.jsx("span",{className:"min-w-0 truncate font-mono",children:X.path||"/"}),e.jsxs("span",{className:"flex shrink-0 items-center gap-1.5 text-[13px] text-muted",children:[e.jsx("span",{className:"font-mono font-semibold",style:{color:`var(${Ws[O].property})`},"aria-hidden":"true",children:ri(O)}),e.jsx("span",{children:ua(O)})]})]},X.nodeKey)}):e.jsx("p",{className:"px-3 py-4 text-sm text-secondary",children:"No rendered pages match."})}),ce.length===50&&e.jsx("p",{className:"border-t border-subtle px-3 py-2 text-[13px] text-muted",children:"First 50 matches. Refine the search or use the full page inventory."})]})]}),e.jsxs("span",{className:"text-[13px] tabular-nums text-muted",children:[sa(t.length,"page")," · ",sa(s.length,"link")]})]}),e.jsx("div",{className:"relative min-h-0 flex-1 overflow-hidden",children:T==="unavailable"?Me:T==="checking"||!f||!Y||!fe||!b||!W?e.jsx("div",{className:"flex h-full min-h-80 items-center justify-center px-6 text-center",role:"status",children:e.jsx("p",{className:"text-sm text-secondary",children:"Preparing the interactive site map..."})}):e.jsxs(wx,{fallback:Me,resetToken:Y.graph,children:[e.jsx("div",{"aria-hidden":"true",className:"absolute inset-0",children:e.jsx(W,{graph:Y.graph,className:"relative size-full bg-bg [&_.sigma-container]:size-full",style:{width:"100%",height:"100%",background:f.background},settings:fe,children:e.jsx(Rx,{reactSigma:b,graph:Y.graph,theme:f,selectedNodeKey:Q,onSelectNodeKey:G,onHoverNode:be,onCameraReady:U})})}),e.jsxs("div",{className:"absolute right-3 top-3 z-20 flex flex-col overflow-hidden rounded-md border border-base bg-bg shadow-lg",children:[e.jsx(L,{type:"button",variant:"ghost",size:"icon",className:"rounded-none border-b border-subtle","aria-label":"Zoom in",disabled:!j,onClick:()=>m.current?.zoomIn(),children:e.jsx(Iu,{className:"size-4","aria-hidden":"true"})}),e.jsx(L,{type:"button",variant:"ghost",size:"icon",className:"rounded-none border-b border-subtle","aria-label":"Zoom out",disabled:!j,onClick:()=>m.current?.zoomOut(),children:e.jsx(fo,{className:"size-4","aria-hidden":"true"})}),e.jsx(L,{type:"button",variant:"ghost",size:"icon",className:"rounded-none","aria-label":"Fit site map",disabled:!j,onClick:()=>m.current?.reset(),children:e.jsx(Du,{className:"size-4","aria-hidden":"true"})})]}),te&&D&&e.jsxs("div",{role:"tooltip",className:"pointer-events-none absolute z-20 max-w-64 rounded-md border border-base bg-bg/95 px-3 py-2 shadow-lg",style:{left:D.left,top:D.top},children:[e.jsx("p",{className:"truncate font-mono text-[13px] font-medium text-heading",children:te.path||"/"}),e.jsxs("p",{className:"mt-1 text-[13px] text-secondary",children:[ua(fa(te))," · depth ",te.depth??"unknown"]}),te.auditScore!=null&&e.jsxs("p",{className:"mt-1 font-mono text-[13px] text-heading",children:["Technical score ",Math.round(te.auditScore),"/100"]})]})]})}),e.jsxs("div",{"aria-label":"Site map legend",className:"flex flex-wrap items-center gap-x-4 gap-y-2 border-t border-subtle bg-bg-elevated/50 px-3 py-2 text-[13px] text-secondary",children:[["eligible","hidden","failed","unchecked"].map(X=>e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"w-3 text-center font-mono text-[15px] font-semibold leading-none",style:{color:`var(${Ws[X].property})`},"aria-hidden":"true",children:ri(X)}),ua(X)]},X)),e.jsx("span",{className:"ml-auto",children:"Size shows internal-link importance"}),Y&&(Y.omittedNodes>0||Y.omittedEdges>0)&&e.jsx("span",{className:"text-caution",children:"Some records lacked valid layout data."})]}),e.jsx("p",{id:N,className:"sr-only",children:"The WebGL map supports pointer, wheel, and touch navigation. Use the page search to focus a rendered page. Use the full page inventory for an accessible list of every crawled page and its links."}),e.jsx("p",{role:"status","aria-live":"polite",className:"sr-only",children:pe})]})}function Ex(t){return t>=70?"positive":t>=40?"caution":"negative"}function Ix(t){return t>=70?"pass":t>=40?"partial":"fail"}function Dx(t){return t==="pass"?"positive":t==="partial"?"caution":"negative"}function Cr(t){return t==="pass"?"Pass":t==="partial"?"Partial":"Fail"}function Tx({audit:t,isLoading:s,error:n,onRetry:a}){return e.jsxs("section",{className:"border-t border-default pt-5","aria-labelledby":"site-health-page-audit-heading",children:[e.jsxs("div",{children:[e.jsx("h3",{id:"site-health-page-audit-heading",className:"text-base font-semibold text-heading",children:"Why this technical score"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Findings and fixes from this page in the selected scan."})]}),s?e.jsx("p",{className:"mt-4 text-sm text-secondary",role:"status",children:"Loading technical findings..."}):n?e.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-between gap-3 border-y border-negative bg-negative-soft px-4 py-3",role:"alert",children:[e.jsx("p",{className:"text-sm text-negative",children:"Technical findings could not be loaded."}),e.jsx(L,{type:"button",variant:"secondary",size:"sm",onClick:a,children:"Retry technical findings"})]}):t?t.state==="no-crawl"?e.jsx("p",{className:"mt-4 text-sm text-secondary",children:"No Site Health scan is available."}):t.state==="details-unavailable"?e.jsx("p",{className:"mt-4 text-sm text-secondary",children:"This scan preserved its summary, but not page-level audit evidence."}):t.state==="not-found"?e.jsx("p",{className:"mt-4 text-sm text-secondary",children:"This page is not present in the selected scan."}):t.state==="not-audited"?e.jsx("p",{className:"mt-4 text-sm text-secondary",children:"This page was discovered, but it was not technically audited."}):e.jsx(Mx,{audit:t}):e.jsx("p",{className:"mt-4 text-sm text-secondary",children:"Technical findings are unavailable for this page."})]})}function Mx({audit:t}){const s=t.factors.filter(n=>n.applicable!==!1&&(n.status!=="pass"||n.findings.some(a=>a.type==="missing"||a.type==="timeout"||a.type==="unreachable")));return e.jsxs("div",{className:"mt-4",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline gap-2",children:[e.jsxs("span",{"aria-label":`Technical score ${Math.round(t.auditScore)} out of 100`,className:"font-mono text-2xl font-semibold tabular-nums text-heading",children:[Math.round(t.auditScore),e.jsx("span",{className:"text-sm text-muted",children:"/100"})]}),e.jsx(oe,{tone:Ex(t.auditScore),children:Cr(Ix(t.auditScore))})]}),t.evidenceState==="scores-only"&&e.jsx("p",{className:"mt-3 border border-caution bg-caution-soft px-3 py-2 text-sm text-caution",children:"This older scan preserved factor scores, but not the original finding text or fixes."}),t.criticalDefects.length>0&&e.jsxs("section",{className:"mt-5","aria-labelledby":"site-health-critical-defects-heading",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("h4",{id:"site-health-critical-defects-heading",className:"text-sm font-semibold text-heading",children:"Score-independent defects"}),e.jsx(oe,{tone:t.criticalDefects.some(n=>n.severity==="critical")?"negative":"caution",children:t.criticalDefects.length}),e.jsx("span",{className:"text-xs text-muted",children:"Not included in the weighted score"})]}),e.jsx("ul",{className:"mt-2 divide-y divide-default border-y border-default",children:t.criticalDefects.map(n=>e.jsxs("li",{className:"py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:n.detail}),e.jsx(oe,{tone:n.severity==="critical"?"negative":"caution",children:n.severity==="critical"?"Critical":"Warning"})]}),e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:[e.jsx("span",{className:"font-medium text-heading",children:"Fix:"})," ",n.recommendation]})]},n.id))})]}),s.length>0?e.jsx("div",{className:"mt-5 divide-y divide-default border-y border-default",children:s.map((n,a)=>e.jsxs("details",{open:a===0,className:"group py-1",children:[e.jsxs("summary",{className:"flex min-h-12 cursor-pointer list-none items-center justify-between gap-3 rounded-sm px-1 py-2 outline-none marker:hidden focus-visible:ring-2 focus-visible:ring-mono-400 [&::-webkit-details-marker]:hidden",children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-2 text-sm font-medium text-heading",children:[e.jsx(qn,{className:"size-4 shrink-0 text-muted transition-transform group-open:rotate-90","aria-hidden":"true"}),n.name]}),e.jsxs("span",{className:"flex shrink-0 items-center gap-2",children:[e.jsxs("span",{className:"font-mono text-sm tabular-nums text-heading",children:[Math.round(n.score),"/100"]}),e.jsx(oe,{tone:Dx(n.status),children:Cr(n.status)})]})]}),e.jsxs("div",{className:"grid gap-4 px-1 pb-4 pt-1 md:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("h5",{className:"text-xs font-semibold uppercase tracking-wide text-muted",children:"Evidence"}),n.findings.length>0?e.jsx("ul",{className:"mt-2 space-y-1.5 text-sm text-secondary",children:n.findings.map((i,r)=>e.jsx("li",{children:i.message},`${i.code}:${r}`))}):e.jsx("p",{className:"mt-2 text-sm text-secondary",children:t.evidenceState==="scores-only"?"Finding text was not preserved for this factor.":"No finding text was emitted for this factor."})]}),e.jsxs("div",{children:[e.jsx("h5",{className:"text-xs font-semibold uppercase tracking-wide text-muted",children:"Recommended fix"}),n.recommendations.length>0?e.jsx("ol",{className:"mt-2 list-decimal space-y-1.5 pl-5 text-sm text-secondary marker:text-muted",children:n.recommendations.map(i=>e.jsx("li",{children:i},i))}):e.jsx("p",{className:"mt-2 text-sm text-secondary",children:t.evidenceState==="scores-only"?"No page-specific fix was preserved.":"No page-specific fix was emitted."}),e.jsxs("p",{className:"mt-3 text-xs text-muted",children:["Weight: ",n.weight,"% of the page score"]})]})]})]},n.id))}):t.criticalDefects.length===0&&t.evidenceState==="complete"?e.jsx("p",{className:"mt-4 border-y border-positive bg-positive-soft px-4 py-3 text-sm text-positive",children:"No technical findings need attention on this page."}):t.criticalDefects.length===0?e.jsx("p",{className:"mt-4 border-y border-default px-4 py-3 text-sm text-secondary",children:"No below-pass factor scores were preserved. Detailed finding evidence is unavailable."}):null]})}const _x=100,Oa=12,Gx=[];function Ox(t){return Co(t.url)}function na(t){return t>=70?"positive":t>=40?"caution":"negative"}function aa(t){return t>=70?"text-positive-400":t>=40?"text-caution-400":"text-negative-400"}function qx(t){return t==="pass"?"positive":t==="partial"?"caution":"negative"}function kn(t){return t>=70?"Pass":t>=40?"Partial":"Fail"}function Fx(t){return gi(ss(String(t)))}function Ux(t){return Ns(ss(String(t)))}function zx({projectName:t,projectId:s,runId:n,integrated:a=!1}){const[i,r]=d.useState(!1),[o,l]=d.useState(null),[c,u]=d.useState(null),m=n===void 0?c:n,[h,x]=d.useState(!1),N=d.useRef(null),f=De(Uc({client:H,path:{name:t},...m?{query:{runId:m}}:{}})),w=De({...zc({client:H,path:{name:t},query:{limit:30}}),enabled:!a}),b=De(Bc({client:H,path:{name:t},query:{limit:_x,sort:"score-asc",...m?{runId:m}:{}}})),A=De({...mi({client:H,path:{name:t},query:{kind:ws["site-audit"],limit:10}}),enabled:!a,refetchOnWindowFocus:"always",refetchInterval:G=>G.state.data?.some(Re=>Re.status==="queued"||Re.status==="running")?3e3:1e4}),T=uo(),P=d.useSyncExternalStore(io,ha,ha),j=Object.values(P.runs).find(G=>G.kind===ws["site-audit"]&&G.projectId===s),p=A.data??[],y=p.find(G=>G.status==="queued"||G.status==="running"),v=p.at(-1),D=T.isPending||!!j||!!y,q=T.isPending?"starting":y?.status??j?.lastAnnouncedStatus,S=d.useCallback(async()=>{const G=await Promise.all([f.refetch(),b.refetch(),...a?[]:[w.refetch()]]),Ee=G.find(Re=>Re.error);if(Ee?.error)throw Ee.error;return G[0]},[a,b.refetch,f.refetch,w.refetch]);d.useEffect(()=>{a||m||!v||v.status!=="completed"&&v.status!=="partial"||f.data?.runId===v.id||N.current===v.id||(N.current=v.id,S().catch(G=>{$e({title:"Technical AEO auto-refresh failed",detail:G instanceof Error?G.message:"Could not load the completed audit.",tone:"negative",dedupeKey:`technical-aeo:auto-refresh:${t}`,dedupeMode:"replace"})}))},[m,a,v?.id,v?.status,t,S,f.data?.runId]);const k=async()=>{x(!0);try{const G=await S();$e({title:"Technical AEO refreshed",detail:D?"The audit is still running. This view will refresh again when it finishes.":G.data?.hasData?`Latest score is ${G.data.aggregateScore}/100 from ${G.data.pagesAudited} audited page${G.data.pagesAudited===1?"":"s"}.`:"No audit data yet. Run an audit to crawl the sitemap.",tone:G.data?.hasData?"positive":"caution",dedupeKey:`technical-aeo:refresh:${t}`,dedupeMode:"replace"})}catch(G){$e({title:"Technical AEO refresh failed",detail:G instanceof Error?G.message:"Could not reload technical audit data.",tone:"negative",dedupeKey:`technical-aeo:refresh:${t}`,dedupeMode:"replace"})}finally{x(!1)}},F=()=>T.mutate({projectName:t,projectId:s}),C=q==="running"?"Audit running":q==="queued"?"Audit queued":"Starting audit",I=f.data,me=b.data?.pages??Gx,pe=(I?.pagesErrored??0)>0,J=i&&pe,ne=d.useMemo(()=>J?me.filter(G=>G.status==="error"):me,[me,J]),Z=_n({rows:ne,getSearchText:Ox}),Q=I?I.pagesAudited>me.length:!1,V=I?.crossCuttingIssues[0]?.factorId??I?.factors.find(G=>G.pagesPartial+G.pagesFailing>0)?.id??null;if(d.useEffect(()=>{r(!1),l(a?V:null)},[m,a,V]),f.isLoading)return e.jsxs("div",{className:`flex min-h-40 items-center justify-center gap-2 text-sm text-secondary ${a?"":"mt-6"}`,role:"status",children:[e.jsx(It,{className:"size-4 motion-safe:animate-spin","aria-hidden":"true"}),"Loading technical checks..."]});if(f.error)return e.jsxs("section",{className:`flex flex-col gap-4 rounded-lg border border-negative bg-negative-soft px-5 py-5 sm:flex-row sm:items-center sm:justify-between ${a?"":"mt-6"}`,role:"alert",children:[e.jsxs("div",{className:"flex min-w-0 gap-3",children:[e.jsx(Xa,{className:"mt-0.5 size-4 shrink-0 text-negative","aria-hidden":"true"}),e.jsxs("div",{children:[a?e.jsx("h3",{className:"font-semibold text-negative",children:"Technical checks could not load"}):e.jsx("h2",{className:"font-semibold text-negative",children:"Technical checks could not load"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"The saved audit could not be read. Try loading it again."})]})]}),e.jsxs(L,{type:"button",variant:"secondary",size:"sm",className:"shrink-0",onClick:()=>{k()},disabled:h,children:[e.jsx(Is,{className:`size-4 ${h?"motion-safe:animate-spin":""}`,"aria-hidden":"true"}),h?"Trying again...":"Try again"]})]});if(!I||!I.hasData)return a?e.jsxs("section",{className:"rounded-lg border border-default bg-surface-subtle px-5 py-7 text-center",children:[e.jsx(Yi,{className:"mx-auto size-7 text-muted","aria-hidden":"true"}),e.jsx("h2",{className:"mt-3 text-base font-semibold text-heading",children:"Technical checks unavailable"}),e.jsx("p",{className:"mx-auto mt-2 max-w-md text-sm text-secondary",children:"Run a new Site Health scan to calculate page-level technical findings."})]}):e.jsxs(ye,{className:"surface-card mt-6 p-8 text-center",children:[e.jsx(Yi,{className:"mx-auto mb-3 h-8 w-8 text-muted","aria-hidden":"true"}),e.jsx("h2",{className:"text-base font-semibold text-heading",children:"No technical audit yet"}),e.jsx("p",{className:"supporting-copy mx-auto mt-2 max-w-md",children:"A technical AEO audit crawls your sitemap and scores every page for structured data, AI-readable content, crawler access, freshness, and more, then rolls it up into one site score."}),!ie()&&e.jsx("div",{className:"mt-5 flex items-center justify-center gap-3",children:e.jsxs(nt,{type:"button",onClick:F,disabled:D,children:[D?e.jsx(It,{className:"mr-1.5 h-4 w-4 motion-safe:animate-spin","aria-hidden":"true"}):e.jsx(Ms,{className:"mr-1.5 h-4 w-4","aria-hidden":"true"}),D?C:"Run first audit"]})}),D?e.jsx("p",{className:"mt-3 text-xs text-muted",role:"status","aria-live":"polite",children:"The dashboard will refresh automatically when the audit finishes."}):null]});const $=I.deltaScore==null?null:`${I.deltaScore>=0?"+":""}${I.deltaScore} vs previous`,te=I.trend==="up"?"positive":I.trend==="down"?"negative":"neutral",ce=w.data?.points??[],re=ce.map(G=>({runId:G.runId,date:G.auditedAt,score:G.aggregateScore})),Y=n===void 0&&c!==null,fe=me.filter(G=>G.status==="success"),U=I.factors.filter(G=>G.pagesPartial+G.pagesFailing>0).length,be=I.crossCuttingIssues.some(G=>G.topRecommendations.length>0);function Ce(G){const Ee=[];for(const Re of fe){const M=Re.factors.find(de=>de.id===G);M&&M.score<70&&Ee.push({url:Re.url,score:M.score})}return Ee.sort((Re,M)=>Re.score-M.score)}return e.jsxs("div",{className:a?"":"mt-6",children:[a?e.jsxs("section",{className:"flex flex-col gap-3 border-b border-default pb-5 sm:flex-row sm:items-end sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-secondary",children:"Site score"}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2",children:[e.jsxs("span",{"aria-label":`Site score ${I.aggregateScore} out of 100`,className:`inline-flex items-baseline gap-1 font-mono tabular-nums ${aa(I.aggregateScore)}`,children:[e.jsx("span",{className:"text-3xl font-semibold",children:I.aggregateScore}),e.jsx("span",{className:"text-sm text-muted",children:"/100"})]}),e.jsx(oe,{tone:na(I.aggregateScore),children:kn(I.aggregateScore)}),$?e.jsx(oe,{tone:te,children:$}):null]})]}),e.jsxs("p",{className:"flex flex-wrap items-center gap-x-2 gap-y-1 text-sm tabular-nums text-secondary",children:[e.jsxs("span",{children:[I.pagesAudited," page",I.pagesAudited===1?"":"s"," checked"]}),e.jsx("span",{"aria-hidden":"true",className:"text-faint",children:"·"}),e.jsxs("span",{children:[U," check",U===1?"":"s"," need",U===1?"s":""," attention"]}),I.pagesErrored>0?e.jsxs(e.Fragment,{children:[e.jsx("span",{"aria-hidden":"true",className:"text-faint",children:"·"}),e.jsxs("span",{className:"text-negative",children:[I.pagesErrored," crawl error",I.pagesErrored===1?"":"s"]})]}):null]})]}):e.jsxs("section",{className:"surface-card flex flex-wrap items-start justify-between gap-6 rounded-lg border border-default bg-surface p-6",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:Y?"Technical AEO history":"Technical AEO"}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-baseline gap-3",children:[e.jsx("span",{className:`text-4xl font-semibold tabular-nums ${aa(I.aggregateScore)}`,children:I.aggregateScore}),e.jsx("span",{className:"text-lg text-muted",children:"/ 100"}),e.jsx(oe,{tone:na(I.aggregateScore),children:kn(I.aggregateScore)}),$?e.jsx(oe,{tone:te,children:$}):null,D?e.jsx(oe,{tone:"neutral",children:C}):null]}),e.jsxs("p",{className:"supporting-copy mt-2 tabular-nums",children:[I.pagesDiscovered," URL",I.pagesDiscovered===1?"":"s"," in sitemap · ",I.pagesAudited," audited · ",I.pagesSkipped," skipped · ",I.pagesErrored," errored"]}),e.jsxs("p",{className:"mt-1 flex flex-wrap items-center gap-x-1.5 text-xs text-muted",children:[e.jsx("span",{className:"text-faint",children:"Sitemap:"}),e.jsx("a",{href:I.sitemapUrl??"#",target:"_blank",rel:"noreferrer",className:"max-w-[22rem] truncate text-secondary underline decoration-mono-700 underline-offset-2 hover:text-strong",children:I.sitemapUrl}),e.jsx(at,{text:"Every audit re-reads this sitemap, so pages you add or remove are picked up on the next run. Discovered/audited counts and the score reflect the sitemap at the time of the latest run. Override it with `canonry technical-aeo run <project> --sitemap-url <url>`."})]}),I.auditedAt?e.jsxs("p",{className:"mt-0.5 text-xs text-faint",children:["Audited ",new Date(I.auditedAt).toLocaleString()]}):null,D?e.jsx("p",{className:"mt-1 text-xs text-muted",role:"status","aria-live":"polite",children:"Results refresh automatically when this audit finishes."}):null]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[n===void 0&&ce.length>1?e.jsxs("select",{"aria-label":"View a Technical AEO audit",value:c??"",onChange:G=>u(G.target.value||null),className:"min-h-11 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:[e.jsx("option",{value:"",children:"Latest audit"}),[...ce].reverse().slice(1).map(G=>e.jsxs("option",{value:G.runId,children:[new Date(G.auditedAt).toLocaleDateString()," · ",G.aggregateScore,"/100"]},G.runId))]}):null,e.jsxs(L,{type:"button",variant:"outline",size:"sm",onClick:()=>{k()},disabled:h,children:[e.jsx(Is,{className:`mr-1.5 h-4 w-4 ${h?"motion-safe:animate-spin":""}`,"aria-hidden":"true"}),h?"Refreshing…":"Refresh"]}),!ie()&&e.jsxs(nt,{type:"button",size:"sm",onClick:F,disabled:D,children:[D?e.jsx(It,{className:"mr-1.5 h-4 w-4 motion-safe:animate-spin","aria-hidden":"true"}):e.jsx(Ms,{className:"mr-1.5 h-4 w-4","aria-hidden":"true"}),D?C:"Re-run audit"]})]})]}),!a&&re.length>=2?e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h2",{children:"Site score over time"})]}),e.jsxs("div",{className:"mt-3 h-56",children:[e.jsxs("p",{className:"sr-only",children:["Technical AEO scores range from ",Math.min(...re.map(G=>G.score))," to ",Math.max(...re.map(G=>G.score))," across ",re.length," audits. Use the audit selector to inspect a previous scorecard."]}),e.jsx("div",{className:"h-full","aria-hidden":"true",children:e.jsx(sn,{width:"100%",height:"100%",children:e.jsxs(nn,{data:re,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(fi,{stroke:xi,vertical:!1}),e.jsx(an,{dataKey:"date",tick:Ot,tickLine:!1,axisLine:{stroke:us},tickFormatter:Fx,minTickGap:24}),e.jsx(rn,{domain:[0,100],ticks:[0,25,50,75,100],tick:Ot,tickLine:!1,axisLine:!1,width:32}),e.jsx(on,{...Ds,cursor:{stroke:us,strokeWidth:1},labelFormatter:Ux,formatter:G=>[`${G}/100`,"Site score"]}),e.jsx(bi,{type:"monotone",dataKey:"score",name:"score",stroke:cs.positive,strokeWidth:2.5,dot:{r:2.5,fill:cs.positive,strokeWidth:0},isAnimationActive:!1})]})})})]})]}):null,e.jsxs("section",{className:a?"pt-5":"page-section-divider",children:[a?e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Technical findings"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:be?"Select a check to see affected pages and recommended fixes.":"Select a check to see affected pages and score details."})]}):e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Scorecard"}),e.jsxs("h2",{className:"inline-flex items-center gap-1.5",children:["Ranking factors",e.jsx(at,{text:"Each factor is scored 0–100 per page (via the aeo-audit engine), then averaged across all successfully-audited pages. Pass ≥70, partial 40–69, fail <40. Expand a row to see which pages fall short and how to fix it."})]})]}),e.jsx("div",{className:"evidence-table-wrap mt-3",children:e.jsxs("table",{className:`evidence-table ${a?"min-w-[42rem]":""}`,children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:a?"Technical check":"Factor"}),a?null:e.jsx("th",{className:"text-right",children:"Weight"}),e.jsx("th",{className:"text-right",children:a?"Score":"Avg"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:a?"Pages affected":"Pass / Partial / Fail"})]})}),e.jsx("tbody",{children:I.factors.map(G=>{const Ee=o===G.id,Re=I.crossCuttingIssues.find(W=>W.factorId===G.id),M=Ee?Ce(G.id):[],de=G.pagesPartial+G.pagesFailing,ke=G.pagesPassing+de,Oe=!!Re?.topRecommendations.length,Me=Oe&&de>0;return e.jsxs(d.Fragment,{children:[e.jsxs("tr",{className:Ee?"bg-surface-subtle":void 0,children:[e.jsx("td",{children:e.jsxs("button",{type:"button",className:"flex min-h-11 w-full items-center gap-2 text-left font-medium text-strong outline-none hover:text-primary focus-visible:text-primary focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-mono-400","aria-expanded":Ee,onClick:()=>l(Ee?null:G.id),children:[Ee?e.jsx(tn,{className:"size-4 shrink-0 text-muted","aria-hidden":"true"}):e.jsx(qn,{className:"size-4 shrink-0 text-muted","aria-hidden":"true"}),G.name]})}),a?null:e.jsxs("td",{className:"text-right tabular-nums text-muted",children:[G.weight,"%"]}),e.jsxs("td",{className:"text-right font-mono tabular-nums text-strong",children:[G.avgScore,a?e.jsx("span",{className:"text-muted",children:"/100"}):null]}),e.jsx("td",{children:e.jsx(oe,{tone:qx(G.status),children:kn(G.avgScore)})}),a?e.jsxs("td",{className:`tabular-nums ${de>0?"text-strong":"text-muted"}`,children:[de," of ",ke]}):e.jsxs("td",{className:"tabular-nums text-secondary",children:[e.jsx("span",{className:"text-positive-400",children:G.pagesPassing})," / ",e.jsx("span",{className:"text-caution-400",children:G.pagesPartial})," / ",e.jsx("span",{className:"text-negative-400",children:G.pagesFailing})]})]}),Ee?e.jsx("tr",{className:"bg-surface-subtle",children:e.jsx("td",{colSpan:a?4:5,className:"px-4 pb-5 pt-0",children:e.jsxs("div",{className:`grid gap-5 border-t border-subtle pt-4 ${Me?"lg:grid-cols-2":""}`,children:[Oe&&Re?e.jsxs("section",{"aria-labelledby":`technical-finding-${G.id}-fixes`,children:[e.jsx("h4",{id:`technical-finding-${G.id}-fixes`,className:"text-sm font-semibold text-heading",children:"Recommended fixes"}),e.jsx("ol",{className:"mt-2 list-decimal space-y-1.5 pl-5 marker:text-muted",children:Re.topRecommendations.map((W,X)=>e.jsx("li",{className:"pl-1 text-sm text-secondary",children:W},X))}),a?e.jsxs("p",{className:"mt-3 text-xs text-muted",children:["Weight: ",G.weight,"% of the site score"]}):null]}):de===0?e.jsx("p",{className:"text-sm text-secondary",children:"Every audited page passes this check."}):null,de>0?e.jsxs("section",{"aria-labelledby":`technical-finding-${G.id}-pages`,children:[e.jsxs("h4",{id:`technical-finding-${G.id}-pages`,className:"text-sm font-semibold text-heading",children:["Affected pages (",de,")"]}),a&&b.isLoading?e.jsxs("div",{className:"mt-3 flex items-center gap-2 text-sm text-secondary",role:"status",children:[e.jsx(It,{className:"size-4 motion-safe:animate-spin","aria-hidden":"true"}),"Loading affected pages..."]}):a&&b.error?e.jsxs("div",{className:"mt-3",role:"alert",children:[e.jsx("p",{className:"text-sm font-medium text-negative",children:"Affected pages could not load"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Try the page-level audit read again."}),e.jsxs(L,{type:"button",variant:"secondary",size:"sm",className:"mt-3",onClick:()=>{b.refetch()},disabled:b.isFetching,children:[b.isFetching?e.jsx(It,{className:"size-4 motion-safe:animate-spin","aria-hidden":"true"}):e.jsx(Is,{className:"size-4","aria-hidden":"true"}),b.isFetching?"Retrying affected pages...":"Retry affected pages"]})]}):M.length>0?e.jsx("ul",{className:"mt-2 space-y-1.5",children:M.slice(0,Oa).map(W=>e.jsxs("li",{className:"flex min-w-0 items-center gap-2 text-sm",children:[e.jsx("span",{className:`w-8 shrink-0 text-right font-mono tabular-nums ${aa(W.score)}`,children:W.score}),e.jsx("a",{href:W.url,target:"_blank",rel:"noreferrer",className:"min-w-0 truncate text-link outline-none hover:text-heading focus-visible:ring-2 focus-visible:ring-mono-400",title:W.url,children:W.url})]},W.url))}):e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Page details are not available in the loaded audit sample."}),M.length>Oa?e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["+ ",M.length-Oa," more below pass"]}):null,Q&&(!a||!b.isLoading&&!b.error)?e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Showing the worst ",me.length," audited pages."]}):null]}):null]})})}):null]},G.id)})})]})})]}),!a&&I.crossCuttingIssues.length>0?e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Opportunities"}),e.jsxs("h2",{className:"inline-flex items-center gap-1.5",children:["Prioritized fixes",e.jsx(at,{text:"Factors scoring below pass across the most pages, ranked by site-wide impact. Fixing one of these typically lifts many pages at once."})]})]}),e.jsx("div",{className:"mt-3 divide-y divide-mono-800/60 overflow-hidden rounded-lg border border-default",children:I.crossCuttingIssues.map(G=>e.jsxs("div",{className:"p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:G.factorName}),e.jsx(oe,{tone:na(G.avgScore),children:kn(G.avgScore)}),e.jsxs("span",{className:"text-xs tabular-nums text-muted",children:["avg ",G.avgScore," · affects ",G.affectedPages," of ",G.totalPages," pages (",G.affectedPct,"%)"]})]}),G.topRecommendations.length>0?e.jsx("ul",{className:"mt-2 space-y-1",children:G.topRecommendations.map((Ee,Re)=>e.jsxs("li",{className:"flex gap-2 text-sm text-secondary",children:[e.jsx("span",{className:"select-none text-faint",children:"→"}),e.jsx("span",{children:Ee})]},Re))}):null]},G.factorId))})]}):null,a?null:e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Pages"}),e.jsx("h2",{children:"Per-page breakdown"})]}),pe?e.jsxs("div",{className:"segmented",role:"group","aria-label":"Filter pages",children:[e.jsxs("button",{type:"button",onClick:()=>{r(!1),Z.setPage(1)},"aria-pressed":!J,className:`segmented-option min-h-11 tabular-nums ${J?"":"segmented-option-active"}`,children:["All ",I.pagesAudited]}),e.jsxs("button",{type:"button",onClick:()=>{r(!0),Z.setPage(1)},"aria-pressed":J,className:`segmented-option min-h-11 tabular-nums ${J?"segmented-option-active text-negative":""}`,children:["Errors ",I.pagesErrored]})]}):null]}),me.length>0?e.jsx(Ys,{value:Z.query,onChange:Z.setQuery,label:"Filter audited page URLs",placeholder:"Filter page URL or query parameters",className:"mt-3 max-w-md"}):null,Z.totalRows===0?e.jsx("p",{className:"supporting-copy mt-3",children:Z.hasQuery?"No pages match this filter.":"No pages recorded."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"evidence-table-wrap mt-3",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-right",children:"Score"}),e.jsx("th",{children:"Status"}),e.jsx("th",{className:"w-full",children:"URL"})]})}),e.jsx("tbody",{children:Z.rows.map(G=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-right tabular-nums",children:G.status==="error"?e.jsxs("span",{className:"inline-flex items-center gap-1 text-negative-400",children:[e.jsx(Xa,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"err"]}):e.jsx("span",{className:aa(G.overallScore),children:G.overallScore})}),e.jsx("td",{children:G.status==="error"?e.jsx(oe,{tone:"negative",children:"Error"}):e.jsx(oe,{tone:na(G.overallScore),children:kn(G.overallScore)})}),e.jsx("td",{className:"w-full max-w-0",children:e.jsx("a",{href:G.url,target:"_blank",rel:"noreferrer",className:"block truncate text-neutral hover:text-heading",title:G.status==="error"?G.error??G.url:G.url,children:e.jsx(In,{value:G.url,headLength:54,tailLength:20,title:G.status==="error"?G.error??G.url:G.url})})})]},G.url))})]})}),e.jsx(Ts,{page:Z.page,pageSize:Z.pageSize,visibleRows:Z.rows.length,totalRows:Z.totalRows,onPageChange:Z.setPage,itemLabel:Z.hasQuery?"matches":"rows"}),Q?e.jsxs("p",{className:"mt-2 text-xs text-faint",children:["Showing the worst ",me.length," of ",I.pagesAudited," audited pages."]}):null]})]})]})}const Ks=[{id:"map",label:"Map"},{id:"inventory",label:"Inventory"},{id:"technical",label:"Technical checks"}],Bx={map:"Explore how pages, site sections, and internal links fit together.",inventory:"Review discovered pages and the links that shape their visibility.",technical:"Prioritize audit findings and inspect the pages that need work."},Kx=200,Vx=100,sl=100,Qx=50,Hx=Jc,Wx=Xc,oi=new Intl.NumberFormat,Yx=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",year:"numeric"}),Xx={eligible:"positive",hidden:"caution",failed:"negative",unchecked:"neutral"};function nl(t){if(!t)return"Date unavailable";const s=new Date(t);return Number.isNaN(s.getTime())?"Date unavailable":Yx.format(s)}function Jx(t){return t.replaceAll("_"," ").replaceAll("-"," ").replace(/\b\w/g,s=>s.toUpperCase())}function al(t){const s=fa(t);return{label:ua(s),tone:Xx[s]}}function il(t){if(t==null)return"Not scored";const s=t<=1?t*100:t;return`${Math.round(s)}%`}function Zx(t){return t.auditScore==null?"Not checked":`${Math.round(t.auditScore)}/100`}function ot(t){return t==null?"Not available":oi.format(t)}function eg(t,s){if(!t||!s)return null;try{const n=new URL(t).host,a=new URL(s).host;return n!==a?{requested:n,effective:a}:null}catch{return null}}function tg(t){return t==="completed"?"positive":t==="partial"||t==="queued"||t==="running"?"caution":t==="failed"||t==="cancelled"?"negative":"neutral"}function sg(t){return`${nl(t.finishedAt??t.startedAt??t.createdAt)} · ${Jx(t.status)}`}function ng(t){return t?t.includes("page")?"Stopped at the configured page limit. The map contains fetched pages only.":t.includes("edge")?"Stopped at the configured internal-link limit. Some connections are omitted.":t.includes("depth")?"Stopped at the configured crawl depth. Deeper pages were not checked.":"The scan stopped before all discovered pages were checked.":"The scan stopped before all discovered pages were checked."}function ag(t,s){return t==="disabled"?{label:"Check off",tone:"neutral"}:t==="complete"?{label:`${oi.format(s??0)} found`,tone:s?"negative":"positive"}:t==="partial"?{label:`${oi.format(s??0)} found, partial`,tone:"caution"}:{label:"Unavailable",tone:"neutral"}}function ig({page:t}){return e.jsxs("dl",{className:"grid grid-cols-2 divide-x divide-y divide-default rounded-lg border border-default sm:grid-cols-4 sm:divide-y-0",children:[e.jsxs("div",{className:"px-4 py-3",children:[e.jsx("dt",{className:"text-xs text-muted",children:"Crawl depth"}),e.jsx("dd",{className:"mt-1 font-mono text-sm font-medium text-heading",children:t.depth??"Not reached"})]}),e.jsxs("div",{className:"px-4 py-3",children:[e.jsx("dt",{className:"text-xs text-muted",children:"Links in"}),e.jsx("dd",{className:"mt-1 font-mono text-sm font-medium text-heading",children:ot(t.inboundUniqueEdges)})]}),e.jsxs("div",{className:"px-4 py-3",children:[e.jsx("dt",{className:"text-xs text-muted",children:"Links out"}),e.jsx("dd",{className:"mt-1 font-mono text-sm font-medium text-heading",children:ot(t.outboundUniqueEdges)})]}),e.jsxs("div",{className:"px-4 py-3",children:[e.jsx("dt",{className:"text-xs text-muted",children:"Internal-link importance"}),e.jsx("dd",{className:"mt-1 font-mono text-sm font-medium text-heading",children:il(t.linkScoreNormalized)})]})]})}function Ar({direction:t,edges:s,truncated:n}){const a=t==="inbound"?"Links in":"Links out";return e.jsxs("section",{className:"min-w-0","aria-labelledby":`site-health-${t}-heading`,children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("h4",{id:`site-health-${t}-heading`,className:"text-sm font-medium text-heading",children:[a," (",ot(s.length),")"]}),n&&e.jsxs("span",{className:"text-xs text-muted",children:["First ",sl]})]}),s.length===0?e.jsxs("p",{className:"rounded-lg border border-subtle bg-surface-subtle px-3 py-4 text-sm text-secondary",children:["No ",t," internal links were observed."]}):e.jsx("div",{className:"evidence-table-wrap max-h-64 overflow-auto",children:e.jsxs("table",{className:"evidence-table min-w-[420px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Page"}),e.jsx("th",{scope:"col",children:"Anchor text"}),e.jsx("th",{scope:"col",children:"Uses"})]})}),e.jsx("tbody",{children:s.map(i=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-64 truncate font-mono",title:t==="inbound"?i.sourceUrl:i.targetUrl,children:t==="inbound"?i.sourceUrl:i.targetUrl}),e.jsx("td",{className:"max-w-52 truncate",title:i.anchors.join(", ")||void 0,children:i.anchors.join(", ")||"No anchor text"}),e.jsx("td",{className:"font-mono",children:ot(i.occurrences)})]},i.edgeKey))})]})})]})}function $r({page:t,isLoading:s,error:n,inbound:a,outbound:i,inboundTruncated:r,outboundTruncated:o,audit:l,auditLoading:c,auditError:u,onRetryAudit:m}){if(!t)return e.jsxs("section",{className:"border-t border-default pt-5","aria-label":"Selected page details",children:[e.jsx("h3",{className:"text-base font-medium text-heading",children:"Page links"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Select a page to inspect its internal links and crawl signals."})]});const h=al(t);return e.jsxs("section",{className:"border-t border-default pt-5","aria-labelledby":"site-health-page-inspector-title",children:[e.jsxs("div",{className:"flex flex-col justify-between gap-3 sm:flex-row sm:items-start",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("h3",{id:"site-health-page-inspector-title",className:"break-words font-mono text-base font-semibold text-heading",children:t.path}),e.jsx(oe,{tone:h.tone,children:h.label})]}),e.jsx("p",{className:"mt-1 break-all text-sm text-secondary",children:t.url})]}),e.jsx(L,{asChild:!0,variant:"secondary",size:"sm",children:e.jsxs("a",{href:t.url,target:"_blank",rel:"noreferrer",children:["Open page ",e.jsx(bo,{className:"size-3.5","aria-hidden":"true"})]})})]}),e.jsx("div",{className:"mt-4",children:e.jsx(Tx,{audit:l,isLoading:c,error:u,onRetry:m})}),e.jsxs("section",{className:"mt-5 border-t border-default pt-5","aria-labelledby":"site-health-page-links-heading",children:[e.jsx("h3",{id:"site-health-page-links-heading",className:"text-base font-semibold text-heading",children:"Internal links"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Observed links to and from this page in the selected scan."}),e.jsx("div",{className:"mt-4",children:e.jsx(ig,{page:t})}),e.jsx("div",{className:"mt-5",children:s?e.jsxs("div",{className:"flex items-center gap-2 py-6 text-sm text-secondary",children:[e.jsx(It,{className:"size-4 animate-spin","aria-hidden":"true"}),"Loading page links..."]}):n?e.jsx("p",{className:"rounded-lg border border-negative bg-negative-soft px-4 py-3 text-sm text-negative",role:"alert",children:"Page links could not be loaded."}):e.jsxs("div",{className:"grid gap-5 lg:grid-cols-2",children:[e.jsx(Ar,{direction:"inbound",edges:a,truncated:r}),e.jsx(Ar,{direction:"outbound",edges:i,truncated:o})]})})]})]})}function rg({pages:t,total:s,selectedNodeKey:n,onSelect:a,hasNextPage:i,isFetchingNextPage:r,onLoadMore:o}){const[l,c]=d.useState(""),u=l.trim().toLowerCase(),m=d.useMemo(()=>u?t.filter(x=>`${x.path} ${x.url}`.toLowerCase().includes(u)):t,[u,t]),h=u.length>0&&(i||t.length<s);return e.jsxs("section",{"aria-labelledby":"site-health-inventory-heading",children:[e.jsxs("div",{className:"mb-3 flex flex-col justify-between gap-3 sm:flex-row sm:items-end",children:[e.jsxs("div",{children:[e.jsx("h2",{id:"site-health-inventory-heading",className:"text-base font-semibold text-heading",children:"Page inventory"}),e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:["Loaded ",ot(t.length)," of ",ot(s)," discovered pages."]})]}),e.jsxs("label",{className:"relative block w-full sm:w-72",children:[e.jsx("span",{className:"sr-only",children:"Search loaded pages"}),e.jsx(pi,{className:"pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted","aria-hidden":"true"}),e.jsx("input",{type:"search",value:l,onChange:x=>c(x.target.value),placeholder:"Search loaded pages",className:"h-9 w-full rounded-md border border-base bg-bg pl-9 pr-3 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-600"})]})]}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table min-w-[940px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Page"}),e.jsx("th",{scope:"col",children:"Status"}),e.jsx("th",{scope:"col",children:"Technically eligible"}),e.jsx("th",{scope:"col",children:"Crawl depth"}),e.jsx("th",{scope:"col",children:"Links in"}),e.jsx("th",{scope:"col",children:"Links out"}),e.jsx("th",{scope:"col",children:"Internal-link importance"}),e.jsx("th",{scope:"col",children:"Technical score"})]})}),e.jsx("tbody",{children:m.map(x=>{const N=al(x);return e.jsxs("tr",{className:n===x.nodeKey?"bg-surface-active":void 0,children:[e.jsx("td",{className:"max-w-80",children:e.jsx("button",{type:"button",onClick:()=>a(x.nodeKey),className:"block max-w-full truncate rounded-sm font-mono text-sm font-medium text-link outline-none focus-visible:ring-2 focus-visible:ring-mono-400",title:x.url,children:x.path})}),e.jsx("td",{children:e.jsx(oe,{tone:N.tone,children:N.label})}),e.jsx("td",{children:x.inventoryEligible?"Yes":"No"}),e.jsx("td",{className:"font-mono",children:x.depth??"Not reached"}),e.jsx("td",{className:"font-mono",children:ot(x.inboundUniqueEdges)}),e.jsx("td",{className:"font-mono",children:ot(x.outboundUniqueEdges)}),e.jsx("td",{className:"font-mono",children:il(x.linkScoreNormalized)}),e.jsx("td",{className:"font-mono",children:Zx(x)})]},x.nodeKey)})})]})}),m.length===0&&e.jsx("p",{className:"border-x border-b border-default px-4 py-8 text-center text-sm text-secondary",children:u.length===0?"No pages are available.":h?`No matches in the ${ot(t.length)} loaded pages. Load more pages to continue searching.`:"No pages match this search."}),i&&e.jsx("div",{className:"flex justify-center border-x border-b border-default px-4 py-3",children:e.jsxs(L,{variant:"secondary",size:"sm",disabled:r,onClick:o,children:[r&&e.jsx(It,{className:"size-4 animate-spin","aria-hidden":"true"}),r?"Loading more pages":"Load more pages"]})})]})}function og({projectName:t,runId:s,section:n,onSelect:a}){const[i,r]=d.useState(!1),l=n.pageCount-(n.hasPage?1:0)>0;return e.jsxs("li",{children:[e.jsxs("div",{className:"flex min-h-11 items-center gap-1 px-2 py-1",children:[l?e.jsx("button",{type:"button","aria-label":`${i?"Collapse":"Expand"} ${n.path}`,"aria-expanded":i,onClick:()=>r(c=>!c),className:"flex size-8 shrink-0 items-center justify-center rounded-sm text-muted outline-none hover:bg-surface-hover hover:text-heading focus-visible:ring-2 focus-visible:ring-mono-400",children:i?e.jsx(tn,{className:"size-3.5","aria-hidden":"true"}):e.jsx(qn,{className:"size-3.5","aria-hidden":"true"})}):e.jsx("span",{className:"block size-8 shrink-0","aria-hidden":"true"}),e.jsx("button",{type:"button",onClick:()=>a(n.path),className:"min-w-0 flex-1 break-all rounded-sm py-2 text-left font-mono text-sm text-heading outline-none hover:text-link focus-visible:ring-2 focus-visible:ring-mono-400",children:n.path}),e.jsx("span",{className:"shrink-0 px-2 font-mono text-xs text-muted",children:ot(n.pageCount)})]}),i&&e.jsx("div",{className:"ml-6 border-l border-default pl-1",children:e.jsx(rl,{projectName:t,runId:s,parentPath:n.path,onSelect:a})})]})}function rl({projectName:t,runId:s,parentPath:n,onSelect:a}){const i={client:H,path:{name:t},query:{runId:s,parentPath:n,limit:Vx}},r=ui({...Zc(i),initialPageParam:i,getNextPageParam:l=>l.nextCursor?{path:i.path,query:{...i.query,cursor:l.nextCursor}}:void 0}),o=r.data?.pages.flatMap(l=>l.children)??[];return r.isLoading?e.jsxs("div",{className:"flex items-center gap-2 px-3 py-4 text-sm text-secondary",role:"status",children:[e.jsx(It,{className:"size-4 animate-spin","aria-hidden":"true"})," Loading sections..."]}):r.error?e.jsx("p",{className:"px-3 py-4 text-sm text-negative",role:"alert",children:"Site sections could not be loaded."}):o.length===0?e.jsx("p",{className:"px-3 py-4 text-sm text-secondary",children:"No nested sections were found."}):e.jsxs(e.Fragment,{children:[e.jsx("ul",{className:"divide-y divide-default",children:o.map(l=>e.jsx(og,{projectName:t,runId:s,section:l,onSelect:a},l.path))}),r.hasNextPage&&e.jsx("div",{className:"px-3 py-2",children:e.jsx(L,{variant:"ghost",size:"sm",disabled:r.isFetchingNextPage,onClick:()=>{r.fetchNextPage()},children:r.isFetchingNextPage?"Loading more sections":"Load more sections"})})]})}function lg(){return e.jsx("div",{role:"status",className:"flex min-h-[420px] items-center justify-center rounded-lg border border-default bg-surface-inset px-6 text-center lg:min-h-[520px]",children:e.jsxs("div",{className:"max-w-sm",children:[e.jsx(It,{className:"mx-auto size-5 animate-spin text-muted","aria-hidden":"true"}),e.jsx("p",{className:"mt-3 text-sm font-medium text-heading",children:"Preparing the interactive site map"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Page and link data is ready for the graph renderer."})]})})}function cg({projectName:t,projectId:s}){const[n,a]=d.useState("map"),i=d.useRef([]),[r,o]=d.useState(null),[l,c]=d.useState(null),[u,m]=d.useState(!1),h=ie(),x=uo(),f=De({...mi({client:H,path:{name:t},query:{kind:ws["site-audit"],limit:20}}),refetchOnWindowFocus:"always",refetchInterval:M=>M.state.data?.some(de=>de.status==="queued"||de.status==="running")?3e3:15e3}).data??[],w=f.find(M=>M.status==="queued"||M.status==="running"),b=f.filter(M=>M.status==="completed"||M.status==="partial").at(-1),A=r??b?.id??null,T=De({...Kc({client:H,path:{name:t},...A?{query:{runId:A}}:{}}),refetchInterval:!r&&w?3e3:!1}),P=T.data,j=A??P?.runId??null,p=!!(j&&P?.hasCrawlData&&P.detailsAvailable),y=j?{runId:j}:{},v=De({...Vc({client:H,path:{name:t},query:{...y,maxNodes:Hx,maxEdges:Wx}}),enabled:p}),D={client:H,path:{name:t},query:{...y,limit:Kx,sort:"path"}},q=ui({...Qc(D),enabled:p,initialPageParam:D,getNextPageParam:M=>M.nextCursor?{path:D.path,query:{...D.query,cursor:M.nextCursor}}:void 0}),S=p&&(P?.deadLinks.state==="complete"||P?.deadLinks.state==="partial"),k=De({...Hc({client:H,path:{name:t},query:{...y,limit:Qx}}),enabled:S}),F=v.data?.nodes??[],C=v.data?.layout.state==="ready"?v.data.totalEdges:null,I=d.useMemo(()=>q.data?.pages.flatMap(M=>M.pages)??[],[q.data]),me=q.data?.pages[0]?.total??I.length,pe=d.useMemo(()=>F.find(M=>M.nodeKey===l)??I.find(M=>M.nodeKey===l)??null,[F,I,l]),J=pe?.nodeKey??null,ne=De({...Wc({client:H,path:{name:t},query:{...y,nodeKey:J??void 0,limit:sl}}),enabled:p&&!!J}),Z=De({...Yc({client:H,path:{name:t},query:{...y,nodeKey:J??void 0}}),enabled:p&&!!J}),Q=d.useMemo(()=>[...f].filter(M=>M.status==="completed"||M.status==="partial").sort((M,de)=>de.createdAt.localeCompare(M.createdAt)),[f]),V=d.useMemo(()=>f.length===0?null:[...f].sort((M,de)=>de.createdAt.localeCompare(M.createdAt))[0].status,[f]),$=j?f.find(M=>M.id===j):void 0,te=!r&&w?w.status:P?.runStatus??$?.status??null,ce=te==="running"?"Scan running":te==="queued"?"Scan queued":te==="partial"?"Partial scan":te==="completed"?"Complete":te==="failed"?"Scan failed":"No scan",re=k.data,Y=ag(re?.state??P?.deadLinks.state??"unavailable",re&&"found"in re?re.found:P?.deadLinks&&"found"in P.deadLinks?P.deadLinks.found:void 0),fe=eg(P?.requestedRootUrl??null,P?.rootUrl??null),U=x.isPending||!!w,be=M=>{o(M||null),c(null)},Ce=()=>x.mutate({projectName:t,projectId:s,body:{checkDeadLinks:u}}),G=M=>{const de=F.find(ke=>ke.path===M||ke.path.startsWith(`${M}/`));de&&c(de.nodeKey)},Ee=M=>a(M),Re=(M,de)=>{let ke=null;M.key==="ArrowRight"||M.key==="ArrowDown"?ke=(de+1)%Ks.length:M.key==="ArrowLeft"||M.key==="ArrowUp"?ke=(de-1+Ks.length)%Ks.length:M.key==="Home"?ke=0:M.key==="End"&&(ke=Ks.length-1),ke!=null&&(M.preventDefault(),Ee(Ks[ke].id),i.current[ke]?.focus())};return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("header",{className:"flex flex-col justify-between gap-4 lg:flex-row lg:items-start",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("h2",{className:"text-xl font-semibold tracking-tight text-heading",children:"Site Health"}),e.jsx(oe,{tone:tg(te),children:ce}),$&&e.jsx("span",{className:"text-xs text-muted",children:nl($.finishedAt??$.startedAt)})]}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:Bx[n]})]}),e.jsxs("div",{className:"flex flex-wrap items-start gap-2",children:[e.jsxs("label",{className:"grid gap-1 text-xs text-muted",children:["Scan history",e.jsxs("select",{"aria-label":"View a Site Health scan",value:r??"",onChange:M=>be(M.target.value),className:"h-9 min-w-48 rounded-md border border-base bg-bg px-3 text-sm text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-600",children:[e.jsx("option",{value:"",children:"Latest scan"}),Q.map(M=>e.jsx("option",{value:M.id,children:sg(M)},M.id))]})]}),!h&&e.jsxs("div",{className:"flex items-end gap-2 pt-5",children:[e.jsxs("details",{className:"group relative",children:[e.jsxs("summary",{className:"flex h-9 cursor-pointer list-none items-center gap-2 rounded-md border border-base bg-bg px-3 text-sm font-medium text-heading outline-none hover:bg-bg-elevated focus-visible:ring-2 focus-visible:ring-mono-400",children:[e.jsx(Tu,{className:"size-4","aria-hidden":"true"}),"Scan settings"]}),e.jsx("div",{className:"absolute right-0 z-20 mt-2 w-72 rounded-lg border border-strong bg-bg-elevated p-4 shadow-[0_12px_32px_var(--color-shadow-panel)]",children:e.jsxs("label",{className:"flex cursor-pointer items-start gap-3 text-sm text-heading",children:[e.jsx("input",{type:"checkbox","aria-label":"Check dead links",checked:u,disabled:U,onChange:M=>m(M.target.checked),className:"mt-0.5 size-4 rounded border-base accent-mono-200 focus:ring-2 focus:ring-mono-400"}),e.jsxs("span",{children:[e.jsx("span",{className:"font-medium",children:"Check dead links"}),e.jsx("span",{className:"mt-1 block text-sm text-secondary",children:"Adds dead-link analysis to this scan."})]})]})})]}),e.jsxs(nt,{onClick:Ce,disabled:U,children:[U?e.jsx(It,{className:"size-4 animate-spin","aria-hidden":"true"}):e.jsx(Ms,{className:"size-4","aria-hidden":"true"}),w?.status==="running"?"Scan running":w?.status==="queued"?"Scan queued":"Run scan"]})]})]})]}),P?.hasCrawlData&&n!=="technical"&&e.jsxs("div",{className:"grid grid-cols-2 divide-x divide-y divide-default rounded-lg border border-default bg-surface-subtle sm:grid-cols-4 sm:divide-y-0",children:[e.jsxs("div",{className:"px-4 py-3",children:[e.jsx("div",{className:"text-xs text-muted",children:"Pages found"}),e.jsx("div",{className:"mt-1 font-mono text-xl font-semibold tabular-nums text-heading",children:ot(P.counts.pagesDiscovered)})]}),e.jsxs("div",{className:"px-4 py-3",children:[e.jsx("div",{className:"text-xs text-muted",children:"Pages checked"}),e.jsx("div",{className:"mt-1 font-mono text-xl font-semibold tabular-nums text-heading",children:ot(P.counts.pagesFetched)})]}),e.jsxs("div",{className:"px-4 py-3",children:[e.jsx("div",{className:"text-xs text-muted",children:"Technically eligible"}),e.jsx("div",{className:"mt-1 font-mono text-xl font-semibold tabular-nums text-heading",children:ot(P.counts.pagesEligible)})]}),e.jsxs("div",{className:"px-4 py-3",children:[e.jsx("div",{className:"text-xs text-muted",children:"Internal links"}),e.jsx("div",{className:"mt-1 font-mono text-xl font-semibold tabular-nums text-heading",children:ot(C)})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 border-b border-default",children:[e.jsx("div",{role:"tablist","aria-label":"Site Health views","aria-orientation":"horizontal",className:"flex min-w-0 gap-5",children:Ks.map((M,de)=>e.jsx("button",{type:"button",role:"tab",id:`site-health-${M.id}-tab`,"aria-selected":n===M.id,"aria-controls":`site-health-${M.id}-panel`,tabIndex:n===M.id?0:-1,ref:ke=>{i.current[de]=ke},onClick:()=>Ee(M.id),onKeyDown:ke=>Re(ke,de),className:`min-h-11 border-b-2 px-0.5 text-sm font-medium outline-none transition-colors focus-visible:ring-2 focus-visible:ring-mono-400 ${n===M.id?"border-strong text-heading":"border-transparent text-secondary hover:border-base hover:text-primary"}`,children:M.label},M.id))}),P?.hasCrawlData&&n!=="technical"&&e.jsxs("div",{className:"flex items-center gap-2 pb-2",children:[e.jsx("span",{className:"text-xs text-muted",children:"Dead-link check"}),e.jsx(oe,{tone:Y.tone,children:Y.label})]})]}),!r&&w&&e.jsx("div",{className:"rounded-lg border border-caution bg-caution-soft px-4 py-3 text-sm text-caution",role:"status",children:"The scan is running. The latest completed results remain available until it finishes."}),fe&&e.jsxs("div",{className:"rounded-lg border border-base bg-surface-subtle px-4 py-3 text-sm text-secondary",role:"status",children:[e.jsx("span",{className:"font-medium text-heading",children:"Site address changed during this scan."})," ","The scan started at ",e.jsx("span",{className:"font-mono text-primary",children:fe.requested})," and continued at"," ",e.jsx("span",{className:"font-mono text-primary",children:fe.effective}),". The map and inventory use the new address."]}),P?.hasCrawlData&&!P.complete&&e.jsx("div",{className:"rounded-lg border border-caution bg-caution-soft px-4 py-3 text-sm text-caution",role:"status",children:ng(P.termination)}),!w&&V==="failed"&&!r&&e.jsxs("div",{className:"flex gap-3 rounded-lg border border-negative bg-negative-soft px-4 py-3 text-sm text-negative",role:"alert",children:[e.jsx(Xa,{className:"mt-0.5 size-4 shrink-0","aria-hidden":"true"}),e.jsx("span",{children:"The latest scan failed. The previous completed results remain available."})]}),n==="technical"?e.jsx("div",{id:"site-health-technical-panel",role:"tabpanel","aria-labelledby":"site-health-technical-tab",className:"min-w-0",children:e.jsx(zx,{projectName:t,projectId:s,runId:j,integrated:!0})}):T.isLoading?e.jsxs("div",{className:"flex min-h-72 items-center justify-center gap-2 text-sm text-secondary",role:"status",children:[e.jsx(It,{className:"size-4 animate-spin","aria-hidden":"true"}),"Loading site health..."]}):T.error?e.jsxs("section",{className:"rounded-lg border border-negative bg-negative-soft px-5 py-6",role:"alert",children:[e.jsx("h2",{className:"font-semibold text-negative",children:"Site Health could not load"}),e.jsx("p",{className:"mt-1 text-sm text-negative",children:"Try loading the crawl again."}),e.jsx(L,{variant:"secondary",size:"sm",className:"mt-4",onClick:()=>{T.refetch()},children:"Try again"})]}):P?.hasCrawlData?P.detailsAvailable?n==="inventory"?e.jsxs("div",{id:"site-health-inventory-panel",role:"tabpanel","aria-labelledby":"site-health-inventory-tab",className:"space-y-5",children:[q.isLoading?e.jsxs("div",{className:"flex min-h-56 items-center justify-center gap-2 text-sm text-secondary",role:"status",children:[e.jsx(It,{className:"size-4 animate-spin","aria-hidden":"true"}),"Loading page inventory..."]}):q.error?e.jsx("p",{className:"rounded-lg border border-negative bg-negative-soft px-4 py-3 text-sm text-negative",role:"alert",children:"The page inventory could not be loaded."}):e.jsx(rg,{pages:I,total:me,selectedNodeKey:J,onSelect:c,hasNextPage:!!q.hasNextPage,isFetchingNextPage:q.isFetchingNextPage,onLoadMore:()=>{q.fetchNextPage()}}),e.jsx($r,{page:pe,isLoading:ne.isLoading&&!!pe,error:ne.error,inbound:ne.data?.inbound??[],outbound:ne.data?.outbound??[],inboundTruncated:ne.data?.inboundTruncated??!1,outboundTruncated:ne.data?.outboundTruncated??!1,audit:Z.data,auditLoading:Z.isLoading&&!!pe,auditError:Z.error,onRetryAudit:()=>{Z.refetch()}})]}):e.jsxs("div",{id:"site-health-map-panel",role:"tabpanel","aria-labelledby":"site-health-map-tab",className:"space-y-5",children:[e.jsxs("section",{"aria-labelledby":"site-map-heading",children:[e.jsxs("div",{className:"mb-3 flex flex-col justify-between gap-2 sm:flex-row sm:items-end",children:[e.jsxs("div",{children:[e.jsx("h2",{id:"site-map-heading",className:"text-base font-semibold text-heading",children:"Site map"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Scroll to zoom, drag to move, and select a page to inspect its technical findings and links."})]}),v.data?.sampled&&e.jsxs("span",{className:"text-xs text-muted",children:["Showing ",ot(v.data.nodes.length)," of ",ot(v.data.totalNodes)," pages"," · ",ot(v.data.edges.length)," of ",ot(v.data.totalEdges)," links"]})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-[minmax(0,1fr)_18rem]",children:[v.isLoading?e.jsx(lg,{}):v.error?e.jsx("div",{className:"flex min-h-[420px] items-center justify-center rounded-lg border border-negative bg-negative-soft px-6 text-center text-sm text-negative lg:min-h-[520px]",role:"alert",children:"The interactive map could not be loaded."}):e.jsx(Lx,{nodes:v.data?.nodes??[],edges:v.data?.edges??[],layoutState:v.data?.layout.state??"unavailable",layoutUnavailableReason:v.data?.layout.state==="unavailable"?v.data.layout.reason:null,selectedNodeKey:J,onSelectNode:M=>c(M.nodeKey),ariaLabel:`Interactive site map showing ${ot(v.data?.nodes.length??0)} pages and ${ot(v.data?.edges.length??0)} internal links`}),e.jsxs("aside",{className:"rounded-lg border border-default bg-surface-subtle","aria-labelledby":"site-sections-heading",children:[e.jsxs("div",{className:"border-b border-default px-4 py-3",children:[e.jsx("h3",{id:"site-sections-heading",className:"text-sm font-semibold text-heading",children:"Site sections"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"Top-level folders in this scan"})]}),e.jsx("div",{className:"max-h-[468px] overflow-auto",children:j&&e.jsx(rl,{projectName:t,runId:j,parentPath:"/",onSelect:G})})]})]})]}),e.jsx($r,{page:pe,isLoading:ne.isLoading&&!!pe,error:ne.error,inbound:ne.data?.inbound??[],outbound:ne.data?.outbound??[],inboundTruncated:ne.data?.inboundTruncated??!1,outboundTruncated:ne.data?.outboundTruncated??!1,audit:Z.data,auditLoading:Z.isLoading&&!!pe,auditError:Z.error,onRetryAudit:()=>{Z.refetch()}})]}):e.jsxs("section",{className:"rounded-lg border border-caution bg-caution-soft px-5 py-6",children:[e.jsx("h2",{className:"font-semibold text-caution",children:"Page details unavailable"}),e.jsx("p",{className:"mt-1 text-sm text-caution",children:"Summary metrics are preserved for this scan, but its page graph cannot be opened."})]}):e.jsxs("section",{className:"rounded-lg border border-default bg-surface-subtle px-5 py-8 text-center",children:[e.jsx("h2",{className:"text-base font-semibold text-heading",children:"Full-site map not available"}),e.jsx("p",{className:"mx-auto mt-2 max-w-xl text-sm text-secondary",children:P?.legacyAuditAvailable?"Existing technical checks are preserved. Run a new scan to build the page and internal-link map.":h?"A full-site scan has not been run for this project.":"Run a scan to discover pages, site sections, and internal links."}),P?.legacyAuditAvailable&&e.jsx(L,{variant:"secondary",size:"sm",className:"mt-4",onClick:()=>a("technical"),children:"View technical checks"})]})]})}function Pr(t){return`${(t*100).toFixed(1)}%`}function dg({projectName:t}){const[s,n]=d.useState("changes"),[a,i]=d.useState(null),[r,o]=d.useState(null),l=De({...ed({client:H,path:{name:t},query:{limit:30}}),enabled:s==="health"}),c=De({...mi({client:H,path:{name:t},query:{kind:"answer-visibility",limit:100}}),enabled:s==="compare"}),u=(c.data??[]).filter(b=>(b.status==="completed"||b.status==="partial")&&b.trigger!=="probe").reverse(),m=r??u[0]?.id??"",h=a??u.find(b=>b.id!==m)?.id??"",x=!!(h&&m&&h!==m),N=De({...td({client:H,path:{name:t},query:{run1:h,run2:m}}),enabled:s==="compare"&&x}),f=l.data??[],w=N.data?.diff.filter(b=>b.changed||b.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(([b,A])=>e.jsx("button",{type:"button",role:"tab","aria-selected":s===b,className:`filter-chip ${s===b?"filter-chip-active":""}`,onClick:()=>n(b),children:A},b))}),s==="changes"?e.jsx(zu,{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."})]}),l.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Loading coverage history…"}):null,!l.isLoading&&f.length===0?e.jsxs(ye,{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(b=>e.jsxs("tr",{children:[e.jsx("td",{className:"whitespace-nowrap tabular-nums text-secondary",children:new Date(b.createdAt).toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[b.mentionedPairs,"/",b.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:Pr(b.overallMentionRate)}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[b.citedPairs,"/",b.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:Pr(b.overallCitedRate)})]},b.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:h,onChange:b=>i(b.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:u.map(b=>e.jsx("option",{value:b.id,children:new Date(b.createdAt).toLocaleString()},b.id))})]}),e.jsxs("label",{className:"text-xs text-muted",children:["Later run",e.jsx("select",{value:m,onChange:b=>o(b.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:u.map(b=>e.jsx("option",{value:b.id,children:new Date(b.createdAt).toLocaleString()},b.id))})]})]}),c.isLoading||N.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Comparing runs…"}):null,!c.isLoading&&u.length<2?e.jsxs(ye,{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&&w.length===0?e.jsxs(ye,{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,w.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:w.map(b=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:b.query??"Archived query"}),e.jsx("td",{children:e.jsxs(oe,{tone:b.changed?"caution":"neutral",children:[b.run1State??"none"," → ",b.run2State??"none"]})}),e.jsx("td",{children:e.jsxs(oe,{tone:b.visibilityChanged?"caution":"neutral",children:[b.run1MentionState??"none"," → ",b.run2MentionState??"none"]})})]},b.queryId??b.query??"unknown"))})]})}):null]}):null]})}const qa=20,os=50,ug=50,hg=50;function Ci(t){return t==="viewer"}function Ai(t){return t?.status==="unavailable"}function ol(t,s,n){return n?t.includes(s)?[...t]:[...t,s]:t.filter(a=>a!==s)}function ll(t,s){const n=new Map(s.map(i=>[i.id,i.label])),a=t.map(i=>n.get(i)).filter(i=>!!i);return a.length===0?"Not applied":a.length>3?`${a.length} Properties`:a.join(", ")}function ia(t,s,n){if(t.kind==="all")return s.map(r=>r.id);if(t.kind==="specific")return s.filter(r=>t.propertyIds.includes(r.id)).map(r=>r.id);const a=new Set(t.groupIds),i=new Set(n.filter(r=>a.has(r.id)).flatMap(r=>r.propertyIds));return s.filter(r=>i.has(r.id)).map(r=>r.id)}function mg(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(i=>s.find(r=>r.id===i)?.name).filter(i=>!!i);return a.length===0?"selected groups":a.join(" + ")}function Fa(t,s){const n=new Set(s.map(i=>i.id)),a=t.propertyIds.filter(i=>n.has(i)).length;return`${t.name} · ${a===1?"1 Property":`${a} Properties`}`}function Rr(t){return t==="matched"?"positive":t==="duplicate"?"neutral":t==="ambiguous"||t==="proposed"||t==="excluded"?"caution":"negative"}function Lr(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 ra(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 li(t){return t.state==="missing"||t.source==="unavailable-tracked-query"||!t.source}function Ua(t){return li(t)?"Unavailable tracked query":t.text?.trim()||"Unavailable tracked query"}function ci({properties:t,selectedPropertyIds:s,onSelectedPropertyIdsChange:n,legend:a,showBulkActions:i=!0}){const[r,o]=d.useState(""),[l,c]=d.useState(!1),u=r.trim().toLocaleLowerCase(),m=u?t.filter(f=>f.label.toLocaleLowerCase().includes(u)):t,h=l?m:m.slice(0,ug),x=h.length<m.length;function N(){const f=new Set([...s,...h.map(w=>w.id)]);n(t.filter(w=>f.has(w.id)).map(w=>w.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:r,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"})]}),i?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(L,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:h.length===0,onClick:N,children:"Select all shown"}),e.jsx(L,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:s.length===0,onClick:()=>n([]),children:"Clear selection"})]}):null]}),m.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 ",h.length," of ",m.length," Properties"]}),e.jsx("div",{className:"mt-2 max-h-96 divide-y divide-default overflow-y-auto border-y border-default",children:h.map(f=>{const w=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:w,type:"checkbox",onChange:b=>n(ol(s,f.id,b.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)})}),x?e.jsx(L,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",onClick:()=>c(!0),children:"Show all Properties"}):null]})]})}function $i(){return e.jsxs("div",{className:"flex items-center gap-2 text-sm text-secondary",children:[e.jsx(oe,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]})}function Pi({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(oe,{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 pg({value:t}){const[s,n]=d.useState(0),[a,i]=d.useState(0),[r,o]=d.useState(null),l=t.preview,c=l?.counts.needsAttention??0,u=l?.rows.filter(v=>v.status==="matched")??[],m=l?.rows??[],h=m.filter(v=>v.status!=="matched"),x=Math.max(1,Math.ceil(m.length/os)),N=Math.min(s,x-1),f=m.slice(N*os,(N+1)*os),w=Math.max(1,Math.ceil(h.length/os)),b=Math.min(a,w-1),A=h.slice(b*os,(b+1)*os),T=t.csv.trim().length>0&&!t.isReviewing&&!t.isApplying,P=u.length>0&&!t.isApplying,j=l!==null&&r===l.previewChecksum,p=h.length>0&&b===w-1;d.useEffect(()=>{n(0),i(0),o(null)},[l?.previewChecksum]);async function y(v){if(v)try{t.onCsvChange(await v.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:v=>{y(v.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:v=>t.onCsvChange(v.currentTarget.value),placeholder:`property,group,url
|
|
9
|
+
${r.nodeKey}`.toLocaleLowerCase().includes(a):!0:!1).slice(0,i)}function jx(t,s,n,a){const r=!!(s&&t.hasNode(s))?s:null,o=n>Pn,l=new Set(r&&o?t.neighbors(r).filter(c=>c!==r).sort((c,u)=>{const m=t.getNodeAttributes(c),h=t.getNodeAttributes(u);return h.size-m.size||(m.depth??Number.MAX_SAFE_INTEGER)-(h.depth??Number.MAX_SAFE_INTEGER)||dn(m.path,h.path)||dn(c,u)}).slice(0,px):[]);return{nodeReducer:(c,u)=>r?c===r?{...u,size:u.size*1.35,forceLabel:!0,zIndex:3}:t.areNeighbors(c,r)?o?l.has(c)?{...u,forceLabel:!1}:{...u,forceLabel:!1,label:""}:u:{...u,color:a.dimmedNode,forceLabel:!1,label:"",zIndex:0}:o?u.depth===0||u.depth===1?{...u,forceLabel:!0}:{...u,forceLabel:!1,label:""}:u,edgeReducer:(c,u)=>{const[m,h]=t.extremities(c);return r&&(m===r||h===r)?{...u,color:a.edgeActive,size:Math.max(1.4,u.size),zIndex:2}:o?{...u,hidden:!0}:r?{...u,color:a.edgeDimmed,size:Math.min(.45,u.size),zIndex:0}:u}}}function Nx(t){return t==="layout-failed"?{heading:"Graph layout failed",detail:"This scan completed, but its graph layout could not be published. The page inventory remains available."}:{heading:"Graph layout unavailable",detail:"This scan does not have a published graph layout yet."}}class wx extends d.Component{state={failed:!1};static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(s){console.error("[SiteGraphSigma] WebGL renderer failed",s)}componentDidUpdate(s){this.state.failed&&s.resetToken!==this.props.resetToken&&this.setState({failed:!1})}render(){return this.state.failed?this.props.fallback:this.props.children}}const ta=220;function sa(t,s,n=`${s}s`){return`${t.toLocaleString()} ${t===1?s:n}`}function Sx(t,s,n){const i=window.getComputedStyle(t).getPropertyValue(s).trim();if(i&&!i.includes("var(")&&Sr(i))return i;const r=document.createElement("span");r.style.position="absolute",r.style.visibility="hidden",r.style.color=`var(${s})`,t.appendChild(r);const o=window.getComputedStyle(r).color.trim();return r.remove(),o&&!o.includes("var(")&&Sr(o)?o:n}function kx(t){const s=n=>{const a=ux[n];return Sx(t,a.property,a.fallback)};return{eligible:s("eligible"),hidden:s("hidden"),failed:s("failed"),unchecked:s("unchecked"),dimmedNode:s("dimmedNode"),edge:s("edge"),edgeDimmed:s("edgeDimmed"),edgeActive:s("edgeActive"),label:s("label"),background:s("background")}}function Cx(t,s,n,a,i,r){const o=Math.min(r,a/2,i/2);t.beginPath(),t.moveTo(s+o,n),t.lineTo(s+a-o,n),t.arcTo(s+a,n,s+a,n+o,o),t.lineTo(s+a,n+i-o),t.arcTo(s+a,n+i,s+a-o,n+i,o),t.lineTo(s+o,n+i),t.arcTo(s,n+i,s,n+i-o,o),t.lineTo(s,n+o),t.arcTo(s,n,s+o,n,o),t.closePath()}function Ax(t){return(s,n,a)=>{const i=typeof n.label=="string"?n.label:null,r=a.labelSize+10,o=n.x+n.size+7,l=n.y-r/2;if(s.save(),s.font=`${a.labelWeight} ${a.labelSize}px ${a.labelFont}`,s.fillStyle=t.background,s.strokeStyle=t.edgeActive,s.lineWidth=1.5,s.beginPath(),s.arc(n.x,n.y,n.size+3,0,Math.PI*2),s.fill(),s.stroke(),s.fillStyle=n.color,s.beginPath(),s.arc(n.x,n.y,n.size,0,Math.PI*2),s.fill(),i){const c=Math.ceil(s.measureText(i).width)+16;Cx(s,o,l,c,r,5),s.fillStyle=t.background,s.fill(),s.strokeStyle=t.edgeActive,s.lineWidth=1,s.stroke(),s.fillStyle=t.label,s.textBaseline="middle",s.fillText(i,o+8,n.y)}s.restore()}}function $x(){if(typeof document>"u")return!1;try{const t=document.createElement("canvas");return!!(t.getContext("webgl2")||t.getContext("webgl"))}catch{return!1}}function Px(){return e.jsx("div",{className:"flex h-full min-h-80 items-center justify-center px-6 text-center",children:e.jsxs("div",{className:"max-w-md",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"Interactive map unavailable"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"This browser could not start WebGL. The page inventory remains available for the complete crawl."})]})})}function Rx({reactSigma:t,graph:s,theme:n,selectedNodeKey:a,onSelectNodeKey:i,onHoverNode:r,onCameraReady:o}){const{useSigma:l,useRegisterEvents:c,useCamera:u}=t,m=l(),h=c(),{zoomIn:x,zoomOut:N,reset:f,gotoNode:w}=u(),[b,A]=d.useState(null),[T,P]=d.useState(()=>m.getCamera().getState().ratio>Pn),j=d.useRef(T),p=b??a;return d.useEffect(()=>(o({zoomIn:()=>x({duration:ta}),zoomOut:()=>N({duration:ta}),reset:()=>f({duration:ta}),gotoNode:y=>w(y,{duration:ta})}),()=>o(null)),[w,o,f,x,N]),d.useEffect(()=>{h({enterNode:({node:y,event:v})=>{A(y),r({nodeKey:y,left:Number.isFinite(v.x)?v.x+14:20,top:Number.isFinite(v.y)?v.y+14:20})},leaveNode:()=>{A(null),r(null)},clickNode:({node:y})=>i(y),clickStage:()=>r(null),updated:y=>{const v=y.ratio>Pn;j.current!==v&&(j.current=v,P(v))}})},[r,i,h]),d.useEffect(()=>{const y=jx(s,p,T?Pn+Number.EPSILON:Pn,n);m.setSetting("nodeReducer",y.nodeReducer),m.setSetting("edgeReducer",y.edgeReducer),m.refresh()},[p,s,T,m,n]),null}function Lx({nodes:t,edges:s,layoutState:n="ready",layoutUnavailableReason:a,selectedNodeKey:i,onSelectNode:r,ariaLabel:o,className:l}){const c=d.useRef(null),u=d.useRef(null),m=d.useRef(null),h=d.useId(),x=d.useId(),N=d.useId(),[f,w]=d.useState(null),[b,A]=d.useState(null),[T,P]=d.useState("checking"),[j,p]=d.useState(!1),[y,v]=d.useState(null),[D,q]=d.useState(null),[S,k]=d.useState(""),[F,C]=d.useState(!1),[I,me]=d.useState(0),[pe,J]=d.useState(""),ne=d.useRef(null),Z=d.useDeferredValue(S),Q=i===void 0?y:i,V=d.useMemo(()=>new Map(t.map(X=>[X.nodeKey,X])),[t]),$=Q?V.get(Q)??null:null,te=D?V.get(D.nodeKey)??null:null,ce=d.useMemo(()=>vx(t,Z),[Z,t]),re=t.some(X=>Number.isFinite(X.x)&&Number.isFinite(X.y)),Y=d.useMemo(()=>f?yx(t,s,f):null,[s,t,f]),fe=d.useMemo(()=>f?{allowInvalidContainer:!0,defaultNodeColor:f.unchecked,defaultEdgeColor:f.edge,defaultEdgeType:"line",enableCameraPanning:!0,enableCameraZooming:!0,enableCameraRotation:!1,enableEdgeEvents:!1,hideEdgesOnMove:!0,hideLabelsOnMove:!0,itemSizesReference:"screen",defaultDrawNodeHover:Ax(f),labelColor:{color:f.label},labelDensity:.2,labelFont:"Geist Sans, sans-serif",labelRenderedSizeThreshold:8,labelSize:13,labelWeight:"600",maxCameraRatio:12,minCameraRatio:.04,minEdgeThickness:.35,renderEdgeLabels:!1,renderLabels:!0,stagePadding:42,zIndex:!0}:null,[f]);d.useEffect(()=>{const X=c.current;if(!X)return;const Ne=()=>w(kx(X));if(Ne(),typeof MutationObserver>"u")return;const O=new MutationObserver(Ne);return O.observe(document.documentElement,{attributes:!0,attributeFilter:["class","data-theme","style"]}),()=>O.disconnect()},[]),d.useEffect(()=>{if(t.length===0||n==="unavailable"||!re){P("checking");return}P($x()?"ready":"unavailable")},[re,n,t.length]),d.useEffect(()=>{if(T!=="ready"){A(null);return}let X=!0;return Fc(()=>import("./react-sigma_core.esm.min-EzswMBkr.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13]),import.meta.url).then(Ne=>{X&&A(Ne)}).catch(()=>{X&&P("unavailable")}),()=>{X=!1}},[T]),d.useEffect(()=>{me(0)},[Z]);const U=d.useCallback(X=>{m.current=X,p(!!X)},[]),be=d.useCallback(X=>{q(X)},[]),Ce=d.useCallback((X,Ne)=>{const O=V.get(X);O&&(i===void 0&&v(X),r?.(O),Ne&&m.current?.gotoNode(X),J(`Focused ${O.path||"/"}`))},[V,r,i]),G=d.useCallback(X=>{Ce(X,!1)},[Ce]);d.useEffect(()=>{if(!j||!i||!V.has(i)){i||(ne.current=null);return}ne.current!==i&&(m.current?.gotoNode(i),ne.current=i)},[j,V,i]);const Ee=X=>{Ce(X.nodeKey,!0),k(X.path||X.url),C(!1)},Re=()=>{window.setTimeout(()=>{document.activeElement!==u.current&&C(!1)},0)},M=`Interactive site map showing ${sa(t.length,"page")} and ${sa(s.length,"internal link")}`,de=X=>`${x}-${X.replaceAll(/[^\w-]/g,"-")}`,ke=Nx(a);if(n==="unavailable")return e.jsx("section",{ref:c,role:"group","aria-label":o??M,className:vn("flex min-h-80 items-center justify-center rounded-lg border border-default bg-surface-inset px-6 text-center",l),children:e.jsxs("div",{className:"max-w-md",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:ke.heading}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:ke.detail})]})});if(t.length===0)return e.jsx("section",{ref:c,role:"group","aria-label":o??M,className:vn("flex min-h-80 items-center justify-center rounded-lg border border-default bg-surface-inset px-6 text-center",l),children:e.jsx("p",{className:"max-w-md text-sm text-secondary",children:"No page graph is available for this scan."})});if(!re)return e.jsx("section",{ref:c,role:"group","aria-label":o??M,className:vn("flex min-h-80 items-center justify-center rounded-lg border border-default bg-surface-inset px-6 text-center",l),children:e.jsxs("div",{className:"max-w-md",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:ke.heading}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:ke.detail})]})});const Oe=ce.at(I),Me=e.jsx(Px,{}),W=b?.SigmaContainer;return e.jsxs("section",{ref:c,role:"group","aria-label":o??M,"aria-describedby":N,className:vn("flex h-[clamp(460px,62vh,680px)] min-h-[460px] flex-col overflow-hidden rounded-lg border border-default bg-surface-inset",l),children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 border-b border-subtle bg-bg-elevated/70 px-3 py-2",children:[e.jsx("label",{htmlFor:h,className:"sr-only",children:"Focus a page in the site map"}),e.jsxs("div",{className:"relative min-w-56 max-w-lg flex-1",children:[e.jsx(pi,{className:"pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted","aria-hidden":"true"}),e.jsx("input",{id:h,ref:u,role:"combobox",type:"search",autoComplete:"off","aria-label":"Focus a page in the site map","aria-autocomplete":"list","aria-controls":x,"aria-expanded":F,"aria-activedescendant":F&&Oe?de(Oe.nodeKey):void 0,value:S,placeholder:$?`Focused: ${$.path||"/"}`:"Find a page",className:"h-10 w-full rounded-md border border-base bg-bg py-2 pl-9 pr-3 text-sm text-primary placeholder-mono-600 outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onFocus:()=>C(!0),onBlur:Re,onChange:X=>{k(X.target.value),C(!0)},onKeyDown:X=>{X.key==="ArrowDown"?(X.preventDefault(),C(!0),me(Ne=>Math.max(0,Math.min(ce.length-1,Ne+1)))):X.key==="ArrowUp"?(X.preventDefault(),me(Ne=>Math.max(0,Ne-1))):X.key==="Enter"&&F&&Oe?(X.preventDefault(),Ee(Oe)):X.key==="Escape"&&C(!1)}}),F&&e.jsxs("div",{className:"absolute left-0 right-0 top-[calc(100%+0.25rem)] z-30 overflow-hidden rounded-md border border-base bg-bg shadow-lg",children:[e.jsx("div",{id:x,role:"listbox","aria-label":"Matching pages",className:"max-h-72 overflow-auto py-1",children:ce.length>0?ce.map((X,Ne)=>{const O=fa(X);return e.jsxs("button",{id:de(X.nodeKey),type:"button",role:"option","aria-selected":Ne===I,tabIndex:-1,className:vn("flex min-h-11 w-full items-center justify-between gap-3 px-3 py-2 text-left text-sm outline-none",Ne===I?"bg-surface-active text-primary":"text-secondary hover:bg-surface-hover hover:text-primary"),onPointerDown:E=>E.preventDefault(),onMouseDown:E=>E.preventDefault(),onMouseEnter:()=>me(Ne),onClick:()=>Ee(X),children:[e.jsx("span",{className:"min-w-0 truncate font-mono",children:X.path||"/"}),e.jsxs("span",{className:"flex shrink-0 items-center gap-1.5 text-[13px] text-muted",children:[e.jsx("span",{className:"font-mono font-semibold",style:{color:`var(${Ws[O].property})`},"aria-hidden":"true",children:ri(O)}),e.jsx("span",{children:ua(O)})]})]},X.nodeKey)}):e.jsx("p",{className:"px-3 py-4 text-sm text-secondary",children:"No rendered pages match."})}),ce.length===50&&e.jsx("p",{className:"border-t border-subtle px-3 py-2 text-[13px] text-muted",children:"First 50 matches. Refine the search or use the full page inventory."})]})]}),e.jsxs("span",{className:"text-[13px] tabular-nums text-muted",children:[sa(t.length,"page")," · ",sa(s.length,"link")]})]}),e.jsx("div",{className:"relative min-h-0 flex-1 overflow-hidden",children:T==="unavailable"?Me:T==="checking"||!f||!Y||!fe||!b||!W?e.jsx("div",{className:"flex h-full min-h-80 items-center justify-center px-6 text-center",role:"status",children:e.jsx("p",{className:"text-sm text-secondary",children:"Preparing the interactive site map..."})}):e.jsxs(wx,{fallback:Me,resetToken:Y.graph,children:[e.jsx("div",{"aria-hidden":"true",className:"absolute inset-0",children:e.jsx(W,{graph:Y.graph,className:"relative size-full bg-bg [&_.sigma-container]:size-full",style:{width:"100%",height:"100%",background:f.background},settings:fe,children:e.jsx(Rx,{reactSigma:b,graph:Y.graph,theme:f,selectedNodeKey:Q,onSelectNodeKey:G,onHoverNode:be,onCameraReady:U})})}),e.jsxs("div",{className:"absolute right-3 top-3 z-20 flex flex-col overflow-hidden rounded-md border border-base bg-bg shadow-lg",children:[e.jsx(L,{type:"button",variant:"ghost",size:"icon",className:"rounded-none border-b border-subtle","aria-label":"Zoom in",disabled:!j,onClick:()=>m.current?.zoomIn(),children:e.jsx(Iu,{className:"size-4","aria-hidden":"true"})}),e.jsx(L,{type:"button",variant:"ghost",size:"icon",className:"rounded-none border-b border-subtle","aria-label":"Zoom out",disabled:!j,onClick:()=>m.current?.zoomOut(),children:e.jsx(fo,{className:"size-4","aria-hidden":"true"})}),e.jsx(L,{type:"button",variant:"ghost",size:"icon",className:"rounded-none","aria-label":"Fit site map",disabled:!j,onClick:()=>m.current?.reset(),children:e.jsx(Du,{className:"size-4","aria-hidden":"true"})})]}),te&&D&&e.jsxs("div",{role:"tooltip",className:"pointer-events-none absolute z-20 max-w-64 rounded-md border border-base bg-bg/95 px-3 py-2 shadow-lg",style:{left:D.left,top:D.top},children:[e.jsx("p",{className:"truncate font-mono text-[13px] font-medium text-heading",children:te.path||"/"}),e.jsxs("p",{className:"mt-1 text-[13px] text-secondary",children:[ua(fa(te))," · depth ",te.depth??"unknown"]}),te.auditScore!=null&&e.jsxs("p",{className:"mt-1 font-mono text-[13px] text-heading",children:["Technical score ",Math.round(te.auditScore),"/100"]})]})]})}),e.jsxs("div",{"aria-label":"Site map legend",className:"flex flex-wrap items-center gap-x-4 gap-y-2 border-t border-subtle bg-bg-elevated/50 px-3 py-2 text-[13px] text-secondary",children:[["eligible","hidden","failed","unchecked"].map(X=>e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"w-3 text-center font-mono text-[15px] font-semibold leading-none",style:{color:`var(${Ws[X].property})`},"aria-hidden":"true",children:ri(X)}),ua(X)]},X)),e.jsx("span",{className:"ml-auto",children:"Size shows internal-link importance"}),Y&&(Y.omittedNodes>0||Y.omittedEdges>0)&&e.jsx("span",{className:"text-caution",children:"Some records lacked valid layout data."})]}),e.jsx("p",{id:N,className:"sr-only",children:"The WebGL map supports pointer, wheel, and touch navigation. Use the page search to focus a rendered page. Use the full page inventory for an accessible list of every crawled page and its links."}),e.jsx("p",{role:"status","aria-live":"polite",className:"sr-only",children:pe})]})}function Ex(t){return t>=70?"positive":t>=40?"caution":"negative"}function Ix(t){return t>=70?"pass":t>=40?"partial":"fail"}function Dx(t){return t==="pass"?"positive":t==="partial"?"caution":"negative"}function Cr(t){return t==="pass"?"Pass":t==="partial"?"Partial":"Fail"}function Tx({audit:t,isLoading:s,error:n,onRetry:a}){return e.jsxs("section",{className:"border-t border-default pt-5","aria-labelledby":"site-health-page-audit-heading",children:[e.jsxs("div",{children:[e.jsx("h3",{id:"site-health-page-audit-heading",className:"text-base font-semibold text-heading",children:"Why this technical score"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Findings and fixes from this page in the selected scan."})]}),s?e.jsx("p",{className:"mt-4 text-sm text-secondary",role:"status",children:"Loading technical findings..."}):n?e.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-between gap-3 border-y border-negative bg-negative-soft px-4 py-3",role:"alert",children:[e.jsx("p",{className:"text-sm text-negative",children:"Technical findings could not be loaded."}),e.jsx(L,{type:"button",variant:"secondary",size:"sm",onClick:a,children:"Retry technical findings"})]}):t?t.state==="no-crawl"?e.jsx("p",{className:"mt-4 text-sm text-secondary",children:"No Site Health scan is available."}):t.state==="details-unavailable"?e.jsx("p",{className:"mt-4 text-sm text-secondary",children:"This scan preserved its summary, but not page-level audit evidence."}):t.state==="not-found"?e.jsx("p",{className:"mt-4 text-sm text-secondary",children:"This page is not present in the selected scan."}):t.state==="not-audited"?e.jsx("p",{className:"mt-4 text-sm text-secondary",children:"This page was discovered, but it was not technically audited."}):e.jsx(Mx,{audit:t}):e.jsx("p",{className:"mt-4 text-sm text-secondary",children:"Technical findings are unavailable for this page."})]})}function Mx({audit:t}){const s=t.factors.filter(n=>n.applicable!==!1&&(n.status!=="pass"||n.findings.some(a=>a.type==="missing"||a.type==="timeout"||a.type==="unreachable")));return e.jsxs("div",{className:"mt-4",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline gap-2",children:[e.jsxs("span",{"aria-label":`Technical score ${Math.round(t.auditScore)} out of 100`,className:"font-mono text-2xl font-semibold tabular-nums text-heading",children:[Math.round(t.auditScore),e.jsx("span",{className:"text-sm text-muted",children:"/100"})]}),e.jsx(oe,{tone:Ex(t.auditScore),children:Cr(Ix(t.auditScore))})]}),t.evidenceState==="scores-only"&&e.jsx("p",{className:"mt-3 border border-caution bg-caution-soft px-3 py-2 text-sm text-caution",children:"This older scan preserved factor scores, but not the original finding text or fixes."}),t.criticalDefects.length>0&&e.jsxs("section",{className:"mt-5","aria-labelledby":"site-health-critical-defects-heading",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("h4",{id:"site-health-critical-defects-heading",className:"text-sm font-semibold text-heading",children:"Score-independent defects"}),e.jsx(oe,{tone:t.criticalDefects.some(n=>n.severity==="critical")?"negative":"caution",children:t.criticalDefects.length}),e.jsx("span",{className:"text-xs text-muted",children:"Not included in the weighted score"})]}),e.jsx("ul",{className:"mt-2 divide-y divide-default border-y border-default",children:t.criticalDefects.map(n=>e.jsxs("li",{className:"py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:n.detail}),e.jsx(oe,{tone:n.severity==="critical"?"negative":"caution",children:n.severity==="critical"?"Critical":"Warning"})]}),e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:[e.jsx("span",{className:"font-medium text-heading",children:"Fix:"})," ",n.recommendation]})]},n.id))})]}),s.length>0?e.jsx("div",{className:"mt-5 divide-y divide-default border-y border-default",children:s.map((n,a)=>e.jsxs("details",{open:a===0,className:"group py-1",children:[e.jsxs("summary",{className:"flex min-h-12 cursor-pointer list-none items-center justify-between gap-3 rounded-sm px-1 py-2 outline-none marker:hidden focus-visible:ring-2 focus-visible:ring-mono-400 [&::-webkit-details-marker]:hidden",children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-2 text-sm font-medium text-heading",children:[e.jsx(qn,{className:"size-4 shrink-0 text-muted transition-transform group-open:rotate-90","aria-hidden":"true"}),n.name]}),e.jsxs("span",{className:"flex shrink-0 items-center gap-2",children:[e.jsxs("span",{className:"font-mono text-sm tabular-nums text-heading",children:[Math.round(n.score),"/100"]}),e.jsx(oe,{tone:Dx(n.status),children:Cr(n.status)})]})]}),e.jsxs("div",{className:"grid gap-4 px-1 pb-4 pt-1 md:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("h5",{className:"text-xs font-semibold uppercase tracking-wide text-muted",children:"Evidence"}),n.findings.length>0?e.jsx("ul",{className:"mt-2 space-y-1.5 text-sm text-secondary",children:n.findings.map((i,r)=>e.jsx("li",{children:i.message},`${i.code}:${r}`))}):e.jsx("p",{className:"mt-2 text-sm text-secondary",children:t.evidenceState==="scores-only"?"Finding text was not preserved for this factor.":"No finding text was emitted for this factor."})]}),e.jsxs("div",{children:[e.jsx("h5",{className:"text-xs font-semibold uppercase tracking-wide text-muted",children:"Recommended fix"}),n.recommendations.length>0?e.jsx("ol",{className:"mt-2 list-decimal space-y-1.5 pl-5 text-sm text-secondary marker:text-muted",children:n.recommendations.map(i=>e.jsx("li",{children:i},i))}):e.jsx("p",{className:"mt-2 text-sm text-secondary",children:t.evidenceState==="scores-only"?"No page-specific fix was preserved.":"No page-specific fix was emitted."}),e.jsxs("p",{className:"mt-3 text-xs text-muted",children:["Weight: ",n.weight,"% of the page score"]})]})]})]},n.id))}):t.criticalDefects.length===0&&t.evidenceState==="complete"?e.jsx("p",{className:"mt-4 border-y border-positive bg-positive-soft px-4 py-3 text-sm text-positive",children:"No technical findings need attention on this page."}):t.criticalDefects.length===0?e.jsx("p",{className:"mt-4 border-y border-default px-4 py-3 text-sm text-secondary",children:"No below-pass factor scores were preserved. Detailed finding evidence is unavailable."}):null]})}const _x=100,Oa=12,Gx=[];function Ox(t){return Co(t.url)}function na(t){return t>=70?"positive":t>=40?"caution":"negative"}function aa(t){return t>=70?"text-positive-400":t>=40?"text-caution-400":"text-negative-400"}function qx(t){return t==="pass"?"positive":t==="partial"?"caution":"negative"}function kn(t){return t>=70?"Pass":t>=40?"Partial":"Fail"}function Fx(t){return gi(ss(String(t)))}function Ux(t){return Ns(ss(String(t)))}function zx({projectName:t,projectId:s,runId:n,integrated:a=!1}){const[i,r]=d.useState(!1),[o,l]=d.useState(null),[c,u]=d.useState(null),m=n===void 0?c:n,[h,x]=d.useState(!1),N=d.useRef(null),f=De(Uc({client:H,path:{name:t},...m?{query:{runId:m}}:{}})),w=De({...zc({client:H,path:{name:t},query:{limit:30}}),enabled:!a}),b=De(Bc({client:H,path:{name:t},query:{limit:_x,sort:"score-asc",...m?{runId:m}:{}}})),A=De({...mi({client:H,path:{name:t},query:{kind:ws["site-audit"],limit:10}}),enabled:!a,refetchOnWindowFocus:"always",refetchInterval:G=>G.state.data?.some(Re=>Re.status==="queued"||Re.status==="running")?3e3:1e4}),T=uo(),P=d.useSyncExternalStore(io,ha,ha),j=Object.values(P.runs).find(G=>G.kind===ws["site-audit"]&&G.projectId===s),p=A.data??[],y=p.find(G=>G.status==="queued"||G.status==="running"),v=p.at(-1),D=T.isPending||!!j||!!y,q=T.isPending?"starting":y?.status??j?.lastAnnouncedStatus,S=d.useCallback(async()=>{const G=await Promise.all([f.refetch(),b.refetch(),...a?[]:[w.refetch()]]),Ee=G.find(Re=>Re.error);if(Ee?.error)throw Ee.error;return G[0]},[a,b.refetch,f.refetch,w.refetch]);d.useEffect(()=>{a||m||!v||v.status!=="completed"&&v.status!=="partial"||f.data?.runId===v.id||N.current===v.id||(N.current=v.id,S().catch(G=>{$e({title:"Technical AEO auto-refresh failed",detail:G instanceof Error?G.message:"Could not load the completed audit.",tone:"negative",dedupeKey:`technical-aeo:auto-refresh:${t}`,dedupeMode:"replace"})}))},[m,a,v?.id,v?.status,t,S,f.data?.runId]);const k=async()=>{x(!0);try{const G=await S();$e({title:"Technical AEO refreshed",detail:D?"The audit is still running. This view will refresh again when it finishes.":G.data?.hasData?`Latest score is ${G.data.aggregateScore}/100 from ${G.data.pagesAudited} audited page${G.data.pagesAudited===1?"":"s"}.`:"No audit data yet. Run an audit to crawl the sitemap.",tone:G.data?.hasData?"positive":"caution",dedupeKey:`technical-aeo:refresh:${t}`,dedupeMode:"replace"})}catch(G){$e({title:"Technical AEO refresh failed",detail:G instanceof Error?G.message:"Could not reload technical audit data.",tone:"negative",dedupeKey:`technical-aeo:refresh:${t}`,dedupeMode:"replace"})}finally{x(!1)}},F=()=>T.mutate({projectName:t,projectId:s}),C=q==="running"?"Audit running":q==="queued"?"Audit queued":"Starting audit",I=f.data,me=b.data?.pages??Gx,pe=(I?.pagesErrored??0)>0,J=i&&pe,ne=d.useMemo(()=>J?me.filter(G=>G.status==="error"):me,[me,J]),Z=_n({rows:ne,getSearchText:Ox}),Q=I?I.pagesAudited>me.length:!1,V=I?.crossCuttingIssues[0]?.factorId??I?.factors.find(G=>G.pagesPartial+G.pagesFailing>0)?.id??null;if(d.useEffect(()=>{r(!1),l(a?V:null)},[m,a,V]),f.isLoading)return e.jsxs("div",{className:`flex min-h-40 items-center justify-center gap-2 text-sm text-secondary ${a?"":"mt-6"}`,role:"status",children:[e.jsx(It,{className:"size-4 motion-safe:animate-spin","aria-hidden":"true"}),"Loading technical checks..."]});if(f.error)return e.jsxs("section",{className:`flex flex-col gap-4 rounded-lg border border-negative bg-negative-soft px-5 py-5 sm:flex-row sm:items-center sm:justify-between ${a?"":"mt-6"}`,role:"alert",children:[e.jsxs("div",{className:"flex min-w-0 gap-3",children:[e.jsx(Xa,{className:"mt-0.5 size-4 shrink-0 text-negative","aria-hidden":"true"}),e.jsxs("div",{children:[a?e.jsx("h3",{className:"font-semibold text-negative",children:"Technical checks could not load"}):e.jsx("h2",{className:"font-semibold text-negative",children:"Technical checks could not load"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"The saved audit could not be read. Try loading it again."})]})]}),e.jsxs(L,{type:"button",variant:"secondary",size:"sm",className:"shrink-0",onClick:()=>{k()},disabled:h,children:[e.jsx(Is,{className:`size-4 ${h?"motion-safe:animate-spin":""}`,"aria-hidden":"true"}),h?"Trying again...":"Try again"]})]});if(!I||!I.hasData)return a?e.jsxs("section",{className:"rounded-lg border border-default bg-surface-subtle px-5 py-7 text-center",children:[e.jsx(Yi,{className:"mx-auto size-7 text-muted","aria-hidden":"true"}),e.jsx("h2",{className:"mt-3 text-base font-semibold text-heading",children:"Technical checks unavailable"}),e.jsx("p",{className:"mx-auto mt-2 max-w-md text-sm text-secondary",children:"Run a new Site Health scan to calculate page-level technical findings."})]}):e.jsxs(ye,{className:"surface-card mt-6 p-8 text-center",children:[e.jsx(Yi,{className:"mx-auto mb-3 h-8 w-8 text-muted","aria-hidden":"true"}),e.jsx("h2",{className:"text-base font-semibold text-heading",children:"No technical audit yet"}),e.jsx("p",{className:"supporting-copy mx-auto mt-2 max-w-md",children:"A technical AEO audit crawls your sitemap and scores every page for structured data, AI-readable content, crawler access, freshness, and more, then rolls it up into one site score."}),!ie()&&e.jsx("div",{className:"mt-5 flex items-center justify-center gap-3",children:e.jsxs(nt,{type:"button",onClick:F,disabled:D,children:[D?e.jsx(It,{className:"mr-1.5 h-4 w-4 motion-safe:animate-spin","aria-hidden":"true"}):e.jsx(Ms,{className:"mr-1.5 h-4 w-4","aria-hidden":"true"}),D?C:"Run first audit"]})}),D?e.jsx("p",{className:"mt-3 text-xs text-muted",role:"status","aria-live":"polite",children:"The dashboard will refresh automatically when the audit finishes."}):null]});const $=I.deltaScore==null?null:`${I.deltaScore>=0?"+":""}${I.deltaScore} vs previous`,te=I.trend==="up"?"positive":I.trend==="down"?"negative":"neutral",ce=w.data?.points??[],re=ce.map(G=>({runId:G.runId,date:G.auditedAt,score:G.aggregateScore})),Y=n===void 0&&c!==null,fe=me.filter(G=>G.status==="success"),U=I.factors.filter(G=>G.pagesPartial+G.pagesFailing>0).length,be=I.crossCuttingIssues.some(G=>G.topRecommendations.length>0);function Ce(G){const Ee=[];for(const Re of fe){const M=Re.factors.find(de=>de.id===G);M&&M.score<70&&Ee.push({url:Re.url,score:M.score})}return Ee.sort((Re,M)=>Re.score-M.score)}return e.jsxs("div",{className:a?"":"mt-6",children:[a?e.jsxs("section",{className:"flex flex-col gap-3 border-b border-default pb-5 sm:flex-row sm:items-end sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-secondary",children:"Site score"}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2",children:[e.jsxs("span",{"aria-label":`Site score ${I.aggregateScore} out of 100`,className:`inline-flex items-baseline gap-1 font-mono tabular-nums ${aa(I.aggregateScore)}`,children:[e.jsx("span",{className:"text-3xl font-semibold",children:I.aggregateScore}),e.jsx("span",{className:"text-sm text-muted",children:"/100"})]}),e.jsx(oe,{tone:na(I.aggregateScore),children:kn(I.aggregateScore)}),$?e.jsx(oe,{tone:te,children:$}):null]})]}),e.jsxs("p",{className:"flex flex-wrap items-center gap-x-2 gap-y-1 text-sm tabular-nums text-secondary",children:[e.jsxs("span",{children:[I.pagesAudited," page",I.pagesAudited===1?"":"s"," checked"]}),e.jsx("span",{"aria-hidden":"true",className:"text-faint",children:"·"}),e.jsxs("span",{children:[U," check",U===1?"":"s"," need",U===1?"s":""," attention"]}),I.pagesErrored>0?e.jsxs(e.Fragment,{children:[e.jsx("span",{"aria-hidden":"true",className:"text-faint",children:"·"}),e.jsxs("span",{className:"text-negative",children:[I.pagesErrored," crawl error",I.pagesErrored===1?"":"s"]})]}):null]})]}):e.jsxs("section",{className:"surface-card flex flex-wrap items-start justify-between gap-6 rounded-lg border border-default bg-surface p-6",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:Y?"Technical AEO history":"Technical AEO"}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-baseline gap-3",children:[e.jsx("span",{className:`text-4xl font-semibold tabular-nums ${aa(I.aggregateScore)}`,children:I.aggregateScore}),e.jsx("span",{className:"text-lg text-muted",children:"/ 100"}),e.jsx(oe,{tone:na(I.aggregateScore),children:kn(I.aggregateScore)}),$?e.jsx(oe,{tone:te,children:$}):null,D?e.jsx(oe,{tone:"neutral",children:C}):null]}),e.jsxs("p",{className:"supporting-copy mt-2 tabular-nums",children:[I.pagesDiscovered," URL",I.pagesDiscovered===1?"":"s"," in sitemap · ",I.pagesAudited," audited · ",I.pagesSkipped," skipped · ",I.pagesErrored," errored"]}),e.jsxs("p",{className:"mt-1 flex flex-wrap items-center gap-x-1.5 text-xs text-muted",children:[e.jsx("span",{className:"text-faint",children:"Sitemap:"}),e.jsx("a",{href:I.sitemapUrl??"#",target:"_blank",rel:"noreferrer",className:"max-w-[22rem] truncate text-secondary underline decoration-mono-700 underline-offset-2 hover:text-strong",children:I.sitemapUrl}),e.jsx(at,{text:"Every audit re-reads this sitemap, so pages you add or remove are picked up on the next run. Discovered/audited counts and the score reflect the sitemap at the time of the latest run. Override it with `canonry technical-aeo run <project> --sitemap-url <url>`."})]}),I.auditedAt?e.jsxs("p",{className:"mt-0.5 text-xs text-faint",children:["Audited ",new Date(I.auditedAt).toLocaleString()]}):null,D?e.jsx("p",{className:"mt-1 text-xs text-muted",role:"status","aria-live":"polite",children:"Results refresh automatically when this audit finishes."}):null]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[n===void 0&&ce.length>1?e.jsxs("select",{"aria-label":"View a Technical AEO audit",value:c??"",onChange:G=>u(G.target.value||null),className:"min-h-11 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:[e.jsx("option",{value:"",children:"Latest audit"}),[...ce].reverse().slice(1).map(G=>e.jsxs("option",{value:G.runId,children:[new Date(G.auditedAt).toLocaleDateString()," · ",G.aggregateScore,"/100"]},G.runId))]}):null,e.jsxs(L,{type:"button",variant:"outline",size:"sm",onClick:()=>{k()},disabled:h,children:[e.jsx(Is,{className:`mr-1.5 h-4 w-4 ${h?"motion-safe:animate-spin":""}`,"aria-hidden":"true"}),h?"Refreshing…":"Refresh"]}),!ie()&&e.jsxs(nt,{type:"button",size:"sm",onClick:F,disabled:D,children:[D?e.jsx(It,{className:"mr-1.5 h-4 w-4 motion-safe:animate-spin","aria-hidden":"true"}):e.jsx(Ms,{className:"mr-1.5 h-4 w-4","aria-hidden":"true"}),D?C:"Re-run audit"]})]})]}),!a&&re.length>=2?e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h2",{children:"Site score over time"})]}),e.jsxs("div",{className:"mt-3 h-56",children:[e.jsxs("p",{className:"sr-only",children:["Technical AEO scores range from ",Math.min(...re.map(G=>G.score))," to ",Math.max(...re.map(G=>G.score))," across ",re.length," audits. Use the audit selector to inspect a previous scorecard."]}),e.jsx("div",{className:"h-full","aria-hidden":"true",children:e.jsx(sn,{width:"100%",height:"100%",children:e.jsxs(nn,{data:re,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(fi,{stroke:xi,vertical:!1}),e.jsx(an,{dataKey:"date",tick:Ot,tickLine:!1,axisLine:{stroke:us},tickFormatter:Fx,minTickGap:24}),e.jsx(rn,{domain:[0,100],ticks:[0,25,50,75,100],tick:Ot,tickLine:!1,axisLine:!1,width:32}),e.jsx(on,{...Ds,cursor:{stroke:us,strokeWidth:1},labelFormatter:Ux,formatter:G=>[`${G}/100`,"Site score"]}),e.jsx(bi,{type:"monotone",dataKey:"score",name:"score",stroke:cs.positive,strokeWidth:2.5,dot:{r:2.5,fill:cs.positive,strokeWidth:0},isAnimationActive:!1})]})})})]})]}):null,e.jsxs("section",{className:a?"pt-5":"page-section-divider",children:[a?e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Technical findings"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:be?"Select a check to see affected pages and recommended fixes.":"Select a check to see affected pages and score details."})]}):e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Scorecard"}),e.jsxs("h2",{className:"inline-flex items-center gap-1.5",children:["Ranking factors",e.jsx(at,{text:"Each factor is scored 0–100 per page (via the aeo-audit engine), then averaged across all successfully-audited pages. Pass ≥70, partial 40–69, fail <40. Expand a row to see which pages fall short and how to fix it."})]})]}),e.jsx("div",{className:"evidence-table-wrap mt-3",children:e.jsxs("table",{className:`evidence-table ${a?"min-w-[42rem]":""}`,children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:a?"Technical check":"Factor"}),a?null:e.jsx("th",{className:"text-right",children:"Weight"}),e.jsx("th",{className:"text-right",children:a?"Score":"Avg"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:a?"Pages affected":"Pass / Partial / Fail"})]})}),e.jsx("tbody",{children:I.factors.map(G=>{const Ee=o===G.id,Re=I.crossCuttingIssues.find(W=>W.factorId===G.id),M=Ee?Ce(G.id):[],de=G.pagesPartial+G.pagesFailing,ke=G.pagesPassing+de,Oe=!!Re?.topRecommendations.length,Me=Oe&&de>0;return e.jsxs(d.Fragment,{children:[e.jsxs("tr",{className:Ee?"bg-surface-subtle":void 0,children:[e.jsx("td",{children:e.jsxs("button",{type:"button",className:"flex min-h-11 w-full items-center gap-2 text-left font-medium text-strong outline-none hover:text-primary focus-visible:text-primary focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-mono-400","aria-expanded":Ee,onClick:()=>l(Ee?null:G.id),children:[Ee?e.jsx(tn,{className:"size-4 shrink-0 text-muted","aria-hidden":"true"}):e.jsx(qn,{className:"size-4 shrink-0 text-muted","aria-hidden":"true"}),G.name]})}),a?null:e.jsxs("td",{className:"text-right tabular-nums text-muted",children:[G.weight,"%"]}),e.jsxs("td",{className:"text-right font-mono tabular-nums text-strong",children:[G.avgScore,a?e.jsx("span",{className:"text-muted",children:"/100"}):null]}),e.jsx("td",{children:e.jsx(oe,{tone:qx(G.status),children:kn(G.avgScore)})}),a?e.jsxs("td",{className:`tabular-nums ${de>0?"text-strong":"text-muted"}`,children:[de," of ",ke]}):e.jsxs("td",{className:"tabular-nums text-secondary",children:[e.jsx("span",{className:"text-positive-400",children:G.pagesPassing})," / ",e.jsx("span",{className:"text-caution-400",children:G.pagesPartial})," / ",e.jsx("span",{className:"text-negative-400",children:G.pagesFailing})]})]}),Ee?e.jsx("tr",{className:"bg-surface-subtle",children:e.jsx("td",{colSpan:a?4:5,className:"px-4 pb-5 pt-0",children:e.jsxs("div",{className:`grid gap-5 border-t border-subtle pt-4 ${Me?"lg:grid-cols-2":""}`,children:[Oe&&Re?e.jsxs("section",{"aria-labelledby":`technical-finding-${G.id}-fixes`,children:[e.jsx("h4",{id:`technical-finding-${G.id}-fixes`,className:"text-sm font-semibold text-heading",children:"Recommended fixes"}),e.jsx("ol",{className:"mt-2 list-decimal space-y-1.5 pl-5 marker:text-muted",children:Re.topRecommendations.map((W,X)=>e.jsx("li",{className:"pl-1 text-sm text-secondary",children:W},X))}),a?e.jsxs("p",{className:"mt-3 text-xs text-muted",children:["Weight: ",G.weight,"% of the site score"]}):null]}):de===0?e.jsx("p",{className:"text-sm text-secondary",children:"Every audited page passes this check."}):null,de>0?e.jsxs("section",{"aria-labelledby":`technical-finding-${G.id}-pages`,children:[e.jsxs("h4",{id:`technical-finding-${G.id}-pages`,className:"text-sm font-semibold text-heading",children:["Affected pages (",de,")"]}),a&&b.isLoading?e.jsxs("div",{className:"mt-3 flex items-center gap-2 text-sm text-secondary",role:"status",children:[e.jsx(It,{className:"size-4 motion-safe:animate-spin","aria-hidden":"true"}),"Loading affected pages..."]}):a&&b.error?e.jsxs("div",{className:"mt-3",role:"alert",children:[e.jsx("p",{className:"text-sm font-medium text-negative",children:"Affected pages could not load"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Try the page-level audit read again."}),e.jsxs(L,{type:"button",variant:"secondary",size:"sm",className:"mt-3",onClick:()=>{b.refetch()},disabled:b.isFetching,children:[b.isFetching?e.jsx(It,{className:"size-4 motion-safe:animate-spin","aria-hidden":"true"}):e.jsx(Is,{className:"size-4","aria-hidden":"true"}),b.isFetching?"Retrying affected pages...":"Retry affected pages"]})]}):M.length>0?e.jsx("ul",{className:"mt-2 space-y-1.5",children:M.slice(0,Oa).map(W=>e.jsxs("li",{className:"flex min-w-0 items-center gap-2 text-sm",children:[e.jsx("span",{className:`w-8 shrink-0 text-right font-mono tabular-nums ${aa(W.score)}`,children:W.score}),e.jsx("a",{href:W.url,target:"_blank",rel:"noreferrer",className:"min-w-0 truncate text-link outline-none hover:text-heading focus-visible:ring-2 focus-visible:ring-mono-400",title:W.url,children:W.url})]},W.url))}):e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Page details are not available in the loaded audit sample."}),M.length>Oa?e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["+ ",M.length-Oa," more below pass"]}):null,Q&&(!a||!b.isLoading&&!b.error)?e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Showing the worst ",me.length," audited pages."]}):null]}):null]})})}):null]},G.id)})})]})})]}),!a&&I.crossCuttingIssues.length>0?e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Opportunities"}),e.jsxs("h2",{className:"inline-flex items-center gap-1.5",children:["Prioritized fixes",e.jsx(at,{text:"Factors scoring below pass across the most pages, ranked by site-wide impact. Fixing one of these typically lifts many pages at once."})]})]}),e.jsx("div",{className:"mt-3 divide-y divide-mono-800/60 overflow-hidden rounded-lg border border-default",children:I.crossCuttingIssues.map(G=>e.jsxs("div",{className:"p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:G.factorName}),e.jsx(oe,{tone:na(G.avgScore),children:kn(G.avgScore)}),e.jsxs("span",{className:"text-xs tabular-nums text-muted",children:["avg ",G.avgScore," · affects ",G.affectedPages," of ",G.totalPages," pages (",G.affectedPct,"%)"]})]}),G.topRecommendations.length>0?e.jsx("ul",{className:"mt-2 space-y-1",children:G.topRecommendations.map((Ee,Re)=>e.jsxs("li",{className:"flex gap-2 text-sm text-secondary",children:[e.jsx("span",{className:"select-none text-faint",children:"→"}),e.jsx("span",{children:Ee})]},Re))}):null]},G.factorId))})]}):null,a?null:e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Pages"}),e.jsx("h2",{children:"Per-page breakdown"})]}),pe?e.jsxs("div",{className:"segmented",role:"group","aria-label":"Filter pages",children:[e.jsxs("button",{type:"button",onClick:()=>{r(!1),Z.setPage(1)},"aria-pressed":!J,className:`segmented-option min-h-11 tabular-nums ${J?"":"segmented-option-active"}`,children:["All ",I.pagesAudited]}),e.jsxs("button",{type:"button",onClick:()=>{r(!0),Z.setPage(1)},"aria-pressed":J,className:`segmented-option min-h-11 tabular-nums ${J?"segmented-option-active text-negative":""}`,children:["Errors ",I.pagesErrored]})]}):null]}),me.length>0?e.jsx(Ys,{value:Z.query,onChange:Z.setQuery,label:"Filter audited page URLs",placeholder:"Filter page URL or query parameters",className:"mt-3 max-w-md"}):null,Z.totalRows===0?e.jsx("p",{className:"supporting-copy mt-3",children:Z.hasQuery?"No pages match this filter.":"No pages recorded."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"evidence-table-wrap mt-3",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-right",children:"Score"}),e.jsx("th",{children:"Status"}),e.jsx("th",{className:"w-full",children:"URL"})]})}),e.jsx("tbody",{children:Z.rows.map(G=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-right tabular-nums",children:G.status==="error"?e.jsxs("span",{className:"inline-flex items-center gap-1 text-negative-400",children:[e.jsx(Xa,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"err"]}):e.jsx("span",{className:aa(G.overallScore),children:G.overallScore})}),e.jsx("td",{children:G.status==="error"?e.jsx(oe,{tone:"negative",children:"Error"}):e.jsx(oe,{tone:na(G.overallScore),children:kn(G.overallScore)})}),e.jsx("td",{className:"w-full max-w-0",children:e.jsx("a",{href:G.url,target:"_blank",rel:"noreferrer",className:"block truncate text-neutral hover:text-heading",title:G.status==="error"?G.error??G.url:G.url,children:e.jsx(In,{value:G.url,headLength:54,tailLength:20,title:G.status==="error"?G.error??G.url:G.url})})})]},G.url))})]})}),e.jsx(Ts,{page:Z.page,pageSize:Z.pageSize,visibleRows:Z.rows.length,totalRows:Z.totalRows,onPageChange:Z.setPage,itemLabel:Z.hasQuery?"matches":"rows"}),Q?e.jsxs("p",{className:"mt-2 text-xs text-faint",children:["Showing the worst ",me.length," of ",I.pagesAudited," audited pages."]}):null]})]})]})}const Ks=[{id:"map",label:"Map"},{id:"inventory",label:"Inventory"},{id:"technical",label:"Technical checks"}],Bx={map:"Explore how pages, site sections, and internal links fit together.",inventory:"Review discovered pages and the links that shape their visibility.",technical:"Prioritize audit findings and inspect the pages that need work."},Kx=200,Vx=100,sl=100,Qx=50,Hx=Jc,Wx=Xc,oi=new Intl.NumberFormat,Yx=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",year:"numeric"}),Xx={eligible:"positive",hidden:"caution",failed:"negative",unchecked:"neutral"};function nl(t){if(!t)return"Date unavailable";const s=new Date(t);return Number.isNaN(s.getTime())?"Date unavailable":Yx.format(s)}function Jx(t){return t.replaceAll("_"," ").replaceAll("-"," ").replace(/\b\w/g,s=>s.toUpperCase())}function al(t){const s=fa(t);return{label:ua(s),tone:Xx[s]}}function il(t){if(t==null)return"Not scored";const s=t<=1?t*100:t;return`${Math.round(s)}%`}function Zx(t){return t.auditScore==null?"Not checked":`${Math.round(t.auditScore)}/100`}function ot(t){return t==null?"Not available":oi.format(t)}function eg(t,s){if(!t||!s)return null;try{const n=new URL(t).host,a=new URL(s).host;return n!==a?{requested:n,effective:a}:null}catch{return null}}function tg(t){return t==="completed"?"positive":t==="partial"||t==="queued"||t==="running"?"caution":t==="failed"||t==="cancelled"?"negative":"neutral"}function sg(t){return`${nl(t.finishedAt??t.startedAt??t.createdAt)} · ${Jx(t.status)}`}function ng(t){return t?t.includes("page")?"Stopped at the configured page limit. The map contains fetched pages only.":t.includes("edge")?"Stopped at the configured internal-link limit. Some connections are omitted.":t.includes("depth")?"Stopped at the configured crawl depth. Deeper pages were not checked.":"The scan stopped before all discovered pages were checked.":"The scan stopped before all discovered pages were checked."}function ag(t,s){return t==="disabled"?{label:"Check off",tone:"neutral"}:t==="complete"?{label:`${oi.format(s??0)} found`,tone:s?"negative":"positive"}:t==="partial"?{label:`${oi.format(s??0)} found, partial`,tone:"caution"}:{label:"Unavailable",tone:"neutral"}}function ig({page:t}){return e.jsxs("dl",{className:"grid grid-cols-2 divide-x divide-y divide-default rounded-lg border border-default sm:grid-cols-4 sm:divide-y-0",children:[e.jsxs("div",{className:"px-4 py-3",children:[e.jsx("dt",{className:"text-xs text-muted",children:"Crawl depth"}),e.jsx("dd",{className:"mt-1 font-mono text-sm font-medium text-heading",children:t.depth??"Not reached"})]}),e.jsxs("div",{className:"px-4 py-3",children:[e.jsx("dt",{className:"text-xs text-muted",children:"Links in"}),e.jsx("dd",{className:"mt-1 font-mono text-sm font-medium text-heading",children:ot(t.inboundUniqueEdges)})]}),e.jsxs("div",{className:"px-4 py-3",children:[e.jsx("dt",{className:"text-xs text-muted",children:"Links out"}),e.jsx("dd",{className:"mt-1 font-mono text-sm font-medium text-heading",children:ot(t.outboundUniqueEdges)})]}),e.jsxs("div",{className:"px-4 py-3",children:[e.jsx("dt",{className:"text-xs text-muted",children:"Internal-link importance"}),e.jsx("dd",{className:"mt-1 font-mono text-sm font-medium text-heading",children:il(t.linkScoreNormalized)})]})]})}function Ar({direction:t,edges:s,truncated:n}){const a=t==="inbound"?"Links in":"Links out";return e.jsxs("section",{className:"min-w-0","aria-labelledby":`site-health-${t}-heading`,children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("h4",{id:`site-health-${t}-heading`,className:"text-sm font-medium text-heading",children:[a," (",ot(s.length),")"]}),n&&e.jsxs("span",{className:"text-xs text-muted",children:["First ",sl]})]}),s.length===0?e.jsxs("p",{className:"rounded-lg border border-subtle bg-surface-subtle px-3 py-4 text-sm text-secondary",children:["No ",t," internal links were observed."]}):e.jsx("div",{className:"evidence-table-wrap max-h-64 overflow-auto",children:e.jsxs("table",{className:"evidence-table min-w-[420px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Page"}),e.jsx("th",{scope:"col",children:"Anchor text"}),e.jsx("th",{scope:"col",children:"Uses"})]})}),e.jsx("tbody",{children:s.map(i=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-64 truncate font-mono",title:t==="inbound"?i.sourceUrl:i.targetUrl,children:t==="inbound"?i.sourceUrl:i.targetUrl}),e.jsx("td",{className:"max-w-52 truncate",title:i.anchors.join(", ")||void 0,children:i.anchors.join(", ")||"No anchor text"}),e.jsx("td",{className:"font-mono",children:ot(i.occurrences)})]},i.edgeKey))})]})})]})}function $r({page:t,isLoading:s,error:n,inbound:a,outbound:i,inboundTruncated:r,outboundTruncated:o,audit:l,auditLoading:c,auditError:u,onRetryAudit:m}){if(!t)return e.jsxs("section",{className:"border-t border-default pt-5","aria-label":"Selected page details",children:[e.jsx("h3",{className:"text-base font-medium text-heading",children:"Page links"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Select a page to inspect its internal links and crawl signals."})]});const h=al(t);return e.jsxs("section",{className:"border-t border-default pt-5","aria-labelledby":"site-health-page-inspector-title",children:[e.jsxs("div",{className:"flex flex-col justify-between gap-3 sm:flex-row sm:items-start",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("h3",{id:"site-health-page-inspector-title",className:"break-words font-mono text-base font-semibold text-heading",children:t.path}),e.jsx(oe,{tone:h.tone,children:h.label})]}),e.jsx("p",{className:"mt-1 break-all text-sm text-secondary",children:t.url})]}),e.jsx(L,{asChild:!0,variant:"secondary",size:"sm",children:e.jsxs("a",{href:t.url,target:"_blank",rel:"noreferrer",children:["Open page ",e.jsx(bo,{className:"size-3.5","aria-hidden":"true"})]})})]}),e.jsx("div",{className:"mt-4",children:e.jsx(Tx,{audit:l,isLoading:c,error:u,onRetry:m})}),e.jsxs("section",{className:"mt-5 border-t border-default pt-5","aria-labelledby":"site-health-page-links-heading",children:[e.jsx("h3",{id:"site-health-page-links-heading",className:"text-base font-semibold text-heading",children:"Internal links"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Observed links to and from this page in the selected scan."}),e.jsx("div",{className:"mt-4",children:e.jsx(ig,{page:t})}),e.jsx("div",{className:"mt-5",children:s?e.jsxs("div",{className:"flex items-center gap-2 py-6 text-sm text-secondary",children:[e.jsx(It,{className:"size-4 animate-spin","aria-hidden":"true"}),"Loading page links..."]}):n?e.jsx("p",{className:"rounded-lg border border-negative bg-negative-soft px-4 py-3 text-sm text-negative",role:"alert",children:"Page links could not be loaded."}):e.jsxs("div",{className:"grid gap-5 lg:grid-cols-2",children:[e.jsx(Ar,{direction:"inbound",edges:a,truncated:r}),e.jsx(Ar,{direction:"outbound",edges:i,truncated:o})]})})]})]})}function rg({pages:t,total:s,selectedNodeKey:n,onSelect:a,hasNextPage:i,isFetchingNextPage:r,onLoadMore:o}){const[l,c]=d.useState(""),u=l.trim().toLowerCase(),m=d.useMemo(()=>u?t.filter(x=>`${x.path} ${x.url}`.toLowerCase().includes(u)):t,[u,t]),h=u.length>0&&(i||t.length<s);return e.jsxs("section",{"aria-labelledby":"site-health-inventory-heading",children:[e.jsxs("div",{className:"mb-3 flex flex-col justify-between gap-3 sm:flex-row sm:items-end",children:[e.jsxs("div",{children:[e.jsx("h2",{id:"site-health-inventory-heading",className:"text-base font-semibold text-heading",children:"Page inventory"}),e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:["Loaded ",ot(t.length)," of ",ot(s)," discovered pages."]})]}),e.jsxs("label",{className:"relative block w-full sm:w-72",children:[e.jsx("span",{className:"sr-only",children:"Search loaded pages"}),e.jsx(pi,{className:"pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted","aria-hidden":"true"}),e.jsx("input",{type:"search",value:l,onChange:x=>c(x.target.value),placeholder:"Search loaded pages",className:"h-9 w-full rounded-md border border-base bg-bg pl-9 pr-3 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-600"})]})]}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table min-w-[940px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Page"}),e.jsx("th",{scope:"col",children:"Status"}),e.jsx("th",{scope:"col",children:"Technically eligible"}),e.jsx("th",{scope:"col",children:"Crawl depth"}),e.jsx("th",{scope:"col",children:"Links in"}),e.jsx("th",{scope:"col",children:"Links out"}),e.jsx("th",{scope:"col",children:"Internal-link importance"}),e.jsx("th",{scope:"col",children:"Technical score"})]})}),e.jsx("tbody",{children:m.map(x=>{const N=al(x);return e.jsxs("tr",{className:n===x.nodeKey?"bg-surface-active":void 0,children:[e.jsx("td",{className:"max-w-80",children:e.jsx("button",{type:"button",onClick:()=>a(x.nodeKey),className:"block max-w-full truncate rounded-sm font-mono text-sm font-medium text-link outline-none focus-visible:ring-2 focus-visible:ring-mono-400",title:x.url,children:x.path})}),e.jsx("td",{children:e.jsx(oe,{tone:N.tone,children:N.label})}),e.jsx("td",{children:x.inventoryEligible?"Yes":"No"}),e.jsx("td",{className:"font-mono",children:x.depth??"Not reached"}),e.jsx("td",{className:"font-mono",children:ot(x.inboundUniqueEdges)}),e.jsx("td",{className:"font-mono",children:ot(x.outboundUniqueEdges)}),e.jsx("td",{className:"font-mono",children:il(x.linkScoreNormalized)}),e.jsx("td",{className:"font-mono",children:Zx(x)})]},x.nodeKey)})})]})}),m.length===0&&e.jsx("p",{className:"border-x border-b border-default px-4 py-8 text-center text-sm text-secondary",children:u.length===0?"No pages are available.":h?`No matches in the ${ot(t.length)} loaded pages. Load more pages to continue searching.`:"No pages match this search."}),i&&e.jsx("div",{className:"flex justify-center border-x border-b border-default px-4 py-3",children:e.jsxs(L,{variant:"secondary",size:"sm",disabled:r,onClick:o,children:[r&&e.jsx(It,{className:"size-4 animate-spin","aria-hidden":"true"}),r?"Loading more pages":"Load more pages"]})})]})}function og({projectName:t,runId:s,section:n,onSelect:a}){const[i,r]=d.useState(!1),l=n.pageCount-(n.hasPage?1:0)>0;return e.jsxs("li",{children:[e.jsxs("div",{className:"flex min-h-11 items-center gap-1 px-2 py-1",children:[l?e.jsx("button",{type:"button","aria-label":`${i?"Collapse":"Expand"} ${n.path}`,"aria-expanded":i,onClick:()=>r(c=>!c),className:"flex size-8 shrink-0 items-center justify-center rounded-sm text-muted outline-none hover:bg-surface-hover hover:text-heading focus-visible:ring-2 focus-visible:ring-mono-400",children:i?e.jsx(tn,{className:"size-3.5","aria-hidden":"true"}):e.jsx(qn,{className:"size-3.5","aria-hidden":"true"})}):e.jsx("span",{className:"block size-8 shrink-0","aria-hidden":"true"}),e.jsx("button",{type:"button",onClick:()=>a(n.path),className:"min-w-0 flex-1 break-all rounded-sm py-2 text-left font-mono text-sm text-heading outline-none hover:text-link focus-visible:ring-2 focus-visible:ring-mono-400",children:n.path}),e.jsx("span",{className:"shrink-0 px-2 font-mono text-xs text-muted",children:ot(n.pageCount)})]}),i&&e.jsx("div",{className:"ml-6 border-l border-default pl-1",children:e.jsx(rl,{projectName:t,runId:s,parentPath:n.path,onSelect:a})})]})}function rl({projectName:t,runId:s,parentPath:n,onSelect:a}){const i={client:H,path:{name:t},query:{runId:s,parentPath:n,limit:Vx}},r=ui({...Zc(i),initialPageParam:i,getNextPageParam:l=>l.nextCursor?{path:i.path,query:{...i.query,cursor:l.nextCursor}}:void 0}),o=r.data?.pages.flatMap(l=>l.children)??[];return r.isLoading?e.jsxs("div",{className:"flex items-center gap-2 px-3 py-4 text-sm text-secondary",role:"status",children:[e.jsx(It,{className:"size-4 animate-spin","aria-hidden":"true"})," Loading sections..."]}):r.error?e.jsx("p",{className:"px-3 py-4 text-sm text-negative",role:"alert",children:"Site sections could not be loaded."}):o.length===0?e.jsx("p",{className:"px-3 py-4 text-sm text-secondary",children:"No nested sections were found."}):e.jsxs(e.Fragment,{children:[e.jsx("ul",{className:"divide-y divide-default",children:o.map(l=>e.jsx(og,{projectName:t,runId:s,section:l,onSelect:a},l.path))}),r.hasNextPage&&e.jsx("div",{className:"px-3 py-2",children:e.jsx(L,{variant:"ghost",size:"sm",disabled:r.isFetchingNextPage,onClick:()=>{r.fetchNextPage()},children:r.isFetchingNextPage?"Loading more sections":"Load more sections"})})]})}function lg(){return e.jsx("div",{role:"status",className:"flex min-h-[420px] items-center justify-center rounded-lg border border-default bg-surface-inset px-6 text-center lg:min-h-[520px]",children:e.jsxs("div",{className:"max-w-sm",children:[e.jsx(It,{className:"mx-auto size-5 animate-spin text-muted","aria-hidden":"true"}),e.jsx("p",{className:"mt-3 text-sm font-medium text-heading",children:"Preparing the interactive site map"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Page and link data is ready for the graph renderer."})]})})}function cg({projectName:t,projectId:s}){const[n,a]=d.useState("map"),i=d.useRef([]),[r,o]=d.useState(null),[l,c]=d.useState(null),[u,m]=d.useState(!1),h=ie(),x=uo(),f=De({...mi({client:H,path:{name:t},query:{kind:ws["site-audit"],limit:20}}),refetchOnWindowFocus:"always",refetchInterval:M=>M.state.data?.some(de=>de.status==="queued"||de.status==="running")?3e3:15e3}).data??[],w=f.find(M=>M.status==="queued"||M.status==="running"),b=f.filter(M=>M.status==="completed"||M.status==="partial").at(-1),A=r??b?.id??null,T=De({...Kc({client:H,path:{name:t},...A?{query:{runId:A}}:{}}),refetchInterval:!r&&w?3e3:!1}),P=T.data,j=A??P?.runId??null,p=!!(j&&P?.hasCrawlData&&P.detailsAvailable),y=j?{runId:j}:{},v=De({...Vc({client:H,path:{name:t},query:{...y,maxNodes:Hx,maxEdges:Wx}}),enabled:p}),D={client:H,path:{name:t},query:{...y,limit:Kx,sort:"path"}},q=ui({...Qc(D),enabled:p,initialPageParam:D,getNextPageParam:M=>M.nextCursor?{path:D.path,query:{...D.query,cursor:M.nextCursor}}:void 0}),S=p&&(P?.deadLinks.state==="complete"||P?.deadLinks.state==="partial"),k=De({...Hc({client:H,path:{name:t},query:{...y,limit:Qx}}),enabled:S}),F=v.data?.nodes??[],C=v.data?.layout.state==="ready"?v.data.totalEdges:null,I=d.useMemo(()=>q.data?.pages.flatMap(M=>M.pages)??[],[q.data]),me=q.data?.pages[0]?.total??I.length,pe=d.useMemo(()=>F.find(M=>M.nodeKey===l)??I.find(M=>M.nodeKey===l)??null,[F,I,l]),J=pe?.nodeKey??null,ne=De({...Wc({client:H,path:{name:t},query:{...y,nodeKey:J??void 0,limit:sl}}),enabled:p&&!!J}),Z=De({...Yc({client:H,path:{name:t},query:{...y,nodeKey:J??void 0}}),enabled:p&&!!J}),Q=d.useMemo(()=>[...f].filter(M=>M.status==="completed"||M.status==="partial").sort((M,de)=>de.createdAt.localeCompare(M.createdAt)),[f]),V=d.useMemo(()=>f.length===0?null:[...f].sort((M,de)=>de.createdAt.localeCompare(M.createdAt))[0].status,[f]),$=j?f.find(M=>M.id===j):void 0,te=!r&&w?w.status:P?.runStatus??$?.status??null,ce=te==="running"?"Scan running":te==="queued"?"Scan queued":te==="partial"?"Partial scan":te==="completed"?"Complete":te==="failed"?"Scan failed":"No scan",re=k.data,Y=ag(re?.state??P?.deadLinks.state??"unavailable",re&&"found"in re?re.found:P?.deadLinks&&"found"in P.deadLinks?P.deadLinks.found:void 0),fe=eg(P?.requestedRootUrl??null,P?.rootUrl??null),U=x.isPending||!!w,be=M=>{o(M||null),c(null)},Ce=()=>x.mutate({projectName:t,projectId:s,body:{checkDeadLinks:u}}),G=M=>{const de=F.find(ke=>ke.path===M||ke.path.startsWith(`${M}/`));de&&c(de.nodeKey)},Ee=M=>a(M),Re=(M,de)=>{let ke=null;M.key==="ArrowRight"||M.key==="ArrowDown"?ke=(de+1)%Ks.length:M.key==="ArrowLeft"||M.key==="ArrowUp"?ke=(de-1+Ks.length)%Ks.length:M.key==="Home"?ke=0:M.key==="End"&&(ke=Ks.length-1),ke!=null&&(M.preventDefault(),Ee(Ks[ke].id),i.current[ke]?.focus())};return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("header",{className:"flex flex-col justify-between gap-4 lg:flex-row lg:items-start",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("h2",{className:"text-xl font-semibold tracking-tight text-heading",children:"Site Health"}),e.jsx(oe,{tone:tg(te),children:ce}),$&&e.jsx("span",{className:"text-xs text-muted",children:nl($.finishedAt??$.startedAt)})]}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:Bx[n]})]}),e.jsxs("div",{className:"flex flex-wrap items-start gap-2",children:[e.jsxs("label",{className:"grid gap-1 text-xs text-muted",children:["Scan history",e.jsxs("select",{"aria-label":"View a Site Health scan",value:r??"",onChange:M=>be(M.target.value),className:"h-9 min-w-48 rounded-md border border-base bg-bg px-3 text-sm text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-600",children:[e.jsx("option",{value:"",children:"Latest scan"}),Q.map(M=>e.jsx("option",{value:M.id,children:sg(M)},M.id))]})]}),!h&&e.jsxs("div",{className:"flex items-end gap-2 pt-5",children:[e.jsxs("details",{className:"group relative",children:[e.jsxs("summary",{className:"flex h-9 cursor-pointer list-none items-center gap-2 rounded-md border border-base bg-bg px-3 text-sm font-medium text-heading outline-none hover:bg-bg-elevated focus-visible:ring-2 focus-visible:ring-mono-400",children:[e.jsx(Tu,{className:"size-4","aria-hidden":"true"}),"Scan settings"]}),e.jsx("div",{className:"absolute right-0 z-20 mt-2 w-72 rounded-lg border border-strong bg-bg-elevated p-4 shadow-[0_12px_32px_var(--color-shadow-panel)]",children:e.jsxs("label",{className:"flex cursor-pointer items-start gap-3 text-sm text-heading",children:[e.jsx("input",{type:"checkbox","aria-label":"Check dead links",checked:u,disabled:U,onChange:M=>m(M.target.checked),className:"mt-0.5 size-4 rounded border-base accent-mono-200 focus:ring-2 focus:ring-mono-400"}),e.jsxs("span",{children:[e.jsx("span",{className:"font-medium",children:"Check dead links"}),e.jsx("span",{className:"mt-1 block text-sm text-secondary",children:"Adds dead-link analysis to this scan."})]})]})})]}),e.jsxs(nt,{onClick:Ce,disabled:U,children:[U?e.jsx(It,{className:"size-4 animate-spin","aria-hidden":"true"}):e.jsx(Ms,{className:"size-4","aria-hidden":"true"}),w?.status==="running"?"Scan running":w?.status==="queued"?"Scan queued":"Run scan"]})]})]})]}),P?.hasCrawlData&&n!=="technical"&&e.jsxs("div",{className:"grid grid-cols-2 divide-x divide-y divide-default rounded-lg border border-default bg-surface-subtle sm:grid-cols-4 sm:divide-y-0",children:[e.jsxs("div",{className:"px-4 py-3",children:[e.jsx("div",{className:"text-xs text-muted",children:"Pages found"}),e.jsx("div",{className:"mt-1 font-mono text-xl font-semibold tabular-nums text-heading",children:ot(P.counts.pagesDiscovered)})]}),e.jsxs("div",{className:"px-4 py-3",children:[e.jsx("div",{className:"text-xs text-muted",children:"Pages checked"}),e.jsx("div",{className:"mt-1 font-mono text-xl font-semibold tabular-nums text-heading",children:ot(P.counts.pagesFetched)})]}),e.jsxs("div",{className:"px-4 py-3",children:[e.jsx("div",{className:"text-xs text-muted",children:"Technically eligible"}),e.jsx("div",{className:"mt-1 font-mono text-xl font-semibold tabular-nums text-heading",children:ot(P.counts.pagesEligible)})]}),e.jsxs("div",{className:"px-4 py-3",children:[e.jsx("div",{className:"text-xs text-muted",children:"Internal links"}),e.jsx("div",{className:"mt-1 font-mono text-xl font-semibold tabular-nums text-heading",children:ot(C)})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 border-b border-default",children:[e.jsx("div",{role:"tablist","aria-label":"Site Health views","aria-orientation":"horizontal",className:"flex min-w-0 gap-5",children:Ks.map((M,de)=>e.jsx("button",{type:"button",role:"tab",id:`site-health-${M.id}-tab`,"aria-selected":n===M.id,"aria-controls":`site-health-${M.id}-panel`,tabIndex:n===M.id?0:-1,ref:ke=>{i.current[de]=ke},onClick:()=>Ee(M.id),onKeyDown:ke=>Re(ke,de),className:`min-h-11 border-b-2 px-0.5 text-sm font-medium outline-none transition-colors focus-visible:ring-2 focus-visible:ring-mono-400 ${n===M.id?"border-strong text-heading":"border-transparent text-secondary hover:border-base hover:text-primary"}`,children:M.label},M.id))}),P?.hasCrawlData&&n!=="technical"&&e.jsxs("div",{className:"flex items-center gap-2 pb-2",children:[e.jsx("span",{className:"text-xs text-muted",children:"Dead-link check"}),e.jsx(oe,{tone:Y.tone,children:Y.label})]})]}),!r&&w&&e.jsx("div",{className:"rounded-lg border border-caution bg-caution-soft px-4 py-3 text-sm text-caution",role:"status",children:"The scan is running. The latest completed results remain available until it finishes."}),fe&&e.jsxs("div",{className:"rounded-lg border border-base bg-surface-subtle px-4 py-3 text-sm text-secondary",role:"status",children:[e.jsx("span",{className:"font-medium text-heading",children:"Site address changed during this scan."})," ","The scan started at ",e.jsx("span",{className:"font-mono text-primary",children:fe.requested})," and continued at"," ",e.jsx("span",{className:"font-mono text-primary",children:fe.effective}),". The map and inventory use the new address."]}),P?.hasCrawlData&&!P.complete&&e.jsx("div",{className:"rounded-lg border border-caution bg-caution-soft px-4 py-3 text-sm text-caution",role:"status",children:ng(P.termination)}),!w&&V==="failed"&&!r&&e.jsxs("div",{className:"flex gap-3 rounded-lg border border-negative bg-negative-soft px-4 py-3 text-sm text-negative",role:"alert",children:[e.jsx(Xa,{className:"mt-0.5 size-4 shrink-0","aria-hidden":"true"}),e.jsx("span",{children:"The latest scan failed. The previous completed results remain available."})]}),n==="technical"?e.jsx("div",{id:"site-health-technical-panel",role:"tabpanel","aria-labelledby":"site-health-technical-tab",className:"min-w-0",children:e.jsx(zx,{projectName:t,projectId:s,runId:j,integrated:!0})}):T.isLoading?e.jsxs("div",{className:"flex min-h-72 items-center justify-center gap-2 text-sm text-secondary",role:"status",children:[e.jsx(It,{className:"size-4 animate-spin","aria-hidden":"true"}),"Loading site health..."]}):T.error?e.jsxs("section",{className:"rounded-lg border border-negative bg-negative-soft px-5 py-6",role:"alert",children:[e.jsx("h2",{className:"font-semibold text-negative",children:"Site Health could not load"}),e.jsx("p",{className:"mt-1 text-sm text-negative",children:"Try loading the crawl again."}),e.jsx(L,{variant:"secondary",size:"sm",className:"mt-4",onClick:()=>{T.refetch()},children:"Try again"})]}):P?.hasCrawlData?P.detailsAvailable?n==="inventory"?e.jsxs("div",{id:"site-health-inventory-panel",role:"tabpanel","aria-labelledby":"site-health-inventory-tab",className:"space-y-5",children:[q.isLoading?e.jsxs("div",{className:"flex min-h-56 items-center justify-center gap-2 text-sm text-secondary",role:"status",children:[e.jsx(It,{className:"size-4 animate-spin","aria-hidden":"true"}),"Loading page inventory..."]}):q.error?e.jsx("p",{className:"rounded-lg border border-negative bg-negative-soft px-4 py-3 text-sm text-negative",role:"alert",children:"The page inventory could not be loaded."}):e.jsx(rg,{pages:I,total:me,selectedNodeKey:J,onSelect:c,hasNextPage:!!q.hasNextPage,isFetchingNextPage:q.isFetchingNextPage,onLoadMore:()=>{q.fetchNextPage()}}),e.jsx($r,{page:pe,isLoading:ne.isLoading&&!!pe,error:ne.error,inbound:ne.data?.inbound??[],outbound:ne.data?.outbound??[],inboundTruncated:ne.data?.inboundTruncated??!1,outboundTruncated:ne.data?.outboundTruncated??!1,audit:Z.data,auditLoading:Z.isLoading&&!!pe,auditError:Z.error,onRetryAudit:()=>{Z.refetch()}})]}):e.jsxs("div",{id:"site-health-map-panel",role:"tabpanel","aria-labelledby":"site-health-map-tab",className:"space-y-5",children:[e.jsxs("section",{"aria-labelledby":"site-map-heading",children:[e.jsxs("div",{className:"mb-3 flex flex-col justify-between gap-2 sm:flex-row sm:items-end",children:[e.jsxs("div",{children:[e.jsx("h2",{id:"site-map-heading",className:"text-base font-semibold text-heading",children:"Site map"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Scroll to zoom, drag to move, and select a page to inspect its technical findings and links."})]}),v.data?.sampled&&e.jsxs("span",{className:"text-xs text-muted",children:["Showing ",ot(v.data.nodes.length)," of ",ot(v.data.totalNodes)," pages"," · ",ot(v.data.edges.length)," of ",ot(v.data.totalEdges)," links"]})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-[minmax(0,1fr)_18rem]",children:[v.isLoading?e.jsx(lg,{}):v.error?e.jsx("div",{className:"flex min-h-[420px] items-center justify-center rounded-lg border border-negative bg-negative-soft px-6 text-center text-sm text-negative lg:min-h-[520px]",role:"alert",children:"The interactive map could not be loaded."}):e.jsx(Lx,{nodes:v.data?.nodes??[],edges:v.data?.edges??[],layoutState:v.data?.layout.state??"unavailable",layoutUnavailableReason:v.data?.layout.state==="unavailable"?v.data.layout.reason:null,selectedNodeKey:J,onSelectNode:M=>c(M.nodeKey),ariaLabel:`Interactive site map showing ${ot(v.data?.nodes.length??0)} pages and ${ot(v.data?.edges.length??0)} internal links`}),e.jsxs("aside",{className:"rounded-lg border border-default bg-surface-subtle","aria-labelledby":"site-sections-heading",children:[e.jsxs("div",{className:"border-b border-default px-4 py-3",children:[e.jsx("h3",{id:"site-sections-heading",className:"text-sm font-semibold text-heading",children:"Site sections"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"Top-level folders in this scan"})]}),e.jsx("div",{className:"max-h-[468px] overflow-auto",children:j&&e.jsx(rl,{projectName:t,runId:j,parentPath:"/",onSelect:G})})]})]})]}),e.jsx($r,{page:pe,isLoading:ne.isLoading&&!!pe,error:ne.error,inbound:ne.data?.inbound??[],outbound:ne.data?.outbound??[],inboundTruncated:ne.data?.inboundTruncated??!1,outboundTruncated:ne.data?.outboundTruncated??!1,audit:Z.data,auditLoading:Z.isLoading&&!!pe,auditError:Z.error,onRetryAudit:()=>{Z.refetch()}})]}):e.jsxs("section",{className:"rounded-lg border border-caution bg-caution-soft px-5 py-6",children:[e.jsx("h2",{className:"font-semibold text-caution",children:"Page details unavailable"}),e.jsx("p",{className:"mt-1 text-sm text-caution",children:"Summary metrics are preserved for this scan, but its page graph cannot be opened."})]}):e.jsxs("section",{className:"rounded-lg border border-default bg-surface-subtle px-5 py-8 text-center",children:[e.jsx("h2",{className:"text-base font-semibold text-heading",children:"Full-site map not available"}),e.jsx("p",{className:"mx-auto mt-2 max-w-xl text-sm text-secondary",children:P?.legacyAuditAvailable?"Existing technical checks are preserved. Run a new scan to build the page and internal-link map.":h?"A full-site scan has not been run for this project.":"Run a scan to discover pages, site sections, and internal links."}),P?.legacyAuditAvailable&&e.jsx(L,{variant:"secondary",size:"sm",className:"mt-4",onClick:()=>a("technical"),children:"View technical checks"})]})]})}function Pr(t){return`${(t*100).toFixed(1)}%`}function dg({projectName:t}){const[s,n]=d.useState("changes"),[a,i]=d.useState(null),[r,o]=d.useState(null),l=De({...ed({client:H,path:{name:t},query:{limit:30}}),enabled:s==="health"}),c=De({...mi({client:H,path:{name:t},query:{kind:"answer-visibility",limit:100}}),enabled:s==="compare"}),u=(c.data??[]).filter(b=>(b.status==="completed"||b.status==="partial")&&b.trigger!=="probe").reverse(),m=r??u[0]?.id??"",h=a??u.find(b=>b.id!==m)?.id??"",x=!!(h&&m&&h!==m),N=De({...td({client:H,path:{name:t},query:{run1:h,run2:m}}),enabled:s==="compare"&&x}),f=l.data??[],w=N.data?.diff.filter(b=>b.changed||b.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(([b,A])=>e.jsx("button",{type:"button",role:"tab","aria-selected":s===b,className:`filter-chip ${s===b?"filter-chip-active":""}`,onClick:()=>n(b),children:A},b))}),s==="changes"?e.jsx(zu,{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."})]}),l.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Loading coverage history…"}):null,!l.isLoading&&f.length===0?e.jsxs(ye,{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(b=>e.jsxs("tr",{children:[e.jsx("td",{className:"whitespace-nowrap tabular-nums text-secondary",children:new Date(b.createdAt).toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[b.mentionedPairs,"/",b.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:Pr(b.overallMentionRate)}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[b.citedPairs,"/",b.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:Pr(b.overallCitedRate)})]},b.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:h,onChange:b=>i(b.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:u.map(b=>e.jsx("option",{value:b.id,children:new Date(b.createdAt).toLocaleString()},b.id))})]}),e.jsxs("label",{className:"text-xs text-muted",children:["Later run",e.jsx("select",{value:m,onChange:b=>o(b.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:u.map(b=>e.jsx("option",{value:b.id,children:new Date(b.createdAt).toLocaleString()},b.id))})]})]}),c.isLoading||N.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Comparing runs…"}):null,!c.isLoading&&u.length<2?e.jsxs(ye,{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&&w.length===0?e.jsxs(ye,{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,w.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:w.map(b=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:b.query??"Archived query"}),e.jsx("td",{children:e.jsxs(oe,{tone:b.changed?"caution":"neutral",children:[b.run1State??"none"," → ",b.run2State??"none"]})}),e.jsx("td",{children:e.jsxs(oe,{tone:b.visibilityChanged?"caution":"neutral",children:[b.run1MentionState??"none"," → ",b.run2MentionState??"none"]})})]},b.queryId??b.query??"unknown"))})]})}):null]}):null]})}const qa=20,os=50,ug=50,hg=50;function Ci(t){return t==="viewer"}function Ai(t){return t?.status==="unavailable"}function ol(t,s,n){return n?t.includes(s)?[...t]:[...t,s]:t.filter(a=>a!==s)}function ll(t,s){const n=new Map(s.map(i=>[i.id,i.label])),a=t.map(i=>n.get(i)).filter(i=>!!i);return a.length===0?"Not applied":a.length>3?`${a.length} Properties`:a.join(", ")}function ia(t,s,n){if(t.kind==="all")return s.map(r=>r.id);if(t.kind==="specific")return s.filter(r=>t.propertyIds.includes(r.id)).map(r=>r.id);const a=new Set(t.groupIds),i=new Set(n.filter(r=>a.has(r.id)).flatMap(r=>r.propertyIds));return s.filter(r=>i.has(r.id)).map(r=>r.id)}function mg(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(i=>s.find(r=>r.id===i)?.name).filter(i=>!!i);return a.length===0?"selected groups":a.join(" + ")}function Fa(t,s){const n=new Set(s.map(i=>i.id)),a=t.propertyIds.filter(i=>n.has(i)).length;return`${t.name} · ${a===1?"1 Property":`${a} Properties`}`}function Rr(t){return t==="matched"?"positive":t==="duplicate"?"neutral":t==="ambiguous"||t==="proposed"||t==="excluded"?"caution":"negative"}function Lr(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 ra(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 li(t){return t.state==="missing"||t.source==="unavailable-tracked-query"||!t.source}function Ua(t){return li(t)?"Unavailable tracked query":t.text?.trim()||"Unavailable tracked query"}function ci({properties:t,selectedPropertyIds:s,onSelectedPropertyIdsChange:n,legend:a,showBulkActions:i=!0}){const[r,o]=d.useState(""),[l,c]=d.useState(!1),u=r.trim().toLocaleLowerCase(),m=u?t.filter(f=>f.label.toLocaleLowerCase().includes(u)):t,h=l?m:m.slice(0,ug),x=h.length<m.length;function N(){const f=new Set([...s,...h.map(w=>w.id)]);n(t.filter(w=>f.has(w.id)).map(w=>w.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:r,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"})]}),i?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(L,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:h.length===0,onClick:N,children:"Select all shown"}),e.jsx(L,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:s.length===0,onClick:()=>n([]),children:"Clear selection"})]}):null]}),m.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 ",h.length," of ",m.length," Properties"]}),e.jsx("div",{className:"mt-2 max-h-96 divide-y divide-default overflow-y-auto border-y border-default",children:h.map(f=>{const w=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:w,type:"checkbox",onChange:b=>n(ol(s,f.id,b.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)})}),x?e.jsx(L,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",onClick:()=>c(!0),children:"Show all Properties"}):null]})]})}function $i(){return e.jsxs("div",{className:"flex items-center gap-2 text-sm text-secondary",children:[e.jsx(oe,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]})}function Pi({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(oe,{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 pg({value:t}){const[s,n]=d.useState(0),[a,i]=d.useState(0),[r,o]=d.useState(null),l=t.preview,c=l?.counts.needsAttention??0,u=l?.rows.filter(v=>v.status==="matched")??[],m=l?.rows??[],h=m.filter(v=>v.status!=="matched"),x=Math.max(1,Math.ceil(m.length/os)),N=Math.min(s,x-1),f=m.slice(N*os,(N+1)*os),w=Math.max(1,Math.ceil(h.length/os)),b=Math.min(a,w-1),A=h.slice(b*os,(b+1)*os),T=t.csv.trim().length>0&&!t.isReviewing&&!t.isApplying,P=u.length>0&&!t.isApplying,j=l!==null&&r===l.previewChecksum,p=h.length>0&&b===w-1;d.useEffect(()=>{n(0),i(0),o(null)},[l?.previewChecksum]);async function y(v){if(v)try{t.onCsvChange(await v.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:v=>{y(v.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:v=>t.onCsvChange(v.currentTarget.value),placeholder:`property,group,url
|
|
10
10
|
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(L,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!T,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]}),l?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:[l.counts.matchedRows," matched · ",l.counts.groupsReady," group",l.counts.groupsReady===1?"":"s"," ready",c>0?` · ${c} need${c===1?"s":""} attention`:""]}),l.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:l.groupChanges.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:v.label}),e.jsx("td",{className:"text-secondary",children:v.action==="create"?"Create group":"Add to existing group"}),e.jsx("td",{className:"tabular-nums text-secondary",children:v.targetKeys.length}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[v.addedTargetKeys.length,v.unchangedTargetKeys.length>0?` · ${v.unchangedTargetKeys.length} already members`:""]})]},v.groupKey))})]})}):null,l.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 (",l.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(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:v.dataRow}),e.jsx("td",{className:"text-heading",children:v.property}),e.jsx("td",{className:"text-secondary",children:v.group}),e.jsxs("td",{children:[e.jsx(oe,{tone:Rr(v.status),children:Lr(v.status)}),ra(v)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:ra(v)}):null]})]},v.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 ",x," · ",l.rows.length," rows"]}),e.jsx(L,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:N===0,onClick:()=>n(v=>Math.max(0,v-1)),children:"Previous 50 rows"}),e.jsx(L,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:N===x-1,onClick:()=>n(v=>Math.min(x-1,v+1)),children:"Next 50 rows"})]})]}):null,c>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 ",c," row",c===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:A.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:v.dataRow}),e.jsx("td",{className:"text-heading",children:v.property}),e.jsx("td",{className:"text-secondary",children:v.group}),e.jsxs("td",{children:[e.jsx(oe,{tone:Rr(v.status),children:Lr(v.status)}),ra(v)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:ra(v)}):null]})]},v.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 ",b+1," of ",w]}),e.jsx(L,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:b===0,onClick:()=>i(v=>Math.max(0,v-1)),children:"Previous 50 exceptions"}),e.jsx(L,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:b===w-1,onClick:()=>i(v=>Math.min(w-1,v+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:j,disabled:t.isApplying||!p,onChange:v=>o(v.currentTarget.checked?l.previewChecksum:null),className:"size-4 rounded border-default"}),"I reviewed the exceptions and understand that ",c," row",c===1?"":"s"," will be skipped."]}),e.jsx(L,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",disabled:!P||!j,onClick:()=>{t.onApply(u.map(v=>v.dataRow))},children:t.isApplying?"Applying groups…":`Apply ${u.length} matched row${u.length===1?"":"s"}`})]}):e.jsx(L,{type:"button",className:"mt-3 min-h-11",disabled:!P,onClick:()=>{t.onApply(u.map(v=>v.dataRow))},children:t.isApplying?"Creating groups…":`Create ${l.counts.groupsReady} group${l.counts.groupsReady===1?"":"s"} with ${u.length} membership${u.length===1?"":"s"}`})]}):null]})}const xg="—";function gg({access:t,availability:s,properties:n,queries:a,selectedQueryIds:i,isApplying:r=!1,isBusy:o=!1,canContinue:l=!0,onSelectedQueryIdsChange:c,onApplySelectedQueries:u,onClearQueryAssignments:m,onRemoveQuery:h,onCreateQueries:x,onCreateAndPairQuestions:N,isCreatingQueries:f=!1,createQueriesError:w=null,onManageProjectQueries:b,groups:A,audience:T,onAudienceChange:P,assignmentImpact:j=null,isPreviewingAssignmentImpact:p=!1,assignmentImpactError:y=null,onRetryAssignmentImpact:v,assignmentNotice:D=null,onReplaceAssignments:q,isReplacingAssignments:S=!1,onBack:k,onContinue:F}){const[C,I]=d.useState(""),[me,pe]=d.useState(!1),[J,ne]=d.useState(!1),[Z,Q]=d.useState(""),[V,$]=d.useState(""),[te,ce]=d.useState(null);if(Ai(s))return e.jsx("section",{"aria-label":"Queries",children:e.jsx(Pi,{message:s.message})});const re=Ci(t),Y=T,fe=P,U=ia(Y,n,A),be=U.length,Ce=be>0&&i.length>0&&!r&&!o&&!p&&j!==null&&y===null,G=m??h,Ee=C.trim().toLocaleLowerCase(),Re=Ee?a.filter(z=>Ua(z).toLocaleLowerCase().includes(Ee)):a,M=Re.filter(z=>(z.propertyIds?.length??0)===0),de=J?M:Re,ke=me?de:de.slice(0,hg),Oe=ke.filter(z=>!li(z)),Me=[...new Set(Z.split(`
|
|
11
11
|
`).map(z=>z.trim()).filter(Boolean))],W=[...V.matchAll(/\{([a-z][\w-]*)\}/gi)].map(z=>z[1]),X=n.filter(z=>U.includes(z.id)),Ne=W.length===0||V.trim()===""?[]:X.map(z=>({propertyId:z.id,text:W.reduce((Se,Qe)=>Se.replaceAll(`{${Qe}}`,z.label),V.trim())})),O=[...new Set(Ne.map(z=>z.text))];function E(){const z=new Set([...i,...Oe.map(Se=>Se.id)]);c(a.filter(Se=>z.has(Se.id)).map(Se=>Se.id))}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-queries-title",className:"space-y-5",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{id:"advanced-measurement-queries-title",children:"Queries"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Choose queries, then apply them to Properties."})]})}),re?e.jsx($i,{}):null,re?null:e.jsxs("fieldset",{className:"border-y border-default py-4",children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:"Apply to"}),e.jsx("div",{className:"mt-3 max-w-xl",children:e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"sr-only",children:"Apply to"}),e.jsxs("select",{"aria-label":"Apply to",value:Y.kind==="all"?"all":Y.kind==="specific"?"specific":`group:${Y.groupIds[0]??""}`,onChange:z=>{const Se=z.currentTarget.value;Se==="all"?fe({kind:"all"}):Se==="specific"?fe({kind:"specific",propertyIds:[]}):Se.startsWith("group:")&&fe({kind:"groups",groupIds:[Se.slice(6)]})},className:"block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-400",children:[e.jsxs("option",{value:"all",children:["All Properties · ",n.length]}),A.length>0?e.jsx("optgroup",{label:"Groups",children:A.map(z=>{const Se=ia({kind:"groups",groupIds:[z.id]},n,A).length;return e.jsx("option",{value:`group:${z.id}`,disabled:Se===0,children:Fa(z,n)},z.id)})}):null,e.jsx("option",{value:"specific",children:"Specific Properties…"})]})]})}),Y.kind==="groups"?e.jsxs("div",{className:"mt-3 max-w-2xl space-y-3",children:[e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:Y.groupIds.map(z=>{const Se=A.find(Qe=>Qe.id===z);return Se?e.jsxs("span",{className:"inline-flex min-h-11 items-center gap-1 rounded-md border border-default bg-surface px-2 text-sm text-primary",children:[Fa(Se,n),e.jsx("button",{type:"button","aria-label":`Remove ${Se.name}`,className:"-my-px -mr-2 ml-1 inline-flex min-h-11 min-w-11 items-center justify-center rounded text-secondary outline-none hover:text-heading focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>{const Qe=Y.groupIds.filter(qe=>qe!==Se.id);fe(Qe.length>0?{kind:"groups",groupIds:Qe}:{kind:"all"})},children:"×"})]},Se.id):null})}),A.some(z=>!Y.groupIds.includes(z.id)&&ia({kind:"groups",groupIds:[z.id]},n,A).length>0)?e.jsxs("label",{className:"block max-w-sm",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Add another group"}),e.jsxs("select",{"aria-label":"Add another group",value:"",onChange:z=>{z.currentTarget.value&&fe({kind:"groups",groupIds:[...Y.groupIds,z.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 focus:border-strong focus:ring-2 focus:ring-mono-400",children:[e.jsx("option",{value:"",children:"Choose a group"}),A.filter(z=>!Y.groupIds.includes(z.id)).map(z=>{const Se=ia({kind:"groups",groupIds:[z.id]},n,A).length;return e.jsx("option",{value:z.id,disabled:Se===0,children:Fa(z,n)},z.id)})]})]}):null,be===0?e.jsx("p",{role:"alert",className:"text-sm text-caution",children:"This group has no included Properties. Add Properties to the group, then try again."}):null]}):null,Y.kind==="specific"?e.jsx("div",{className:"mt-4",children:e.jsx(ci,{legend:"Specific Properties",properties:n,selectedPropertyIds:Y.propertyIds,showBulkActions:!1,onSelectedPropertyIdsChange:z=>{fe({kind:"specific",propertyIds:z})}})}):null,e.jsx("p",{className:"mt-3 max-w-2xl text-sm text-secondary",children:"Groups are shortcuts resolved when you assign. Changing membership later does not rewrite existing assignments, and a Property added later does not receive earlier group queries."})]}),re||!x?null:e.jsxs("details",{open:a.length===0,className:"border-y border-default py-4",children:[e.jsx("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:"Add queries"}),e.jsxs("div",{className:"pt-3",children:[e.jsx("h4",{className:"m-0 text-sm font-medium text-heading",children:a.length===0?"Add the queries you want to track":"Add more queries"}),e.jsx("p",{className:"mt-1 mb-2 text-sm text-secondary",children:"One per line. Add them to the project, then apply them to Properties."}),e.jsx("textarea",{"aria-label":"New queries, one per line",className:"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",rows:4,value:Z,onChange:z=>Q(z.currentTarget.value),placeholder:`best apartments in dallas
|
|
12
12
|
luxury apartments atlanta
|