@ainyc/canonry 4.186.9 → 4.187.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/assets/{AuditHistoryPanel-aXPOAK7n.js → AuditHistoryPanel-G2iVWlbn.js} +1 -1
- package/assets/assets/{BacklinksPage-Bim-7fNk.js → BacklinksPage-B13UlDT7.js} +1 -1
- package/assets/assets/{HistoryPage-B8RyIjRC.js → HistoryPage-DZoRKfzJ.js} +1 -1
- package/assets/assets/{MeasurementPropertyPage-BlxY3qHW.js → MeasurementPropertyPage-DNxsAgEA.js} +1 -1
- package/assets/assets/{ProjectPage-BMZrEjBE.js → ProjectPage-BdfsfLkU.js} +1 -1
- package/assets/assets/{RunRow-B28gp-6g.js → RunRow-C9u35nrm.js} +1 -1
- package/assets/assets/{RunsPage-BXm6DVdt.js → RunsPage-DST-BpAu.js} +1 -1
- package/assets/assets/{SettingsPage-CJX7c5HH.js → SettingsPage-BC05JomS.js} +1 -1
- package/assets/assets/SiteHealthSection-DIeYA2HJ.js +4 -0
- package/assets/assets/{TrafficPage-wPdIYn8H.js → TrafficPage-DezdhoxL.js} +1 -1
- package/assets/assets/{TrafficSourceDetailPage-C813qZsA.js → TrafficSourceDetailPage-C0FIPjXi.js} +1 -1
- package/assets/assets/{extract-error-message-C3RpUAm_.js → extract-error-message-B5OYNTJO.js} +1 -1
- package/assets/assets/{index-Dr_-IUJz.js → index-DJWMbOc5.js} +18 -18
- package/assets/assets/{react-sigma_core.esm.min-LmiGNvR6.js → react-sigma_core.esm.min-B06R8tYw.js} +1 -1
- package/assets/index.html +1 -1
- package/dist/{chunk-U3M2VALC.js → chunk-5BUAG4CN.js} +8 -0
- package/dist/{chunk-O26JKJXV.js → chunk-B7WQ5Z4L.js} +22 -6
- package/dist/{chunk-XD2ZD2BP.js → chunk-IPALTNIE.js} +1 -1
- package/dist/cli.js +3 -3
- package/dist/index.d.ts +4 -2
- package/dist/index.js +2 -2
- package/dist/mcp.js +2 -2
- package/package.json +10 -10
- package/assets/assets/SiteHealthSection-Ys8sVumO.js +0 -4
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{j as e,r as l,u as we,L as vs,h as js,o as Pt,B as Rr,C as Il,k as $l,l as Tl,D as Ml}from"./vendor-tanstack-CYBjbqVr.js";import{T as ce,t as Ll,a as El,M as fo,I as Me,s as yo,B as A,b as ql,u as bo,C as Dl,P as Cn,h as Ol,c as Fl,d as dn,g as vo,e as jo,f as xe,i as H,j as te,k as Nt,l as qe,m as Gl,n as Kl,o as _l,p as No,q as Ul,r as Bl,S as un,v as Vl,w as zl,x as Ds,y as Bt,z as Ql,A as Xr,D as wo,G as Dt,E as Ir,F as Hl,H as Wl,J as Yl,K as Jl,L as Zr,N as Se,O as Xl,Q as Zl,R as Ea,U as ec,V as tc,W as sc,X as nc,Y as ac,Z as rc,_ as ic,$ as oc,a0 as lc,a1 as cc,a2 as dc,a3 as uc,a4 as mc,a5 as hc,a6 as xc,a7 as So,a8 as zs,a9 as pc,aa as Co,ab as ba,ac as gc,ad as De,ae as fc,af as yc,ag as bc,ah as va,ai as vc,aj as jc,ak as Nc,al as hn,am as wc,an as Sc,ao as Cc,ap as ko,aq as hr,ar as kc,as as Ao,at as Ac,au as _n,av as Qs,aw as Vt,ax as ei,ay as Pc,az as Rc,aA as Hn,aB as Ic,aC as $c,aD as Tc,aE as Mc,aF as Lc,aG as Gn,aH as mn,aI as Ec,aJ as Po,aK as qc,aL as Dc,aM as Oc,aN as ti,aO as Fc,aP as Gc,aQ as Kc,aR as _c,aS as Uc,aT as Bc,aU as Vc,aV as zc,aW as Qc,aX as Hc,aY as Wc,aZ as Yc,a_ as Jc,a$ as Xc,b0 as Zc,b1 as ed,b2 as td,b3 as sd,b4 as nd,b5 as ad,b6 as rd,b7 as id,b8 as od,b9 as ld,ba as cd,bb as dd,bc as ud,bd as md,be as ys,bf as hd,bg as lt,bh as xd,bi as pd,bj as gd,bk as fd,bl as yd,bm as bd,bn as vd,bo as jd,bp as Nd,bq as wd,br as Sd,bs as Cd,bt as kd,bu as Ad,bv as Pd,bw as Rd,bx as Id,by as $d,bz as Td,bA as Md,bB as Ld,bC as Ed,bD as qd,bE as Dd,bF as Od,bG as Fd,bH as Gd,bI as Kd,bJ as _d,bK as Ud,bL as Bd,bM as Vd,bN as zd,bO as Qd,bP as Hd,bQ as Wd,bR as Yd,bS as Jd,bT as Xd,bU as Ro,bV as qa,bW as Zd,bX as si,bY as eu,bZ as tu,b_ as su,b$ as nu,c0 as au,c1 as ru,c2 as iu,c3 as Io,c4 as ou,c5 as lu,c6 as cu,c7 as du,c8 as uu,c9 as mu,ca as hu,cb as xu,cc as ni,cd as pu,ce as gu,cf as fu,cg as yu,ch as bu,ci as vu,cj as ju,ck as Nu,cl as wu,cm as Su,cn as Cu,co as ku,cp as Au,cq as Pu,cr as Ru,cs as ja,ct as Iu,cu as Da,cv as $u,cw as Tu,cx as Mu,cy as Lu,cz as Eu,cA as qu,cB as Du,cC as Ou,cD as Fu,cE as Gu,cF as $o,cG as Ku,cH as _u,cI as Uu,cJ as Bu,cK as Vu,cL as zu,cM as Zn,cN as Qu,cO as Hu,cP as Wu,cQ as ai,cR as Yu}from"./index-Dr_-IUJz.js";import{C as Hs,e as Ju,q as Na,U as Xu,r as Zu,L as em,s as tm,i as sm,P as Un,D as To,t as nm,u as am,E as rm,p as im,v as om,w as Mo}from"./vendor-lucide-BovNTc41.js";import{R as lm}from"./RunRow-B28gp-6g.js";import{u as xn,D as Us,a as Rs,b as Lo,M as xa,c as Ss,S as cm}from"./SiteHealthSection-Ys8sVumO.js";import{C as Bn,f as pn,a as is,b as Rt,c as Ot,d as as,e as nt,g as os,h as Is,M as Eo,i as qo,o as $s,j as Bs,p as dm}from"./ChartPrimitives-DLEICrrL.js";import{u as um,a as mm,b as hm,t as xm,e as pm,c as mt}from"./extract-error-message-C3RpUAm_.js";import{R as Ws,C as Ys,a as Vn,X as Js,Y as Xs,T as Zs,b as xr,L as wa,A as Fs,d as As,e as gm}from"./vendor-recharts-FA0uySU7.js";import{A as fm}from"./AuditHistoryPanel-aXPOAK7n.js";import{a as ym,b as bm}from"./v2-overview-adapter-COMP5UGt.js";import"./vendor-radix-BpmvLvpp.js";import"./vendor-markdown-9tTeP8v7.js";import"./vendor-yaml-GWJz5H2G.js";function Vs(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 vm(t,s,n=800){const a=[];if(!/^\d{4}-\d{2}-\d{2}$/.test(t)||!/^\d{4}-\d{2}-\d{2}$/.test(s))return a;for(let r=t;r<=s&&(a.push(r),!(a.length>=n));r=jm(r,1));return a}function jm(t,s){if(!Number.isFinite(s))return t;const n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t);if(!n?.[1]||!n[2]||!n[3])return t;const a=new Date(Date.UTC(Number(n[1]),Number(n[2])-1,Number(n[3])+Math.trunc(s)));if(Number.isNaN(a.getTime()))return t;const r=a.getUTCFullYear(),o=String(a.getUTCMonth()+1).padStart(2,"0"),i=String(a.getUTCDate()).padStart(2,"0");return`${r}-${o}-${i}`}function Nm(t,s){if(!Number.isFinite(t)||!Number.isFinite(s)||s<=0)return null;const n=(t-s)/s;return Number.isFinite(n)?n:null}function wm(t,s){const n=Nm(t,s);return n===null?null:Math.round(n*100)}function Oa(t,s,n="vs prior 7 days"){return t.deltaPct===null?t.prior===0?"First baseline week":"":t.deltaPct>0?`Up ${t.deltaPct}% ${n} (${Vs(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${Vs(t.prior)} ${s})`:`Flat ${n} (${Vs(t.prior)} ${s})`}const Do=30;function ri(t){return Math.round(t*10)/10}function Sm(t){return t.prior>=Do&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% vs prior`:`${t.deltaAbs>0?"+":""}${ri(t.deltaAbs)} vs ${ri(t.prior)}`}function Cm(t,s,n){return t.prior>=Do&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% ${n}`:`${t.deltaAbs>0?"+":""}${Vs(Math.round(t.deltaAbs))} ${s} ${n}`}const km=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function Oo(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function Fo(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 Go(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(Oo).map(Fo).filter(Boolean)):new Set}function Ko(t,s){const n=Oo(t).map(Fo).filter(Boolean).filter(a=>!km.has(a)).filter(a=>!s.has(a));return[...new Set(n)].sort().join(" ")}function Am(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function Pm(t,s){const n=Go(t);if(s.length<=1||n.size===0)return[...s];const a=new Set,r=[];for(const o of s){if(o.category!=="content"){r.push(o);continue}const i=Ko(Am(o),n);!i||a.has(i)||(a.add(i),r.push(o))}return r}function Rm(t){const s=Go(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const a=new Set;return n.filter(r=>{const o=Ko(r.query,s);return!o||a.has(o)?!1:(a.add(o),!0)})}const Im=1e6;function $m(t,s="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:s}).format(t/Im)}const _o={queryClass:"all"},Tm=["all","non-brand","branded"];function Mm(t){return typeof t=="string"&&Tm.includes(t)}function Uo(t){const s=Mm(t.class)?t.class:_o.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 Lm(t,s){return s===null||t===null?!1:t!==s}function Em(t){return{scope:t.scope==="group"&&t.groupKey?`group:${t.groupKey}`:void 0,class:t.queryClass===_o.queryClass?void 0:t.queryClass}}function qm(t,s){if(!(typeof t!="string"||t.length>16384||!s))try{const n=JSON.parse(t);if(typeof n!="object"||n===null||Array.isArray(n))return;const a=n,r=i=>typeof i=="string"&&i.trim().length>0,o=i=>i===null||r(i);return a.queryKey!==s||!r(a.provider)||a.queryClass!=="branded"&&a.queryClass!=="non-brand"&&a.queryClass!=="unknown"||!o(a.model)||!o(a.location)||!o(a.runId)||a.revision!==null&&(typeof a.revision!="number"||!Number.isSafeInteger(a.revision)||a.revision<=0)?void 0:{queryKey:s,queryClass:a.queryClass,provider:a.provider,model:a.model,location:a.location,runId:a.runId,revision:a.revision}}catch{return}}function Dm(t){const s=h=>typeof t[h]=="string"&&t[h]!==""?t[h]:void 0,n=Uo({scope:s("scope"),class:s("class")}),a=s("measurementScope")??(n.scope==="group"?"group":"project"),r=s("measurementScopeKey")??(s("measurementScope")?void 0:n.groupKey),o=s("queryClass")??s("class"),i={measurementScope:r&&(a==="group"||a==="market"||a==="property")?a:"project",queryClass:o==="all"||o==="branded"||o==="unknown"?o:"non-brand"};i.measurementScope!=="project"&&(i.measurementScopeKey=r);for(const[h,m]of[["measurementProvider","provider"],["measurementModel","model"],["measurementLocation","location"],["measurementFrom","from"],["measurementTo","to"],["measurementRunId","measurementRunId"],["measurementQueryKey","queryKey"]]){const x=s(h);x!==void 0&&(i[m]=x)}const c=Number(t.measurementRevision);Number.isSafeInteger(c)&&c>0&&(i.revision=c);const u=qm(t.measurementAnswer,i.queryKey);return u&&(i.answer=u),i}function Om(t,s){const n={...t,...s};return["measurementScope","measurementScopeKey","queryClass","measurementProvider","measurementModel","measurementLocation","measurementFrom","measurementTo","measurementRevision","measurementRunId"].some(a=>a in s)?(n.measurementQueryKey=void 0,n.measurementAnswer=void 0):"measurementQueryKey"in s&&!("measurementAnswer"in s)&&(n.measurementAnswer=void 0),"measurementScope"in s&&(n.scope=void 0,n.measurementQueryKey=void 0,s.measurementScope==="project"&&(n.measurementScopeKey=void 0)),"queryClass"in s&&(n.class=void 0),n}function pr({state:t,label:s}){return e.jsx(ce,{tone:El(t),children:s??Ll(t)})}const tn=[{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],ii={"non-brand":"Non-brand",branded:"Branded",pooled:"All queries"},Fm={"non-brand":"On queries that do not contain your name: of the brand names written into the answer text, the share that were yours. Branded queries are scored separately because you are named on nearly all of them and a competitor cannot be.",branded:"On queries that contain your name: of the brand names written into the answer text, the share that were yours. This is recognition, not competitive placement, and it is never pooled with the non-brand figure.",pooled:"This project has no brand name or domain to match on, so branded and non-brand queries could not be separated. This figure pools both and is not a competitive read. Set a display name or aliases to split them."},Gm="Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other.";function Km(t,s){if(s.unavailable)return{headline:"No data",numeric:!1,detail:"could not load, refresh to retry",showRows:!1};if(s.noRun)return{headline:"No data",numeric:!1,detail:"no sweep has run yet",showRows:!1};if(t.snapshotsTotal===0)return s.otherClassHasData?{headline:"No non-brand queries",numeric:!1,detail:"every tracked query names your brand",showRows:!1}:{headline:"No queries",numeric:!1,detail:"none tracked",showRows:!1};if(t.snapshotsWithAnswerText===0)return{headline:"No answers",numeric:!1,detail:"no answer text in this run",showRows:!1};if(!s.hasCompetitors)return{headline:"Add competitors",numeric:!1,detail:`you were named in ${t.projectMentionSnapshots} of ${t.snapshotsWithAnswerText} answers`,showRows:!1};const n=t.projectMentionSnapshots+t.competitorMentionSnapshots;return n===0||t.score===null?{headline:"No mentions",numeric:!1,detail:`no brand named in ${t.snapshotsWithAnswerText} answers`,showRows:!1}:{headline:`${t.score}`,numeric:!0,detail:`${t.projectMentionSnapshots} of ${n} brand mentions`,showRows:!0}}function _m({breakdown:t,projectLabel:s,competitorDomains:n}){const a=t.projectMentionSnapshots+t.competitorMentionSnapshots;if(a===0)return null;const r=new Map(t.perCompetitor.map(i=>[i.domain,i.mentionSnapshots])),o=[{label:`${s} (you)`,mentions:t.projectMentionSnapshots,isYou:!0},...n.map(i=>({label:i,mentions:r.get(i)??0,isYou:!1}))].sort((i,c)=>c.mentions-i.mentions||(i.label<c.label?-1:1));return e.jsxs("table",{className:"mention-share-table",children:[e.jsx("caption",{className:"sr-only",children:"Brand mentions by domain, most mentioned first"}),e.jsx("thead",{children:e.jsxs("tr",{className:"mention-share-row mention-share-row-head",children:[e.jsx("th",{scope:"col",className:"mention-share-row-label",children:"Domain"}),e.jsx("th",{"aria-hidden":"true"}),e.jsxs("th",{scope:"col",className:"mention-share-count",children:["Mentions",e.jsx(Me,{text:Gm})]}),e.jsx("th",{scope:"col",className:"mention-share-share",children:"Share"})]})}),e.jsx("tbody",{className:"mention-share-rows",children:o.map(i=>{const c=i.mentions/a*100;return e.jsxs("tr",{className:"mention-share-row",children:[e.jsx("th",{scope:"row",className:`mention-share-row-label ${i.isYou?"text-heading font-medium":"text-secondary"}`,children:i.label}),e.jsx("td",{"aria-hidden":"true",children:e.jsx("div",{className:"mention-share-bar",children:e.jsx("div",{className:`mention-share-bar-fill ${i.isYou?"bg-positive-500/70":"bg-mono-500/60"}`,style:{width:`${c>0?Math.max(c,1.5):0}%`}})})}),e.jsx("td",{className:"mention-share-count",children:i.mentions}),e.jsxs("td",{className:"mention-share-share",children:[c.toFixed(1),"%"]})]},i.label)})})]})}function Um({summary:t,projectLabel:s,competitorDomains:n}){const[a,r]=l.useState("non-brand"),o=l.useId(),i=t.scope==="pooled",c=!i&&t.branded.snapshotsTotal>0,u=c?a:"non-brand",h=i?"pooled":u,m=u==="branded"?t.branded:t.breakdown,x=u==="branded"?t.breakdown:t.branded,g=Km(m,{hasCompetitors:n.length>0,unavailable:t.unavailable===!0,noRun:t.breakdown.snapshotsTotal===0&&t.branded.snapshotsTotal===0,otherClassHasData:x.snapshotsTotal>0}),d=h==="non-brand"?fo[t.tone]:"text-secondary";function f(y){const j=tn.findIndex(P=>P.value===u);let N=null;y.key==="ArrowRight"||y.key==="ArrowDown"?N=(j+1)%tn.length:y.key==="ArrowLeft"||y.key==="ArrowUp"?N=(j-1+tn.length)%tn.length:y.key==="Home"?N=0:y.key==="End"&&(N=tn.length-1),N!==null&&(y.preventDefault(),r(tn[N].value),y.currentTarget.querySelectorAll('[role="radio"]')[N]?.focus())}return e.jsxs("div",{className:"mention-share",children:[e.jsxs("div",{className:"mention-share-head",children:[e.jsxs("div",{className:"mention-share-label",children:[e.jsx("h3",{id:o,className:"mention-share-label-text",children:"Mention share"}),e.jsx(Me,{text:Fm[h]})]}),c?e.jsx("div",{role:"radiogroup","aria-labelledby":o,className:"segmented flex-wrap",onKeyDown:f,children:tn.map(y=>{const j=y.value===u;return e.jsx("button",{type:"button",role:"radio","aria-checked":j,tabIndex:j?0:-1,onClick:()=>r(y.value),className:`segmented-option min-h-11 ${j?"segmented-option-active":""}`,children:y.label},y.value)})}):e.jsx("span",{className:"mention-share-class",children:ii[h]})]}),g.numeric?e.jsxs("p",{className:`mention-share-value ${d}`,children:[g.headline,e.jsx("span",{className:"text-faint",children:"%"})]}):e.jsx("p",{className:"mention-share-value-text",children:g.headline}),e.jsxs("p",{className:"mention-share-caption",children:[e.jsx("span",{className:"mention-share-caption-scope",children:ii[h]}),` · ${g.detail}`]}),i&&e.jsx("p",{className:"mention-share-note",children:"Set a brand name to split branded from non-brand."}),g.showRows&&e.jsx(_m,{breakdown:m,projectLabel:s,competitorDomains:n})]})}const sn=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],oi=5;function Bm(t){switch(t){case"non-brand":return"Counts queries that do not name your brand.";case"branded":return"Counts queries that name your brand.";default:return"Counts every tracked query, so share of voice is not shown."}}function Vm(t){return t?t.evidence.answeredResults>0||t.evidence.sourceResults>0?"measured":"not-measured":"unavailable"}function Fa(t){return t==="unavailable"?"Unavailable":"Not measured"}function Bo(t){switch(t){case"own":return"Your domain";case"direct-competitor":return"Competitor";case"ota-aggregator":return"Aggregator";case"editorial-media":return"Editorial";case"other":return"Other";default:return"Unclassified"}}function zm({value:t,onChange:s}){function n(a){const r=sn.findIndex(c=>c.value===t);let o=null;if(a.key==="ArrowRight"||a.key==="ArrowDown"?o=(r+1)%sn.length:a.key==="ArrowLeft"||a.key==="ArrowUp"?o=(r-1+sn.length)%sn.length:a.key==="Home"?o=0:a.key==="End"&&(o=sn.length-1),o===null)return;a.preventDefault();const i=sn[o];s(i.value),a.currentTarget.querySelectorAll('[role="radio"]')[o].focus()}return e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"block text-sm font-medium text-heading",children:"History"}),e.jsx("div",{role:"radiogroup","aria-label":"Competitor history window",className:"segmented",onKeyDown:n,children:sn.map(a=>{const r=a.value===t;return e.jsx("button",{type:"button",role:"radio","aria-checked":r,tabIndex:r?0:-1,onClick:()=>s(a.value),className:`segmented-option min-h-11 ${r?"segmented-option-active":""}`,children:a.label},a.value)})})]})}function gr({row:t,isProject:s=!1,metricState:n="measured",shareContext:a,canManage:r,onPin:o,onUnpin:i}){const c=!s&&r&&!t.pinned&&!!o,u=!s&&r&&t.pinned&&!!i,h=n==="measured",m=h&&t.sampleUrls.length>0,[x,g]=l.useState(!1),[d,f]=l.useState(null);async function y(j,N){if(!(!N||x)){g(!0),f(null);try{await N(t.domain)===!1&&f(`Could not ${j} competitor. Try again.`)}catch{f(`Could not ${j} competitor. Try again.`)}finally{g(!1)}}}return e.jsxs("tr",{children:[e.jsxs("th",{scope:"row",className:"font-medium text-heading",children:[t.label,s?e.jsx("span",{className:"ml-1 text-secondary",children:"(you)"}):null]}),e.jsx("td",{className:"text-secondary",children:s?"Your brand":Bo(t.surfaceClass)}),e.jsx("td",{className:"tabular-nums text-strong",children:h?ql(t.shareOfVoice,a):Fa(n)}),e.jsx("td",{className:"tabular-nums text-secondary",children:h?t.mentionCount:Fa(n)}),e.jsx("td",{className:"tabular-nums text-secondary",children:h?t.citationCount:Fa(n)}),e.jsx("td",{className:"text-right",children:c||u||m?e.jsxs("div",{className:"flex min-w-max items-start justify-end gap-2",children:[m?e.jsxs("details",{className:"inline-disclosure text-left text-xs text-secondary",children:[e.jsx("summary",{children:"Source URLs"}),e.jsx("ul",{className:"mt-2 max-w-72 space-y-1 font-mono text-[11px] font-normal",children:t.sampleUrls.map(j=>e.jsx("li",{className:"break-all",children:j},j))})]}):null,u&&i?e.jsxs(A,{type:"button",size:"sm",variant:"outline",disabled:x,onClick:()=>{y("unpin",i)},children:["Unpin"," ",e.jsx("span",{className:"sr-only",children:t.domain})]}):null,c&&o?e.jsxs(A,{type:"button",size:"sm",variant:"outline",disabled:x,onClick:()=>{y("pin",o)},children:["Pin"," ",e.jsx("span",{className:"sr-only",children:t.domain})]}):null,d?e.jsx("span",{role:"alert",className:"sr-only",children:d}):null]}):e.jsx("span",{className:"text-faint",children:"—"})})]})}function fr({children:t}){return e.jsx("tr",{className:"competitor-landscape-group",children:e.jsx("th",{scope:"rowgroup",colSpan:6,children:t})})}function Qm({rows:t,shareContext:s,canManage:n,onPin:a}){const[r,o]=l.useState(!1),i=r?t:t.slice(0,oi);return e.jsxs("tbody",{children:[e.jsx(fr,{children:"Observed in this window"}),i.map(c=>e.jsx(gr,{row:{...c,pinned:!1},shareContext:s,canManage:n,onPin:a},c.domain)),t.length>oi?e.jsx("tr",{children:e.jsx("td",{colSpan:6,children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("span",{className:"text-sm text-secondary",children:["Showing ",i.length," of ",t.length," observed competitors."]}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11 text-sm","aria-expanded":r,"aria-label":r?"Show fewer observed competitors":`Show all ${t.length} observed competitors`,onClick:()=>o(c=>!c),children:r?"Show fewer":`Show all ${t.length}`})]})})}):null]})}function Hm({onAddCompetitor:t}){const s=l.useId(),[n,a]=l.useState(""),[r,o]=l.useState(!1),[i,c]=l.useState(null);async function u(){const h=n.trim();if(!(!h||r)){o(!0),c(null);try{if(await t(h)===!1){c("Could not add competitor. Try again.");return}a("")}catch{c("Could not add competitor. Try again.")}finally{o(!1)}}}return e.jsxs("details",{className:"inline-disclosure competitor-landscape-manage",children:[e.jsx("summary",{children:"Manage competitors"}),e.jsxs("form",{className:"mt-3 flex flex-wrap items-end gap-2",onSubmit:h=>{h.preventDefault(),u()},"aria-busy":r,children:[e.jsxs("label",{htmlFor:s,className:"min-w-56 flex-1 text-sm font-medium text-heading",children:["Competitor domain",e.jsx("input",{id:s,type:"text",value:n,onChange:h=>a(h.target.value),placeholder:"competitor.com",className:"mt-1 h-10 w-full rounded-md border border-default bg-surface px-3 text-sm text-primary placeholder-mono-600 focus:outline-none focus:ring-2 focus:ring-mono-400"})]}),e.jsx(A,{type:"submit",size:"sm",className:"min-h-10",disabled:r||!n.trim(),children:r?"Adding…":"Add competitor"}),i?e.jsx("p",{role:"alert",className:"w-full text-sm text-negative",children:i}):null]})]})}function Wm({window:t,landscape:s,pinnedFallback:n=[],canWrite:a,isEmbed:r,onWindowChange:o,onPin:i,onUnpin:c,onAddCompetitor:u,error:h,onRetry:m,isLoading:x=!1,scopeLabel:g}){const d=a&&!r,f=s?.pinned??n,y=s?.observed??[],j=s?.otherSources??[],N=s?.evidence,P=Vm(s),M=s?.marketState?.draft?.pendingCompetitorDomains.length??0;return e.jsxs("section",{"aria-labelledby":"competitor-landscape-title","aria-busy":x,className:"competitor-landscape",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Competitive"}),e.jsx("h2",{id:"competitor-landscape-title",children:"Competitor landscape"}),g?e.jsx("p",{className:"supporting-copy mt-1",children:g}):null,s?e.jsx("p",{className:"supporting-copy mt-1",children:Bm(s.filters?.queryClass)}):null,s?.reason?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:yo(s.reason)}):null]}),e.jsx(zm,{value:t,onChange:o})]}),h?e.jsxs("div",{role:"alert",className:"flex flex-wrap items-center gap-3 border-y border-negative-800/40 bg-negative-950/20 py-3 text-sm text-negative",children:[e.jsx("span",{children:h}),m?e.jsx(A,{type:"button",size:"sm",variant:"outline",onClick:m,children:"Retry competitor history"}):null]}):null,x&&!s&&f.length===0?e.jsx("div",{role:"status","aria-live":"polite",className:"h-48 animate-pulse rounded-md bg-surface-subtle",children:e.jsx("span",{className:"sr-only",children:"Loading competitor history"})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"competitor-table-wrap",children:e.jsxs("table",{className:"competitor-table","aria-label":"Competitor landscape",children:[e.jsx("caption",{className:"sr-only",children:"Pinned competitors followed by competitors observed in the selected history window."}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Competitor"}),e.jsx("th",{scope:"col",children:"Type"}),e.jsx("th",{scope:"col",children:"Share of voice"}),e.jsx("th",{scope:"col",children:"Mentions"}),e.jsx("th",{scope:"col",children:"Citations"}),e.jsx("th",{scope:"col",children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsxs("tbody",{children:[s?e.jsxs(e.Fragment,{children:[e.jsx(fr,{children:"You"}),e.jsx(gr,{row:s.project,shareContext:s,isProject:!0,metricState:P,canManage:!1})]}):null,e.jsx(fr,{children:"Pinned"}),f.length>0?f.map(k=>e.jsx(gr,{row:{...k,pinned:!0},shareContext:s,metricState:P,canManage:d,onUnpin:c},k.domain)):e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"text-secondary",children:"No pinned competitors."})})]}),s&&y.length>0?e.jsx(Qm,{shareContext:s,rows:y,canManage:d,onPin:i},JSON.stringify([t,s.project.domain,s.scope,s.filters])):null]})}),N?e.jsxs("details",{className:"group text-sm text-secondary",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer list-none flex-wrap items-center justify-between gap-x-4 gap-y-1 rounded-md hover:text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500 [&::-webkit-details-marker]:hidden",children:[e.jsxs("span",{className:"flex flex-wrap items-center gap-x-4 gap-y-1",children:[e.jsxs("span",{children:[N.answeredResults," ",N.answeredResults===1?"answer":"answers"]}),N.missingAnswerTextResults>0?e.jsx("span",{className:"text-caution",children:"Answer data incomplete"}):null,N.incompleteSourceResults>0?e.jsx("span",{className:"text-caution",children:"Citation data incomplete"}):null]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:["About these results",e.jsx(Hs,{size:14,"aria-hidden":"true",className:"transition-transform group-open:rotate-180 motion-reduce:transition-none"})]})]}),e.jsxs("div",{className:"max-w-prose space-y-2 pb-2 pt-1",children:[y.length===0?e.jsx("p",{children:"No additional competitors were identified in this period."}):null,e.jsxs("p",{children:[N.sourceResults," ",N.sourceResults===1?"result includes":"results include"," source URLs."]}),N.missingAnswerTextResults>0?e.jsxs("p",{children:[N.missingAnswerTextResults," ",N.missingAnswerTextResults===1?"result has":"results have"," no answer text and ",N.missingAnswerTextResults===1?"is":"are"," excluded from mention share."]}):null,N.incompleteSourceResults>0?e.jsxs("p",{children:[N.incompleteSourceResults," ",N.incompleteSourceResults===1?"result has an incomplete source list":"results have incomplete source lists",". Recorded citations still count; missing citations are not treated as confirmed misses."]}):null,N.excludedProbeResults+N.excludedNonCompletedResults>0?e.jsxs("p",{children:[N.excludedProbeResults+N.excludedNonCompletedResults," test or unfinished ",N.excludedProbeResults+N.excludedNonCompletedResults===1?"result is":"results are"," excluded."]}):null,s.truncated?e.jsx("p",{children:"Lists include up to 100 observed competitors and 100 other sources. All pinned competitors are included."}):null]})]}):null,M>0?e.jsx("p",{className:"text-sm text-secondary",children:s?.scope.kind==="all-markets"?`${M} competitor${M===1?" is":"s are"} pending publication across markets.`:`${M} competitor${M===1?" is":"s are"} pending publication for this market.`}):null,(s?.observedNames?.length??0)>0?e.jsxs("details",{className:"inline-disclosure text-sm text-secondary",children:[e.jsx("summary",{children:"Names observed in answers"}),e.jsx("p",{children:"Names are observations. Only classified competitor domains enter share of voice."}),e.jsx("ul",{children:s?.observedNames?.map(k=>e.jsxs("li",{children:[k.name," · ",k.answerCount," answers"]},k.name))})]}):null,j.length>0?e.jsxs("details",{className:"inline-disclosure",children:[e.jsxs("summary",{children:["Other observed sources (",j.length,")"]}),e.jsx("ul",{className:"mt-3 space-y-2 text-sm text-secondary",children:j.map(k=>e.jsxs("li",{children:[e.jsxs("span",{children:[k.label," · ",Bo(k.surfaceClass)," · ",k.citationCount," citations"]}),k.sampleUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1 font-mono text-[11px] text-muted",children:k.sampleUrls.map(p=>e.jsx("li",{className:"break-all",children:p},p))}):null]},k.domain))})]}):null]}),d&&u?e.jsx(Hm,{onAddCompetitor:u}):null]})}function li({history:t,maxDots:s=12}){const n=t.slice(-s);if(n.length===0)return e.jsx("span",{className:"text-[11px] text-faint",children:"No data"});const a={cited:"bg-positive-400","not-cited":"bg-mono-600",lost:"bg-negative-400",emerging:"bg-caution-400 ring-1 ring-caution-300/60"},r={cited:"rounded-full","not-cited":"rounded-sm",lost:"rotate-45 rounded-[1px]",emerging:"rounded-full"},o=n.length-1,i=new Date(n[0].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),c=new Date(n[o].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),u=n.map((h,m)=>{const x=new Date(h.createdAt).toLocaleDateString();return`${m===o?"Latest run, ":""}${x}: ${h.citationState}${h.model?`, model ${h.model}`:""}`}).join("; ");return e.jsxs("div",{className:"flex items-center gap-1",role:"img","aria-label":`Citation history across ${n.length} runs. ${u}`,children:[e.jsx("span",{className:"text-[9px] text-faint shrink-0","aria-hidden":"true",children:i}),e.jsx("div",{className:"flex items-center gap-[3px]",title:`${n.length} runs`,"aria-hidden":"true",children:n.map((h,m)=>{const x=!!(h.model&&m>0&&n[m-1]?.model&&n[m-1].model!==h.model),g=m===o;return e.jsx("span",{className:`h-2.5 w-2.5 ${r[h.citationState]??"rounded-sm"} ${a[h.citationState]??"bg-mono-700"} ${x?"ring-1 ring-caution-300/80 ring-offset-1 ring-offset-bg":""} ${g?"outline outline-1 outline-offset-2 outline-mono-400":""}`,title:[h.citationState,new Date(h.createdAt).toLocaleDateString(),h.model?`model ${h.model}`:null,x?"model changed":null,g?"latest run":null].filter(Boolean).join(" · ")},`${h.runId}:${h.createdAt}`)})}),e.jsxs("span",{className:"text-[9px] shrink-0 text-secondary","aria-hidden":"true",children:[c," ",e.jsx("span",{className:"text-faint",children:"latest"})]})]})}function yr(t){const s=new Map;for(const a of t)for(const r of a.runHistory){const o=s.get(r.createdAt);o?o.states.push(r.citationState):s.set(r.createdAt,{states:[r.citationState],runId:r.runId})}return[...s.entries()].sort(([a],[r])=>a.localeCompare(r)).map(([a,{states:r,runId:o}])=>({runId:o,createdAt:a,citationState:r.includes("cited")?"cited":r.includes("emerging")?"emerging":"not-cited"}))}const Ym=320;function Jm(t){return t==="branded"?"Branded":t==="non-brand"?"Non-brand":"Unclassified"}function Xm(t){return[t.phrase,t.location??"",...t.rawItems.map(s=>s.provider)].join(" ")}function ci(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 di(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 ui(t,s){const n=s==="mentions"?"mentioned":"cited",a=s==="mentions"?"Mentioned":"Cited";if(t.length===0)return"Awaiting first run";if(t.length===1)return"First observation";const r=t[t.length-1].citationState,o=t[t.length-2].citationState;if(o!=="cited"&&r==="cited")return`Newly ${n}`;if(o==="cited"&&r!=="cited")return"Lost since last run";let i=0;for(let c=t.length-1;c>=0&&t[c].citationState===r;c--)i++;return r==="cited"?i<=1?`${a} in latest run`:`${a} for ${i} runs`:i<=1?`Not ${n} in latest run`:`Not ${n} across ${i} runs`}function Zm(t,s){return t.map(n=>Vo(n,s))}function Vo(t,s){return s==="citations"?t:{...t,citationState:ci(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:ci(n,s)}))}}function mi(t,s){const n=s==="mentions"?"mention":"citation",a=s==="mentions"?"Mention":"Citation";if(t.length===0)return{key:s,label:`${a} pending`,tone:"pending"};const r=t[t.length-1].citationState,o=t.length>=2?t[t.length-2].citationState:null,i=r==="cited"||r==="emerging",c=o==="cited"||o==="emerging";return r==="lost"||o!==null&&c&&!i?{key:s,label:`Lost ${n}`,tone:"negative"}:r==="emerging"||o!==null&&!c&&i?{key:s,label:`New ${n}`,tone:"positive"}:o===null&&i?{key:s,label:`First ${n}`,tone:"positive"}:i?{key:s,label:s==="mentions"?"Still mentioned":"Still cited",tone:"neutral"}:{key:s,label:`No ${n}`,tone:"neutral"}}function eh(t){const s=yr(Zm(t,"mentions")),n=yr(t);return[mi(s,"mentions"),mi(n,"citations")]}function th({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 hi({items:t}){return e.jsx("div",{className:"mt-1 flex flex-wrap gap-1","aria-label":"Latest run mention and citation signals",children:eh(t).map(s=>e.jsx(th,{signal:s},s.key))})}function sh({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:a}=bo(),[r,o]=l.useState(new Set),[i,c]=l.useState("mentions"),[u,h]=l.useState(n),[m,x]=l.useState("all"),g=l.useMemo(()=>{const p=new Map;for(const v of t){const S=v.query,$=v.queryClass??null,q=s?v.location??null:null,L=JSON.stringify([S,$,q]),Q=p.get(L)??{key:L,phrase:S,queryClass:$,location:q,items:[],rawItems:[]};Q.items.push(Vo(v,i)),Q.rawItems.push(v),p.set(L,Q)}return[...p.values()]},[t,i,s]),d=l.useMemo(()=>g.filter(p=>m==="all"||(m==="unclassified"?p.queryClass===null:p.queryClass===m)),[g,m]),f=xn({rows:d,getSearchText:Xm}),y=f.rows.map(p=>p.key),j=y.length>0&&y.every(p=>r.has(p)),N=p=>{o(v=>{const S=new Set(v);return S.has(p)?S.delete(p):S.add(p),S})},P=i==="mentions"?"mentioned":"cited",M=i==="mentions"?"Mention History":"Citation History",k=i==="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":i==="mentions",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${i==="mentions"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>c("mentions"),children:"Mentions"}),e.jsx("button",{type:"button",role:"tab","aria-selected":i==="citations",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${i==="citations"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>c("citations"),children:"Citations"})]}),e.jsx("span",{className:"text-[11px] text-muted",children:i==="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:()=>{o(p=>{const v=new Set(p);for(const S of y)j?v.delete(S):v.add(S);return v})},children:j?"Collapse page":"Expand page"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Density"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-bg-elevated/60 border border-subtle",role:"tablist","aria-label":"Evidence row density",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":u==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${u==="compact"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>h("compact"),children:"Compact"}),e.jsx("button",{type:"button",role:"tab","aria-selected":u==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${u==="detailed"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>h("detailed"),children:"Detailed"})]})]})]})]}),g.length>0?e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-3",children:[e.jsx(Us,{value:f.query,onChange:f.setQuery,label:"Filter tracked queries",placeholder:"Filter query, location, or provider",className:"w-full max-w-md"}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-secondary",children:["Query class",e.jsxs("select",{value:m,onChange:p=>{x(p.target.value),f.setPage(1)},className:"h-9 rounded-md border border-default bg-surface px-3 text-sm text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500",children:[e.jsx("option",{value:"all",children:"All queries"}),e.jsx("option",{value:"branded",children:"Branded"}),e.jsx("option",{value:"non-brand",children:"Non-brand"}),e.jsx("option",{value:"unclassified",children:"Unclassified"})]})]})]}):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:M}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:f.rows.map(({key:p,phrase:v,queryClass:S,location:$,items:q,rawItems:L})=>{const Q=r.has(p),w=q.map(D=>D.citationState),X=w.includes("cited")?"cited":w.includes("emerging")?"emerging":w.includes("lost")?"lost":w.every(D=>D==="pending")?"pending":"not-cited",C=yr(q),F=q.filter(D=>D.citationState===Dl.cited||D.citationState==="emerging").length,_=ui(C,i);return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"cursor-pointer hover:bg-mono-800/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>N(p),onKeyDown:D=>{(D.key==="Enter"||D.key===" ")&&(D.preventDefault(),N(p))},tabIndex:0,role:"button","aria-expanded":Q,children:[e.jsx("td",{children:e.jsx(Ju,{size:14,className:`transition-transform duration-150 text-muted ${Q?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-heading",children:v}),s&&e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-muted",children:$??"No location"}),e.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[e.jsx(ce,{tone:"neutral",className:"whitespace-nowrap",children:Jm(S)}),q.map(D=>e.jsx(Cn,{provider:D.provider},D.id))]})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pr,{state:X,label:di(X,i)}),e.jsxs("span",{className:"text-[11px] text-muted",title:`${F} of ${q.length} engines ${k}`,children:[F,"/",q.length]})]})}),e.jsx("td",{children:e.jsx(li,{history:C})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:_}),e.jsx(hi,{items:L})]}),e.jsx("td",{})]}),Q&&q.map((D,Z)=>e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"bg-surface",children:[e.jsx("td",{}),e.jsx("td",{className:"evidence-query-cell pl-5",children:e.jsx(Cn,{provider:D.provider})}),e.jsx("td",{children:e.jsx(pr,{state:D.citationState,label:di(D.citationState,i)})}),e.jsx("td",{children:e.jsx(li,{history:D.runHistory})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:ui(D.runHistory,i)}),e.jsx(hi,{items:[L[Z]??D]})]}),e.jsx("td",{children:e.jsx(A,{variant:"ghost",size:"sm",type:"button",onClick:oe=>{oe.stopPropagation(),a(D.id)},children:"View"})})]}),u==="detailed"&&e.jsxs("tr",{className:"bg-surface-subtle",children:[e.jsx("td",{}),e.jsx("td",{colSpan:5,className:"px-5 pb-4",children:e.jsx(rh,{item:D,onViewFull:()=>a(D.id)})})]})]},D.id))]},p)})})]})}),f.totalRows===0&&(f.hasQuery||m!=="all")?e.jsx("p",{className:"supporting-copy mt-3",children:"No tracked queries match this filter."}):null,e.jsx(Rs,{page:f.page,pageSize:f.pageSize,visibleRows:f.rows.length,totalRows:f.totalRows,onPageChange:f.setPage,itemLabel:f.hasQuery||m!=="all"?"matches":"queries"}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",P==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function nh(t){const s=(t.matchedTerms??[]).filter(r=>r.trim().length>2),n=[...(t.mentionedCompetitorDomains??[]).flatMap(r=>{const o=Fl(r);return o.length>=4?[o]:[]}),...t.recommendedCompetitors??[]].filter(r=>r.trim().length>2),a=[];return s.length>0&&a.push({terms:s,className:"answer-highlight-brand"}),n.length>0&&a.push({terms:n,className:"answer-highlight-competitor"}),a}function xi(t,s){const n=s.toLowerCase().replace(/^www\./,"");return(t.citedCompetitorDomains??[]).some(a=>a.toLowerCase().replace(/^www\./,"")===n)}function ah(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 rh({item:t,onViewFull:s}){if(!(t.answerSnippet.trim().length>0))return e.jsx("p",{className:"text-[11px] text-muted italic",children:"No answer text captured for this run."});const{body:a,truncated:r}=ah(t.answerSnippet,Ym),o=nh(t);return e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Answer text"}),e.jsx("p",{className:"text-sm leading-relaxed text-neutral",children:Ol(a,o)}),(t.citedDomains.length>0||(t.mentionedCompetitorDomains?.length??0)>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(i=>e.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[11px] ${xi(t,i)?"border-negative-900/40 bg-negative-950/30 text-negative":"border-mono-700/60 bg-bg-elevated/60 text-neutral"}`,children:[i,xi(t,i)?" · competitor source":""]},`c-${i}`)),t.citedDomains.length>6&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.citedDomains.length-6," more"]})]}),(t.mentionedCompetitorDomains?.length??0)>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-negative-500/80",children:"Competitors in answer:"}),t.mentionedCompetitorDomains.slice(0,4).map(i=>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:i},`co-${i}`)),t.mentionedCompetitorDomains.length>4&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.mentionedCompetitorDomains.length-4," more"]})]})]}),r&&e.jsx("button",{type:"button",className:"text-[11px] font-medium text-positive-400 hover:text-positive",onClick:i=>{i.stopPropagation(),s()},children:"View full answer →"})]})}function ea({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})]})}function Ra({windows:t,value:s,onChange:n,label:a,formatOption:r,disabled:o=!1}){return e.jsx("div",{className:"segmented",role:"group","aria-label":a,children:t.map(i=>e.jsx("button",{type:"button","aria-pressed":s===i,disabled:o,className:`segmented-option ${s===i?"segmented-option-active":""}`,onClick:()=>n(i),children:r?r(i):i},i))})}const Ga=nt[0],Ka=nt[1],pi=nt[2],gi=nt[3],ih=["both","server","ga4"],fi={fontSize:11,paddingTop:6},yi=new Set(["Pages crawled trend","Page fetches trend","Visits trend"]),bi=t=>typeof t=="number"?Vs(Math.round(t)):String(t),es=t=>typeof t=="number"&&Number.isFinite(t)?t:0;function _a(t,s){if(!t||s<2)return Array(s).fill(null);const n=t.endIndex-t.startIndex;if(n<=0)return Array(s).fill(null);const a=(t.end-t.start)/n;return Array.from({length:s},(r,o)=>o<t.startIndex||o>t.endIndex?null:t.start+(o-t.startIndex)*a)}function Ua({label:t,value:s,caption:n,tooltip:a}){return e.jsxs("div",{className:"rounded-lg border border-default bg-bg/40 px-4 py-3 flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-1 mb-1",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted",children:t}),e.jsx(Me,{text:a})]}),e.jsx("p",{className:"text-xl font-semibold text-primary tabular-nums",children:s}),e.jsx("p",{className:"text-xs text-muted mt-0.5",children:n})]})}function oh(t,s){return n=>{const{cx:a,cy:r,index:o,key:i}=n,c=o??-1;return!(t[c]!=null&&t[c-1]==null&&t[c+1]==null)||a===void 0||r===void 0?e.jsx("g",{},i):e.jsx("circle",{cx:a,cy:r,r:2.6,fill:s,stroke:"none"},i)}}function lh({projectName:t,sinceMinutes:s}){const[n,a]=l.useState(!0),[r,o]=l.useState(!0),[i,c]=l.useState("both"),u=um(t,{sinceMinutes:s,granularity:"day",limit:1}),h=mm(t),x=we({...vo({client:H,path:{name:t}}),enabled:!!t,staleTime:dn}).data?.connected===!0,g=we({...jo({client:H,path:{name:t},query:{window:s>=2160*60?"90d":s>=720*60?"30d":"7d"}}),enabled:!!t&&x,staleTime:dn}),d=l.useMemo(()=>u.data?.series?.points??[],[u.data]),f=l.useMemo(()=>{const $=g.data;return new Map(($?.days??[]).map(q=>[q.date,q.sessions]))},[g.data]),y=l.useMemo(()=>{const $=L=>L.measured!==!1;if(d.length===0||$(d[0]))return null;const q=d.findIndex($)-1;return q<0?{from:d[0].bucket,to:d[d.length-1].bucket}:{from:d[0].bucket,to:d[q].bucket}},[d]),j=u.data?.series?.coverageStart??null,N=u.data?.series?.trends,P=l.useMemo(()=>{const $=_a(N?.crawlerContentHits,d.length),q=_a(N?.aiUserFetchHits,d.length),L=_a(N?.aiReferralLandedHits,d.length);return d.map((Q,w)=>({...Q,crawlerContentHits:Q.measured!==!1?es(Q.crawlerContentHits):null,aiUserFetchHits:Q.measured!==!1?es(Q.aiUserFetchHits):null,aiReferralLandedHits:Q.measured!==!1?es(Q.aiReferralLandedHits):null,ga4Visits:f.get(Q.bucket)??null,crawlTrend:$[w],fetchTrend:q[w],visitTrend:L[w]}))},[d,f,N]),M=u.data?.totals,k=M&&{crawlers:es(M.crawlerContentHits),fetches:es(M.aiUserFetchHits),visits:es(M.aiReferralLandedHits)},p=l.useMemo(()=>d.reduce(($,q)=>({crawlers:$.crawlers+es(q.crawlerContentHits),fetches:$.fetches+es(q.aiUserFetchHits),visits:$.visits+es(q.aiReferralLandedHits)}),{crawlers:0,fetches:0,visits:0}),[d]),v=k??p,S=v.crawlers>0||v.fetches>0||v.visits>0;if(u.isLoading)return e.jsx(xe,{className:"surface-card p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading AI traffic history…"})});if(u.isError)return e.jsxs(xe,{className:"surface-card p-5",children:[e.jsx("p",{className:"text-sm text-secondary",children:"Could not load AI traffic history."}),e.jsx("p",{className:"text-xs text-muted mt-1",children:"The request failed, so this is not a reading of zero activity. Retry, or check the traffic source."})]});if(!S){const $=h.data?.sources,q=$!==void 0&&$.length===0,L=!q&&j===null;return e.jsxs(xe,{className:"surface-card p-5",children:[e.jsx("p",{className:"text-sm text-secondary",children:q?"No server-side traffic source connected yet.":L?"No AI activity recorded yet.":"No AI activity recorded in this period."}),e.jsx("p",{className:"text-xs text-muted mt-1",children:q?"Connect a traffic source to see how AI engines read this site over time.":L?"The source is connected but has not reported anything yet. A new source can take a few hours to appear.":"The window was measured and nothing was recorded. Try a longer range."})]})}return e.jsxs(xe,{className:"surface-card p-5",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3 mb-5",children:[e.jsx(Ua,{label:"AI crawlers",value:Vs(v.crawlers),caption:"pages crawled",tooltip:"Requests from AI crawlers for a real content page. Robots.txt and sitemap re-fetches are excluded, because they are not a page an engine read."}),e.jsx(Ua,{label:"AI page fetches",value:Vs(v.fetches),caption:"reading a page to answer",tooltip:"An AI engine fetching a page live while answering someone, rather than crawling it for an index."}),e.jsx(Ua,{label:"AI visitors",value:Vs(v.visits),caption:"arrived from an AI answer",tooltip:"Visits your server answered that came from an AI engine. Requests answered with a redirect are excluded: a redirect is a hop, not an arrival."})]}),d.length>0&&e.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-5 gap-y-1 pb-3 mb-4 border-b border-default text-xs text-muted",children:[e.jsx("span",{className:"text-secondary font-semibold",children:"Latest day (UTC)"}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:es(d[d.length-1].crawlerContentHits).toLocaleString()}),"pages crawled"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:es(d[d.length-1].aiUserFetchHits).toLocaleString()}),"page fetches"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:es(d[d.length-1].aiReferralLandedHits).toLocaleString()}),"visits, server"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:f.get(d[d.length-1].bucket)?.toLocaleString()??"—"}),"visits, GA4"]}),e.jsx("span",{className:"text-faint",children:"still filling"})]}),e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Machines reading your site"}),e.jsx(Me,{text:"Crawlers index pages for later. Page fetches happen while an engine is answering someone. Both are machines, not people."})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-secondary cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:n,onChange:$=>a($.target.checked),className:"accent-current"}),"Page fetches"]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-secondary cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:r,onChange:$=>o($.target.checked),className:"accent-current"}),"Trend line"]})]})]}),e.jsx(Ws,{width:"100%",height:206,children:e.jsxs(Ys,{data:P,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(Vn,{stroke:Bn,vertical:!1}),e.jsx(Js,{dataKey:"bucket",tick:Rt,stroke:is,tickFormatter:pn,minTickGap:28}),e.jsx(Xs,{tick:Rt,stroke:is,width:48,allowDecimals:!1}),e.jsx(Zs,{contentStyle:as.contentStyle,labelStyle:as.labelStyle,itemStyle:as.itemStyle,labelFormatter:Ot,formatter:bi}),y&&e.jsx(xr,{x1:y.from,x2:y.to,fill:"var(--color-overlay-hover)",fillOpacity:.5,stroke:"none",label:{value:"not measured",position:"insideTop",fontSize:10,fill:"var(--chart-neutral-text-dim, #71717a)"}}),e.jsx(wa,{wrapperStyle:fi,iconType:"plainline",iconSize:14,formatter:$=>yi.has($)?"":$}),e.jsx(Fs,{type:"monotone",dataKey:"crawlerContentHits",name:"Pages crawled",stroke:Ga,fill:Ga,fillOpacity:.22,strokeWidth:1.8}),n&&e.jsx(Fs,{type:"monotone",dataKey:"aiUserFetchHits",name:"Page fetches",stroke:Ka,fill:Ka,fillOpacity:.18,strokeWidth:1.6}),r&&e.jsx(As,{type:"linear",dataKey:"crawlTrend",name:"Pages crawled trend",dot:!1,tooltipType:"none",stroke:Ga,strokeWidth:1.4,strokeDasharray:"5 4",connectNulls:!0}),r&&n&&e.jsx(As,{type:"linear",dataKey:"fetchTrend",name:"Page fetches trend",dot:!1,tooltipType:"none",stroke:Ka,strokeWidth:1.3,strokeDasharray:"5 4",connectNulls:!0})]})}),e.jsxs("div",{className:"flex items-center justify-between gap-3 mt-5 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"People arriving from AI"}),e.jsx(Me,{text:"Two independent counts of the same thing. Server reads your own logs and misses nothing a browser blocks, but cannot see a page served from cache. GA4 needs the browser to run a tag. They rarely match, and neither is the correction of the other."})]}),e.jsx(Ra,{windows:ih,value:i,onChange:c,label:"Visit measurement source",formatOption:$=>$==="ga4"?"GA4":$==="both"?"Both":"Server"})]}),e.jsx(Ws,{width:"100%",height:176,children:e.jsxs(Ys,{data:P,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(Vn,{stroke:Bn,vertical:!1}),e.jsx(Js,{dataKey:"bucket",tick:Rt,stroke:is,tickFormatter:pn,minTickGap:28}),e.jsx(Xs,{tick:Rt,stroke:is,width:48,allowDecimals:!1}),e.jsx(Zs,{contentStyle:as.contentStyle,labelStyle:as.labelStyle,itemStyle:as.itemStyle,labelFormatter:Ot,formatter:bi}),y&&e.jsx(xr,{x1:y.from,x2:y.to,fill:"var(--color-overlay-hover)",fillOpacity:.5,stroke:"none",label:{value:"not measured",position:"insideTop",fontSize:10,fill:"var(--chart-neutral-text-dim, #71717a)"}}),e.jsx(wa,{wrapperStyle:fi,iconType:"plainline",iconSize:14,formatter:$=>yi.has($)?"":$}),i!=="ga4"&&e.jsx(As,{type:"monotone",dataKey:"aiReferralLandedHits",name:"Visits, server",stroke:pi,strokeWidth:2,dot:!1}),i!=="server"&&e.jsx(As,{type:"monotone",dataKey:"ga4Visits",name:"Visits, GA4",connectNulls:!1,stroke:gi,strokeWidth:1.8,strokeDasharray:"5 3",dot:oh(P.map($=>$.ga4Visits),gi)}),r&&i!=="ga4"&&e.jsx(As,{type:"linear",dataKey:"visitTrend",name:"Visits trend",dot:!1,tooltipType:"none",stroke:pi,strokeWidth:1.3,strokeDasharray:"5 4",connectNulls:!0})]})})]})}const ch=6,kn="__other__",wn="_socialTotal";function dh(t,s=ch){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,x)=>x[1]!==m[1]?x[1]-m[1]:m[0].localeCompare(x[0])),r=a.slice(0,s),o=new Set(r.map(([m])=>m)),i=Math.max(0,a.length-s),c=new Map;for(const m of t){let x=c.get(m.date);x||(x={date:m.date,[wn]:0},c.set(m.date,x));const g=o.has(m.source)?m.source:kn;x[g]=(x[g]??0)+m.sessions,x[wn]=(x[wn]??0)+m.sessions}const u=[...c.values()].sort((m,x)=>String(m.date).localeCompare(String(x.date))),h=r.map(([m])=>m);return i>0&&h.push(kn),{data:u,sources:h,otherCount:i}}function Sn(t){return t.replace(/\+/g," ")}function zo(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const vi="_totalSessions",ji="_organicSessions";function uh(t,s){const n=new Map;for(const i of s)n.set(i.date,{[vi]:i.sessions,[ji]:i.organicSessions});for(const i of t.days){let c=n.get(i.date);c||(c={[vi]:0,[ji]:0},n.set(i.date,c));for(const u of i.bySource)c[u.source]=(c[u.source]??0)+u.sessions}const a=[...n.entries()].sort(([i],[c])=>i.localeCompare(c)).map(([i,c])=>({date:i,...c})),r=a.map(i=>i.date),o=r.length>0?{start:r[0],end:r[r.length-1]}:null;return{data:a,sources:t.sources,dateRange:o}}const mh=["7d","30d","90d"],hh={"7d":10080,"30d":720*60,"90d":2160*60,all:2160*60},Os=nt,br=os.textDim,Qo=os.textFaint,Tn=25;function xh(t){return Lo(t.landingPage)}const ph=25,gh=10,Ba={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0};function ta(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function Ho(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 fh({projectName:t}){const{data:s,isLoading:n,isError:a}=hm(t);if(n)return e.jsx(xe,{className:"p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading server activity…"})});if(a)return e.jsx(xe,{className:"p-5",children:e.jsx("div",{className:"text-sm text-negative-400",children:"Failed to load server activity."})});const r=s?.sources??[];return e.jsxs("section",{children:[e.jsx("div",{className:"flex items-baseline justify-between mb-3",children:e.jsxs("div",{children:[e.jsx("div",{className:"eyebrow",children:"Server activity (last 24h)"}),e.jsx("h2",{className:"text-lg font-semibold text-primary",children:"Server activity"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["Crawler, AI fetch, and referral activity from connected sources."," ",!te()&&e.jsx(vs,{to:"/traffic",className:"text-link hover:underline",children:"Manage sources →"})]})]})}),r.length===0?e.jsx(xe,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-secondary",children:["No server traffic source connected yet."," ",!te()&&e.jsxs(e.Fragment,{children:[e.jsx(vs,{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(xe,{className:"overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-bg-elevated/50 text-[10px] uppercase tracking-wide text-muted",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Source"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Status"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Crawler hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI sessions 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Last sync"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium","aria-label":"open"})]})}),e.jsx("tbody",{children:r.map(o=>e.jsxs("tr",{className:"border-t border-default",children:[e.jsx("td",{className:"px-4 py-3 text-heading",children:o.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(ce,{tone:xm(o.status),children:o.status})}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:o.totals24h.crawlerHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:o.totals24h.aiUserFetchHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:o.totals24h.aiReferralLandedHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right text-secondary text-xs",children:o.lastSyncedAt?Ho(o.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:te()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(vs,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:o.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},o.id))})]})})]})}function yh({projectName:t}){const[s,n]=l.useState("30d");return e.jsxs("div",{className:"space-y-10",children:[e.jsx(fh,{projectName:t}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(Ra,{windows:mh,value:s,onChange:n,label:"Traffic time period"})}),e.jsx(bh,{projectName:t,window:s}),e.jsx(lh,{projectName:t,sinceMinutes:hh[s]})]})}function bh({projectName:t,window:s}){const n=js(),a=s??"30d",[r,o]=l.useState(null),[i,c]=l.useState(null),[u,h]=l.useState(!0),[m,x]=l.useState(!1),[g,d]=l.useState(!1),[f,y]=l.useState(null),[j,N]=l.useState(null),[P,M]=l.useState("sessions"),[k,p]=l.useState("desc"),[v,S]=l.useState("sessions"),[$,q]=l.useState("desc"),[L,Q]=l.useState("sessions"),[w,X]=l.useState("desc"),[C,F]=l.useState("sessions"),[_,D]=l.useState("desc"),[Z,oe]=l.useState(Ba),[ne,U]=l.useState([]),[T,G]=l.useState([]),[ae,W]=l.useState(!1);async function J(Y){h(!0),y(null);try{const Re=await n.fetchQuery({...vo({client:H,path:{name:t}}),staleTime:dn});if(Y.current)return;if(o(Re),!Re.connected){c(null),oe(Ba),U([]),G([]),h(!1);return}const be=a==="all"?void 0:a,je=await n.fetchQuery({...Gl({client:H,path:{name:t},query:be?{window:be}:void 0}),staleTime:dn}).then(ls=>ls),Gt=je.windowStart||je.windowEnd?{...je.windowStart?{startDate:je.windowStart}:{},...je.windowEnd?{endDate:je.windowEnd}:{}}:void 0,[ze,ft,Tt]=await Promise.all([n.fetchQuery({...jo({client:H,path:{name:t},query:be?{window:be}:void 0}),staleTime:dn}).catch(()=>Ba),n.fetchQuery({...Kl({client:H,path:{name:t},query:be?{window:be}:void 0}),staleTime:dn}).catch(()=>[]),n.fetchQuery({..._l({client:H,path:{name:t},query:Gt}),staleTime:dn}).catch(()=>[])]);if(Y.current)return;c(je),oe(ze),U(ft),G(Tt),h(!1)}catch(Re){if(Y.current)return;y(Re instanceof Error?Re.message:"Failed to load GA4 data"),h(!1)}}l.useEffect(()=>{const Y={current:!1};return J(Y),()=>{Y.current=!0}},[t,a,n]);async function ge(){x(!0),y(null),N(null);try{const Y=await No(t);N(`Synced ${Y.rowCount.toLocaleString()} page rows, ${Y.aiReferralCount.toLocaleString()} AI and ${Y.socialReferralCount.toLocaleString()} social referral rows (${Y.days} days)`),await Nt(n,"ga"),await J({current:!1})}catch(Y){y(Y instanceof Error?Y.message:"Sync failed")}finally{x(!1)}}async function z(){d(!0),y(null),N(null);try{await Ul(t),await Nt(n,"ga"),o({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),c(null),N("GA4 disconnected")}catch(Y){y(Y instanceof Error?Y.message:"Disconnect failed")}finally{d(!1)}}function re(Y){Pe.setPage(1),P===Y?p(Re=>Re==="desc"?"asc":"desc"):(M(Y),p("desc"))}function ue(Y){v===Y?q(Re=>Re==="desc"?"asc":"desc"):(S(Y),q("desc"))}function Oe(Y){L===Y?X(Re=>Re==="desc"?"asc":"desc"):(Q(Y),X("desc"))}const Fe=l.useMemo(()=>i?.topPages?[...i.topPages].sort((Y,Re)=>{const be=Y[P],je=Re[P];return typeof be=="string"&&typeof je=="string"?k==="asc"?be.localeCompare(je):je.localeCompare(be):k==="asc"?be-je:je-be}):[],[i?.topPages,P,k]),Pe=xn({rows:Fe,getSearchText:Y=>Lo(Y.landingPage),pageSize:gh}),tt=l.useMemo(()=>i?.aiReferrals?[...i.aiReferrals].sort((Y,Re)=>{const be=Y[v],je=Re[v];return typeof be=="string"&&typeof je=="string"?$==="asc"?be.localeCompare(je):je.localeCompare(be):$==="asc"?be-je:je-be}):[],[i?.aiReferrals,v,$]),it=l.useMemo(()=>i?.aiReferralLandingPages?[...i.aiReferralLandingPages].sort((Y,Re)=>{const be=Y[C],je=Re[C];return typeof be=="string"&&typeof je=="string"?_==="asc"?be.localeCompare(je):je.localeCompare(be):_==="asc"?be-je:je-be}):[],[i?.aiReferralLandingPages,C,_]),ke=xn({rows:it,getSearchText:xh,pageSize:ph}),Xe=ke.totalRows>0?`${ke.totalRows.toLocaleString()} ${ke.hasQuery?ke.totalRows===1?"match":"matches":ke.totalRows===1?"row":"rows"}`:ke.hasQuery&&(i?.aiReferralLandingPages.length??0)>0?"0 matches":"No landing-page rows";function _e(Y){ke.setPage(1),C===Y?D(Re=>Re==="desc"?"asc":"desc"):(F(Y),D("desc"))}const Ve=l.useMemo(()=>i?.socialReferrals?[...i.socialReferrals].sort((Y,Re)=>{const be=Y[L],je=Re[L];return typeof be=="string"&&typeof je=="string"?w==="asc"?be.localeCompare(je):je.localeCompare(be):w==="asc"?be-je:je-be}):[],[i?.socialReferrals,L,w]),{socialChartData:He,socialChartSources:Te,socialOtherCount:B}=l.useMemo(()=>{const Y=dh(T);return{socialChartData:Y.data,socialChartSources:Y.sources,socialOtherCount:Y.otherCount}},[T]),{chartData:O,chartSources:V,dateRange:Ne}=l.useMemo(()=>{const Y=uh(Z,ne);return{chartData:Y.data,chartSources:Y.sources,dateRange:Y.dateRange}},[Z,ne]);if(u&&!r)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!r?.connected)return te()?e.jsx(xe,{className:"p-5",children:e.jsx("div",{className:"text-sm text-secondary",children:"No Google Analytics 4 property connected yet."})}):e.jsx(vh,{projectName:t,onConnected:()=>{(async()=>(await Nt(n,"ga"),await J({current:!1})))()}});const Ie=i?.organicSharePctDisplay??"0%",ee=i?.channelBreakdown?.organic.sharePctDisplay??Ie,We=i?.channelBreakdown?.organic.sessions??i?.totalOrganicSessions??0,ht=i?.aiSessionsDeduped??0,Ze=i?.channelBreakdown?.ai.sessions??i?.aiSessionsBySession??0,ye=i?.channelBreakdown?.ai.sharePctDisplay??i?.aiSharePctBySessionDisplay??"0%",Ge=i?.paidAiSessionsBySession??0,It=i?.paidAiSharePctBySessionDisplay??"0%",xt=i?new Set(i.aiReferrals.map(Y=>Y.source.toLowerCase())).size:0,Ee=tt[0]??null,Ye=i?.totalDirectSessions??0,pt=i?.directSharePctDisplay??"0%",St=i?.channelBreakdown?.direct.sessions??Ye,Ke=i?.channelBreakdown?.direct.sharePctDisplay??pt,Le=i?.channelBreakdown?.other.sessions??i?.otherSessions??0,et=i?.channelBreakdown?.other.sharePctDisplay??i?.otherSharePctDisplay??"0%",Ue=i?.socialSessions??0,Be=i?.socialSharePctDisplay??"0%",$t=i?.channelBreakdown?.social.sessions??Ue,vt=i?.channelBreakdown?.social.sharePctDisplay??Be,Ft=i?new Set(i.socialReferrals.map(Y=>Y.source.toLowerCase())).size:0,gt=Ve[0]??null;return e.jsxs(e.Fragment,{children:[f&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative",children:f}),j&&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:j}),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:r.propertyId}),r.clientEmail&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"text-muted",children:r.clientEmail})]})]})]}),!te()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(A,{variant:"outline",size:"sm",disabled:m,onClick:qe(ge),children:[e.jsx(Na,{className:`w-3.5 h-3.5 mr-1.5 ${m?"animate-spin":""}`}),m?"Syncing…":"Sync"]}),e.jsxs(A,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:g,onClick:qe(z),children:[e.jsx(Xu,{className:"w-3.5 h-3.5 mr-1.5"}),"Disconnect"]})]})]}),e.jsxs("section",{children:[e.jsx("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(Me,{text:`Aggregated traffic metrics from Google Analytics 4.${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"})}.`:""} Distinct users are unavailable when the selected history extends beyond a stored aggregate. Organic sessions are Google organic search sessions specifically.`})]})]})}),i?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(Va,{value:ta(i.totalSessions),label:"Total Sessions",subtitle:i.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(Va,{value:ta(i.totalOrganicSessions),label:"Organic Sessions",subtitle:`${Ie} of total`,tone:"positive"}),e.jsx(Va,{value:i.totalUsers===null?"—":ta(i.totalUsers),label:"Total Users",subtitle:i.totalUsers===null?"Unavailable for this range":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."}),!te()&&e.jsxs(A,{variant:"outline",size:"sm",disabled:m,onClick:qe(ge),children:[e.jsx(Na,{className:`w-3.5 h-3.5 mr-1.5 ${m?"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(Me,{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."})]})]}),Ne&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(Ne.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(Ne.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),O.length>0&&e.jsxs(xe,{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:V.length>0?"AI vs. total sessions":"All sessions (baseline)"}),V.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),V.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(Ws,{width:"100%",height:"100%",children:e.jsxs(Ys,{data:O,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Js,{dataKey:"date",tick:Rt,tickLine:!1,axisLine:{stroke:is},tickFormatter:pn}),e.jsx(Xs,{tick:Rt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Zs,{...as,labelFormatter:Ot,formatter:(Y,Re)=>{const be=typeof Y=="number"?Y.toLocaleString():String(Y??0),je=String(Re??"");return je==="_totalSessions"?[be,"Total Sessions"]:je==="_organicSessions"?[be,"Organic Sessions"]:[be,je]}}),e.jsx(wa,{wrapperStyle:{fontSize:11,color:os.text},formatter:Y=>Y==="_totalSessions"?"Total Sessions":Y==="_organicSessions"?"Organic Sessions":Y}),e.jsx(Fs,{type:"monotone",dataKey:"_totalSessions",stroke:os.textFaint,fill:os.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),V.map((Y,Re)=>e.jsx(Fs,{type:"monotone",dataKey:Y,stackId:"ai",stroke:Os[Re%Os.length],fill:Os[Re%Os.length],fillOpacity:.4,strokeWidth:1.5},Y))]})})})]}),e.jsxs(xe,{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:"Sessions by channel"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(us,{label:"Organic",value:ee,hint:`${We.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(us,{label:"Social",value:vt,hint:`${$t.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(us,{label:"Direct",value:Ke,hint:`${St.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(us,{label:"Visitors from AI (at least)",value:ye,hint:Ge>0?`${Ze.toLocaleString()} sessions · ${Ge.toLocaleString()} paid`:`${Ze.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(us,{label:"Other channels",value:et,hint:`${Le.toLocaleString()} sessions`,tone:"neutral",tooltip:"Remaining GA4 session default channel groups after Known AI, Organic Search, Organic/Paid Social, and Direct are accounted for. This is a residual bucket, not a single source. It can include Referral, Email, Paid Search, Display, Cross-network, Shopping, Video, Affiliates, SMS, Mobile Push Notifications, Paid Other, and unclassified traffic."})]}),Ee&&e.jsxs("div",{className:"mt-4 rounded-lg border border-positive-800/40 bg-positive-500/6 px-4 py-3 text-sm text-positive-100",children:["Top AI referrer: ",e.jsx("span",{className:"font-medium",children:Ee.source})," via ",Ee.medium,", accounting for ",Ee.sessions.toLocaleString()," sessions.",Ge>0&&e.jsxs("span",{children:[" Paid AI: ",Ge.toLocaleString()," sessions (",It,")."]})]})]}),e.jsxs(xe,{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:"Where AI visitors came from"})]}),e.jsx("p",{className:"text-xs text-muted",children:i.aiReferrals.length>0?`${xt} 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(ts,{label:"Source",sortKey:"source",current:v,dir:$,onSort:ue,align:"left"}),e.jsx(ts,{label:"Medium",sortKey:"medium",current:v,dir:$,onSort:ue,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(ts,{label:"Sessions",sortKey:"sessions",current:v,dir:$,onSort:ue,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:tt.map(Y=>e.jsx(Nh,{referral:Y,totalSessions:ht},`${Y.source}:${Y.medium}:${Y.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(xe,{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:"Pages AI visitors landed on"})]}),e.jsx("p",{className:"text-xs text-muted",children:Xe})]}),i.aiReferralLandingPages.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Us,{value:ke.query,onChange:ke.setQuery,label:"Filter landing page URLs or query parameters",placeholder:"Filter URL or query parameters",className:"mb-4 max-w-md"}),ke.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(ts,{label:"Landing Page",sortKey:"landingPage",current:C,dir:_,onSort:_e,align:"left"}),e.jsx(ts,{label:"Source",sortKey:"source",current:C,dir:_,onSort:_e,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(ts,{label:"Sessions",sortKey:"sessions",current:C,dir:_,onSort:_e,align:"right"})]})}),e.jsx("tbody",{children:ke.rows.map(Y=>e.jsx(wh,{row:Y},`${Y.landingPage}:${Y.source}:${Y.medium}:${Y.sourceDimension}`))})]})}),e.jsx(Rs,{page:ke.page,pageSize:ke.pageSize,visibleRows:ke.rows.length,totalRows:ke.totalRows,onPageChange:ke.setPage,itemLabel:ke.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:()=>ke.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 visits recorded yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"Pages appear here once a GA4 sync records a visit that arrived from an AI engine."})]})]})]})]}),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(Me,{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."})]})]}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs(xe,{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:"Visits from social"})]}),i.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(us,{label:"Social Sessions",value:ta(Ue),hint:`${Ue.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(us,{label:"Share of Traffic",value:Be,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(us,{label:"Platforms",value:String(Ft),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."})]}),gt&&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:`${gt.source} via ${gt.medium}`,children:zo(Sn(gt.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:gt.medium,children:["via ",Sn(gt.medium)," · ",gt.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(us,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(us,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(us,{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."})]})]})]}),He.length>0&&e.jsxs(xe,{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:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social sessions"})]}),B>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",Te.length-1," sources · ",B," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(Ws,{width:"100%",height:"100%",children:e.jsxs(Ys,{data:He,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Js,{dataKey:"date",tick:Rt,tickLine:!1,axisLine:{stroke:is},tickFormatter:pn}),e.jsx(Xs,{tick:Rt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Zs,{...as,labelFormatter:Ot,formatter:(Y,Re)=>{const be=typeof Y=="number"?Y.toLocaleString():String(Y??0),je=String(Re??"");if(je===wn)return[be,"Total Social"];if(je===kn){const Gt=`Other (${B} source${B===1?"":"s"})`;return[be,Gt]}return[be,Sn(je)]}}),e.jsx(Fs,{type:"monotone",dataKey:wn,stroke:Qo,fill:os.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),Te.map((Y,Re)=>{const je=Y===kn?br:Os[Re%Os.length];return e.jsx(Fs,{type:"monotone",dataKey:Y,stackId:"social",stroke:je,fill:je,fillOpacity:.4,strokeWidth:1.5},Y)})]})})}),e.jsx(Ch,{sources:Te,otherCount:B})]}),e.jsxs(xe,{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:"Social sources"})]}),e.jsx("p",{className:"text-xs text-muted",children:i.socialReferrals.length>0?Ve.length>Tn&&!ae?`Top ${Tn} of ${Ve.length}`:`${Ve.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(ts,{label:"Source",sortKey:"source",current:L,dir:w,onSort:Oe,align:"left"}),e.jsx(ts,{label:"Medium",sortKey:"medium",current:L,dir:w,onSort:Oe,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(ts,{label:"Sessions",sortKey:"sessions",current:L,dir:w,onSort:Oe,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:(ae?Ve:Ve.slice(0,Tn)).map(Y=>e.jsx(Sh,{referral:Y,totalSessions:Ue},`${Y.source}:${Y.medium}:${Y.channelGroup}`))})]})}),Ve.length>Tn&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>W(Y=>!Y),className:"rounded-md border border-base px-3 py-1.5 text-xs text-secondary transition-colors hover:border-strong hover:text-strong",children:ae?`Show top ${Tn}`:`Show all ${Ve.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(Me,{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(Us,{value:Pe.query,onChange:Pe.setQuery,label:"Filter landing page URLs",placeholder:"Filter landing pages",className:"mb-4 max-w-md"}),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(ts,{label:"Landing Page",sortKey:"landingPage",current:P,dir:k,onSort:re,align:"left"}),e.jsx(ts,{label:"Sessions",sortKey:"sessions",current:P,dir:k,onSort:re,align:"right"}),e.jsx(ts,{label:"Organic",sortKey:"organicSessions",current:P,dir:k,onSort:re,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"})]})}),e.jsx("tbody",{children:Pe.rows.map(Y=>e.jsx(jh,{page:Y},Y.landingPage))})]})}),Pe.totalRows===0&&Pe.hasQuery&&e.jsx("p",{className:"text-sm text-secondary mt-3",children:"No landing pages match this filter"}),e.jsx(Rs,{page:Pe.page,pageSize:Pe.pageSize,visibleRows:Pe.rows.length,totalRows:Pe.totalRows,onPageChange:Pe.setPage,itemLabel:Pe.hasQuery?"matches":"pages"})]})]}),e.jsxs("div",{className:"mt-6 flex items-center justify-between text-xs text-muted",children:[e.jsx("span",{children:i?.lastSyncedAt?`Last synced ${Ho(i.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:i?`${i.topPages.length} pages · ${i.aiReferrals.length} AI rows · ${i.socialReferrals.length} social rows`:""})]})]})}function vh({projectName:t,onConnected:s}){const[n,a]=l.useState(""),[r,o]=l.useState(null),[i,c]=l.useState(null),[u,h]=l.useState(!1),[m,x]=l.useState(null),g=l.useRef(null),d=l.useCallback(y=>{const j=y.target.files?.[0];if(!j)return;x(null),o(j.name);const N=new FileReader;N.onload=()=>{const P=N.result;try{const M=JSON.parse(P);if(!M.client_email||!M.private_key){x("JSON file is missing required fields: client_email and private_key. Make sure you downloaded a service account key (not an OAuth client)."),c(null);return}c(P)}catch{x("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),c(null)}},N.onerror=()=>{x("Failed to read file."),c(null)},N.readAsText(j)},[]);async function f(){if(x(null),!n.trim()){x("Property ID is required.");return}if(!i){x("Please upload a service account key file.");return}h(!0);try{await Bl(t,{propertyId:n.trim(),keyJson:i});try{await No(t)}catch{}s()}catch(y){x(y instanceof Error?y.message:"Failed to connect GA4")}finally{h(!1)}}return e.jsxs(xe,{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:y=>a(y.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:g,type:"file",accept:".json,application/json",onChange:d,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>g.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(Zu,{className:"w-4 h-4 shrink-0"}),r?e.jsx("span",{className:"text-strong truncate",children:r}):e.jsx("span",{children:"Upload .json key file"})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Download from Google Cloud Console → IAM & Admin → Service Accounts → Keys → Add Key → JSON. The service account must have ",e.jsx("span",{className:"text-secondary",children:"Viewer"})," access on the GA4 property."]})]}),e.jsx(A,{variant:"default",size:"sm",disabled:u||!n.trim()||!i,onClick:qe(f),children:u?"Connecting & syncing…":"Connect GA4"})]})}function ts({label:t,sortKey:s,current:n,dir:a,onSort:r,align:o}){const i=n===s;return e.jsx("th",{className:`py-1 ${o==="right"?"text-right":"text-left"}`,children:e.jsxs("button",{type:"button",className:"font-medium cursor-pointer select-none hover:text-neutral transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-400 rounded",onClick:()=>r(s),"aria-label":`Sort by ${t}${i?` (currently ${a==="asc"?"ascending":"descending"})`:""}`,children:[t,i&&e.jsx("span",{className:"ml-0.5",children:a==="asc"?"↑":"↓"})]})})}const Wo={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function Va({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 ${Wo[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function us({value:t,label:s,hint:n,tone:a,tooltip:r}){return e.jsxs("div",{className:"rounded-lg border border-default bg-bg/40 px-4 py-3 flex flex-col",children:[e.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1 flex items-center gap-1",children:[s,r&&e.jsx(Me,{text:r})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${Wo[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function jh({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 Yo={session:"Session",first_user:"First Visit",manual_utm:"UTM"},Jo={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 Nh({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=Yo[t.sourceDimension]??t.sourceDimension,r=Jo[t.sourceDimension]??"",o=t.trafficClass==="paid"?"Paid":"Organic",i=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:i,children:o})}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:r,children:a})}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[n,"%"]})]})}function wh({row:t}){const s=Yo[t.sourceDimension]??t.sourceDimension,n=Jo[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(xa,{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 Sh({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=t.channelGroup==="Paid Social"?"Paid":"Organic",r=Sn(t.source),o=Sn(t.medium);return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 pr-3 text-strong truncate",title:t.source,children:r}),e.jsx("td",{className:"py-1.5 pr-3 text-muted truncate",title:t.medium,children:o}),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,"%"]})]})}function Ch({sources:t,otherCount:s}){const n=[{key:wn,color:Qo,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const r=t[a];if(r===kn)n.push({key:kn,color:br,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const o=Sn(r);n.push({key:r,color:Os[a%Os.length]??br,label:zo(o,32),tooltip:o})}}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 kh(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 Ah=["7d","30d","90d","all"],sa=500,Ni=[{key:"clicks",label:"Clicks",color:nt[1],format:t=>t.toLocaleString()},{key:"impressions",label:"Impressions",color:nt[4],format:t=>t.toLocaleString()},{key:"ctr",label:"CTR",color:Is.caution,format:t=>`${(t*100).toFixed(1)}%`},{key:"position",label:"Avg position",color:nt[2],inverted:!0,format:t=>t.toFixed(1)}],Es=25,Ph="canonry:google-oauth-complete",Rh=new Intl.NumberFormat(void 0,{maximumFractionDigits:1});function Ih(t,s,n){if(!t)return"no comparison period";const a=t.days;if(!t.comparable)return"property-level comparison unavailable";const r=t.change[s];if(r===null||!Number.isFinite(r)){const u=t.prior[s],h=t.trailing[s];return u!==null&&h!==null&&u<=0&&h>0?`new in the last ${a}d`:u===null||u<=0?`no prior ${a}d to compare`:h===null?`no value in the last ${a}d`:"comparison unavailable"}if(r===0)return`→ no change vs prior ${a}d`;const o=Math.abs(r*100),i=o<.1?"<0.1%":`${Rh.format(o)}%`;return`${(n?r<0:r>0)?"↑":"↓"} ${i} vs prior ${a}d`}function $h(t){if(!t)return"Tile percentages compare the selected window with the equal-length period before it.";const{days:s,basis:n,prior:a,trailing:r}=t,o=s===1?"day":"days",i=`${a.startDate} to ${a.endDate}`,c=`${r.startDate} to ${r.endDate}`,u=`Tile percentages compare these ${s} ${o} (${c}) with the ${s} ${o} before them (${i}).`;return n!=="split-window"?u:`${u} That is the trailing half of the selected window against its own earlier half: there is no equal-length period before the window with synced data to compare it against.`}function wi(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function Si(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 Ci(t){return t.isPending?"Processing":Number(t.errors??0)>0?"Errors":Number(t.warnings??0)>0?"Warnings":"Success"}function Th({projectName:t,refreshNonce:s}){const n=js(),[a,r]=l.useState(!1),[o,i]=l.useState([]),[c,u]=l.useState([]),[h,m]=l.useState([]),[x,g]=l.useState(null),[d,f]=l.useState([]),[y,j]=l.useState([]),[N,P]=l.useState(null),[M,k]=l.useState(""),[p,v]=l.useState(""),[S,$]=l.useState("30"),[q,L]=l.useState(!1),[Q,w]=l.useState("30d"),[X,C]=l.useState(["clicks","impressions"]),[F,_]=l.useState(!0),[D,Z]=l.useState(null),[oe,ne]=l.useState(0),[U,T]=l.useState({startDate:"",endDate:"",query:"",page:""}),[G,ae]=l.useState(0),[W,J]=l.useState(!1),[ge,z]=l.useState(0),[re,ue]=l.useState(!1),[Oe,Fe]=l.useState(""),[Pe,tt]=l.useState(!0),[it,ke]=l.useState(!1),[Xe,_e]=l.useState(!1),[Ve,He]=l.useState(!1),[Te,B]=l.useState(!1),[O,V]=l.useState(!1),[Ne,Ie]=l.useState(!1),[ee,We]=l.useState(null),[ht,Ze]=l.useState(!1),[ye,Ge]=l.useState(!1),[It,xt]=l.useState(null),[Ee,Ye]=l.useState(null),[pt,St]=l.useState([]),[Ke,Le]=l.useState(new Set),[et,Ue]=l.useState({}),[Be,$t]=l.useState(new Set),[vt,Ft]=l.useState(""),[gt,Y]=l.useState(null),[Re,be]=l.useState(""),[je,Gt]=l.useState(!1),[ze,ft]=l.useState(!1),[Tt,ls]=l.useState(!1),[Mt,Kt]=l.useState(!1),[ot,cs]=l.useState("indexed"),[Ct,Ts]=l.useState(null),zt=!!(U.query.trim()||U.page.trim()||Ct),Xt=Ct!==null,Qt=l.useMemo(()=>{if(!Ct)return h;const{key:b,dir:K}=Ct;return[...h].sort((de,pe)=>{const Qe=b===un.CTR?Number.isFinite(de.ctr)?de.ctr:0:de[b],Je=b===un.CTR?Number.isFinite(pe.ctr)?pe.ctr:0:pe[b];return K==="asc"?Qe-Je:Je-Qe})},[h,Ct]),dt=xn({rows:Qt,pageSize:Ss}),Ns=re?dt.rows:Qt,Ht=xn({rows:(It??[]).filter(b=>b.path.toLowerCase().includes(vt.trim().toLowerCase())),pageSize:Ss}),[ct,hs]=l.useState([]),[jt,Zt]=l.useState(null),[xs,ps]=l.useState(1),Lt=l.useMemo(()=>{if(ct.length<2)return null;const b=ct[ct.length-1],K=ct[ct.length-2];return{indexed:b.indexed-K.indexed,notIndexed:b.notIndexed-K.notIndexed}},[ct]);l.useEffect(()=>{ps(1)},[ee,ot,jt]);const E=l.useMemo(()=>jt?(ee?.reasonGroups??[]).find(b=>b.reason===jt):void 0,[ee,jt]),se=l.useMemo(()=>ee?ot==="indexed"?ee.indexed:ot==="deindexed"?ee.deindexed:ot==="notIndexed"?jt?E?.urls??[]:(ee.reasonGroups??[]).length===0?ee.notIndexed:[]:[]:[],[ee,ot,jt,E]),fe=Math.max(1,Math.ceil(se.length/Es)),ie=Math.min(Math.max(1,xs),fe),le=(ie-1)*Es,$e=l.useMemo(()=>ee?.indexed.slice(le,le+Es)??[],[ee,le]),Wt=l.useMemo(()=>ee?.notIndexed.slice(le,le+Es)??[],[ee,le]),yt=l.useMemo(()=>ee?.deindexed.slice(le,le+Es)??[],[ee,le]),gs=l.useMemo(()=>(E?.urls??[]).slice(le,le+Es),[E,le]),[R,me]=l.useState(!1),[st,Ae]=l.useState(null),[ut,ds]=l.useState(null),[_t,Yt]=l.useState(null);function $a(b,K){const de=pm(b),pe=kh(de);pe?(ds(pe),Ae(null)):(ds(null),Ae(de.message||K))}const kt=o.find(b=>b.connectionType==="gsc"),ws=(kt?.scopes??[]).includes("https://www.googleapis.com/auth/webmasters"),gn=pt.length>0?pt:(It??[]).map(b=>b.path),Pn=gn.filter(b=>It?.some(K=>K.path===b&&K.isSitemapsIndex)).length,Jt=Pn===1?"Resubmit sitemap index":Pn>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",Ta=h.length>0||d.length>0||y.length>0,Rn=Vl(),In=zl();async function Jn(b,K=!1){if(!b){u([]),k("");return}_e(!0);try{const{sites:de}=await n.fetchQuery({...ic({client:H,path:{name:t}}),staleTime:K?0:Dt});u(de),k(b.propertyId??de[0]?.siteUrl??""),ds(null)}catch(de){u([]),$a(de,"Failed to load Search Console properties")}finally{_e(!1)}}async function en(b){B(!0);const K=b??G;try{const de=zt?sa:Ss,pe=zt?0:K,Qe={limit:String(de)};U.startDate&&(Qe.startDate=U.startDate),U.endDate&&(Qe.endDate=U.endDate),U.query&&(Qe.query=U.query),U.page&&(Qe.page=U.page),pe>0&&(Qe.offset=String(pe)),Q&&Q!=="all"&&!U.startDate&&(Qe.window=Q);const Je=await n.fetchQuery({...Wl({client:H,path:{name:t},query:Qe}),staleTime:Dt}),at=Je.rows;zt?(J(!1),m(at),z(at.length),ue(!0)):(J(pe+at.length<Je.totalMatching),m(at),z(0),ue(!1))}catch(de){m([]),J(!1),z(0),Ae(de instanceof Error?de.message:"Failed to load GSC performance data")}finally{B(!1)}}async function I(){try{const b={};U.startDate&&(b.startDate=U.startDate),U.endDate&&(b.endDate=U.endDate),Q&&Q!=="all"&&!U.startDate&&(b.window=Q);const K=await n.fetchQuery({...Hl({client:H,path:{name:t},query:b}),staleTime:Dt});g(K)}catch{g(null)}}async function he(b=!1){V(!0);try{const K=Oe.trim()||void 0,de={limit:"20"};K&&(de.url=K);const[pe,Qe]=await Promise.all([n.fetchQuery({...ac({client:H,path:{name:t},query:de}),staleTime:b?0:Dt}),n.fetchQuery({...rc({client:H,path:{name:t}}),staleTime:b?0:Dt})]);f(pe),j(Qe)}catch(K){f([]),j([]),Ae(K instanceof Error?K.message:"Failed to load GSC inspection history")}finally{V(!1)}}async function Ce(b=!1){Ze(!0);try{const[K,de]=await Promise.all([n.fetchQuery({...Xl({client:H,path:{name:t}}),staleTime:b?0:Dt}),n.fetchQuery({...Zl({client:H,path:{name:t}}),staleTime:b?0:Dt}).catch(()=>[])]);We(K),hs(de)}catch(K){We(null),hs([]),Ae(K instanceof Error?K.message:"Failed to load coverage data")}finally{Ze(!1)}}async function Ut(b){me(!0),Ae(null);try{const K=await Zr(t,{urls:b}),{succeeded:de,failed:pe,total:Qe}=K.summary;Se({title:"Indexing requested",detail:pe===0?`${de} URL${de!==1?"s":""} submitted for indexing.`:`${de}/${Qe} submitted successfully, ${pe} failed.`,tone:pe===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(K){Ae(K instanceof Error?K.message:"Failed to request indexing")}finally{me(!1)}}async function fs(){me(!0),Ae(null);try{const b=await Zr(t,{urls:[],allUnindexed:!0}),{succeeded:K,failed:de,total:pe}=b.summary;Se({title:"Indexing requested",detail:de===0?`${K} unindexed URL${K!==1?"s":""} submitted for indexing.`:`${K}/${pe} submitted successfully, ${de} failed.`,tone:de===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(b){Ae(b instanceof Error?b.message:"Failed to request indexing")}finally{me(!1)}}async function Ma(){Ge(!0),Ae(null);try{const b=await Ea(t);n.setQueryData(ec({client:H,path:{name:t}}),b),xt(b.sitemaps),Ye(b.summary),St(b.preferredSubmissionUrls),Le(new Set),Ue({}),b.sitemaps.length===0&&Yt("No sitemaps found in this GSC property. Submit one here to start Google processing it.")}catch(b){Ae(b instanceof Error?b.message:"Failed to list sitemaps")}finally{Ge(!1)}}async function Sl(b){const K=Ke.has(b);if(Le(de=>{const pe=new Set(de);return K?pe.delete(b):pe.add(b),pe}),!(K||et[b])){$t(de=>new Set(de).add(b));try{const de=await Ea(t,b);Ue(pe=>({...pe,[b]:de.sitemaps}))}catch(de){Ae(de instanceof Error?de.message:"Failed to load sitemap files")}finally{$t(de=>{const pe=new Set(de);return pe.delete(b),pe})}}}async function fn(b){if(!ws||b.length===0)return;const K=[...new Set(b)];ft(!0),Ae(null),Y({completed:0,total:K.length});let de=0,pe=0,Qe=0,Je=null;try{for(let wt=0;wt<K.length;wt+=50){const rt=K.slice(wt,wt+50);try{const ve=await tc(t,rt);de+=ve.summary.accepted,pe+=ve.summary.failed,Qe+=rt.length,Y({completed:Qe,total:K.length})}catch(ve){Qe+=rt.length;const Ms=rt.length,$n=K.length-Qe,Xn=ve instanceof Error?ve.message:"The batch request failed",Ls=`${de} accepted, ${pe} failed, ${Ms} unconfirmed, ${$n} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;Je=`Sitemap submission stopped after a batch request failed. ${Ls} ${Xn}`,Ae(Je),Se({title:"Sitemap resubmission partially completed",detail:Ls,tone:"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"});return}}const at=K.length;Se({title:pe===0?"Sitemap submitted to Google":"Some sitemap submissions need attention",detail:pe===0?"Google accepted the sitemap submission/refetch request; indexing is not guaranteed.":`Google accepted ${de}/${at} sitemap submissions; ${pe} failed. Indexing is not guaranteed.`,tone:pe===0?"positive":"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"}),be("")}catch(at){Ae(at instanceof Error?at.message:"Failed to submit sitemap to Google")}finally{ft(!1),Y(null),await Ma(),Je&&Ae(Je)}}async function Cl(){ft(!0);const b=It??[];try{const K=b.filter(pe=>pe.isSitemapsIndex),de=[];for(let pe=0;pe<K.length;pe+=4)(await Promise.all(K.slice(pe,pe+4).map(async Je=>{const at=et[Je.path];if(at)return at;const wt=await Ea(t,Je.path);return Ue(rt=>({...rt,[Je.path]:wt.sitemaps})),wt.sitemaps}))).forEach((Je,at)=>{de.push(...Je.length>0?Je.map(wt=>wt.path):[K[pe+at].path])});await fn([...b.filter(pe=>!pe.isSitemapsIndex).map(pe=>pe.path),...de])}catch(K){Ae(K instanceof Error?K.message:"Failed to load sitemap files"),ft(!1)}}async function Vr(b){Gt(!0),Ae(null);try{await sc(t,"gsc",b),await Nt(n,"google"),i(K=>K.map(de=>de.connectionType==="gsc"?{...de,sitemapUrl:b}:de)),Se({title:"Default sitemap updated",detail:b,tone:"positive",dedupeKey:`gsc:sitemap-default:${t}`,dedupeMode:"replace"})}catch(K){Ae(K instanceof Error?K.message:"Failed to set the default sitemap")}finally{Gt(!1)}}async function zr(b){try{await In.mutateAsync({projectName:t,projectLabel:t,opts:b?{sitemapUrl:b}:void 0})}catch{}}async function Qr(){tt(!0),Ae(null);try{const[b,K]=await Promise.all([wo().catch(()=>null),n.fetchQuery({...Ir({client:H,path:{name:t}}),staleTime:Dt}).catch(()=>[])]);r(!!b?.google?.configured),i(K);const de=K.find(pe=>pe.connectionType==="gsc");await Promise.all([Jn(de),en(),I(),he(),Ce(),de?.propertyId?Ma():Promise.resolve()])}finally{tt(!1)}}l.useEffect(()=>{Qr()},[t,s]),l.useEffect(()=>{ae(0),Z(null),T(b=>b.startDate||b.endDate?{...b,startDate:"",endDate:""}:b),ne(b=>b+1),I()},[Q]);const Hr=l.useRef(!1);l.useEffect(()=>{if(!Hr.current){Hr.current=!0;return}ae(0),dt.setPage(1),en(0)},[oe]);function La(b){const K=D===b?null:b;Z(K),T(de=>({...de,startDate:K??"",endDate:K??""})),ne(de=>de+1)}const Wr=l.useRef(!1);l.useEffect(()=>{if(!Wr.current){Wr.current=!0;return}ae(0),en(0)},[Xt]);async function Yr(){if(!a){Ae("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}ke(!0),Ae(null),Yt(null);try{let b=function(ve){if(ve.source!==pe||ve.origin!==Qe||!ve.data||typeof ve.data!="object")return;const Ms=ve.data;Ms.type!==Ph||Ms.connectionType!=="gsc"||rt(!0)};const{authUrl:K,redirectUri:de}=await Jl(t,"gsc");if(!K.startsWith("https://accounts.google.com/")){Ae("Unexpected OAuth redirect URL. Please try again.");return}const pe=window.open(K,"_blank","width=600,height=700");if(!pe){window.location.assign(K);return}const Qe=de?new URL(de).origin:window.location.origin;let Je=!1,at=null;const wt=()=>{at!==null&&window.clearInterval(at),window.removeEventListener("message",b)},rt=async ve=>{if(!Je){Je=!0,wt(),Yt(ve?"Google connected. Refreshing access…":"Refreshing Google connection…");try{await Nt(n,"google"),await Qr()}finally{Yt(null)}}};window.addEventListener("message",b),Yt("Finish the Google consent flow in the popup. This page will refresh automatically."),at=window.setInterval(()=>{pe.closed&&rt(!1)},1e3)}catch(b){Ae(b instanceof Error?b.message:"Failed to start OAuth flow")}finally{ke(!1)}}async function kl(){Ae(null),Yt(null);try{await Yl(t,"gsc"),await Nt(n,"google"),i(b=>b.filter(K=>K.connectionType!=="gsc")),u([]),k("")}catch(b){Ae(b instanceof Error?b.message:"Failed to disconnect")}}async function Al(){if(M){He(!0),Ae(null);try{await oc(t,"gsc",M),await Nt(n,"google"),i(b=>b.map(K=>K.connectionType==="gsc"?{...K,propertyId:M}:K)),Se({title:"GSC property updated",detail:`${t} is now linked to ${M}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(b){Ae(b instanceof Error?b.message:"Failed to save GSC property")}finally{He(!1)}}}async function Pl(){Ae(null),Yt(null);try{await Rn.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(S,10)||void 0,full:q||void 0}}),await Nt(n,"gsc")}catch{}}async function Jr(){if(p.trim()){Ie(!0),Ae(null),Yt(null);try{const b=await nc(t,p.trim());await Nt(n,"gsc"),P(b),v(""),await he()}catch(b){Ae(b instanceof Error?b.message:"Failed to inspect URL")}finally{Ie(!1)}}}return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search Console"}),e.jsx("h2",{children:"Google Search Console"})]})}),ut&&e.jsx("div",{className:"mb-3 rounded-lg border border-caution-800/40 bg-caution-950/20 px-3 py-2.5 text-sm text-caution-200",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-caution-100",children:ut.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:ut.message}),(Ds(ut.enableUrl)||Ds(ut.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[Ds(ut.enableUrl)&&e.jsx("a",{href:Ds(ut.enableUrl),target:"_blank",rel:"noopener noreferrer",className:"font-medium text-caution-100 underline decoration-caution-500/50 underline-offset-2 hover:text-caution-50",children:"Enable Search Console API ↗"}),Ds(ut.indexingApiUrl)&&e.jsx("a",{href:Ds(ut.indexingApiUrl),target:"_blank",rel:"noopener noreferrer",className:"font-medium text-caution-100 underline decoration-caution-500/50 underline-offset-2 hover:text-caution-50",children:"Enable Indexing API ↗"})]})]}),e.jsx("button",{type:"button",className:"text-caution-400 hover:text-caution-200",onClick:()=>ds(null),children:"×"})]})}),st&&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:[st,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>Ae(null),children:"×"})]}),_t&&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:[_t,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>Yt(null),children:"×"})]}),Pe?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[kt?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:kt.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Coverage measured"," ",ee?.lastInspectedAt?Bt(ee.lastInspectedAt):"never"]}),e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:qe(kl),children:"Disconnect"})]}):e.jsxs(xe,{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(ce,{tone:a?"caution":"negative",children:a?"Ready to connect":"App credentials missing"})]}),e.jsxs("div",{className:"mt-3 rounded-lg border border-default bg-surface px-4 py-5",children:[e.jsx("p",{className:"text-sm text-neutral",children:a?"Generate a Google OAuth link for this project and have the client sign in with a Google account that already has access to the correct Search Console property.":"Set Google OAuth client credentials first. Once configured, you can generate a consent link for this project domain."}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[a?e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:it,onClick:qe(Yr),children:it?"Opening…":"Connect Google Search Console"}):e.jsx(A,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(vs,{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."})]})]})]}),(kt||Ta)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs(xe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Performance"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Search performance"}),e.jsx(Me,{text:`${$h(x?.periodComparison)} The optional trend line shows the fitted direction. Click any day to filter the table below to that date. Query and page filters match case-insensitive substrings and run on Apply filters. Filtering and sorting examine up to ${sa.toLocaleString()} matching rows while the table shows ${Ss} per page.`})]}),x?.window?.startDate&&x.window.endDate&&e.jsxs("p",{className:"text-xs text-muted",children:[x.window.startDate," to ",x.window.endDate,(x.window.daysSinceLatestData??0)>0&&` · latest data ${x.window.daysSinceLatestData} day${x.window.daysSinceLatestData===1?"":"s"} ago`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ra,{windows:Ah,value:Q,onChange:b=>{w(b),ae(0),dt.setPage(1)},label:"Search Console time period",formatOption:b=>b==="all"?"All":b}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:Te,onClick:()=>{ae(0),dt.setPage(1),en(0),I()},children:Te?"Loading…":"Apply filters"})]})]}),x&&x.daily.length>0&&(()=>{const{totals:b,daily:K,trends:de,periodComparison:pe}=x,Je=Ni.filter(ve=>X.includes(ve.key)).map(ve=>({dataKey:ve.key,label:ve.label,color:ve.color,axisId:ve.key,inverted:ve.inverted,formatValue:ve.format,trend:F?de?.[ve.key]??null:null})),at=ve=>b[ve]??null,wt=new Map(K.map(ve=>[ve.date,ve])),rt=K.length===0?[]:vm(K[0].date,K[K.length-1].date).map(ve=>wt.get(ve)??{date:ve});return e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:Ni.map(ve=>{const Ms=X.includes(ve.key),$n=at(ve.key),Xn=$n===null;return e.jsxs("button",{type:"button","aria-pressed":Ms,disabled:Xn,className:`rounded-md border px-3 py-2 text-left transition-colors ${Ms?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${Xn?"cursor-not-allowed opacity-50":""}`,onClick:()=>{C(Ls=>Ls.includes(ve.key)?Ls.length===1?Ls:Ls.filter(Rl=>Rl!==ve.key):[...Ls,ve.key])},children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2 w-2 rounded-full",style:{backgroundColor:Ms?ve.color:"transparent",border:`1px solid ${ve.color}`}}),e.jsx("span",{className:"text-xs text-secondary",children:ve.label})]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:$n===null?"—":ve.format($n)}),e.jsx("span",{className:"block text-[11px] tabular-nums text-muted",children:Ih(pe,ve.key,ve.inverted)})]},ve.key)})}),e.jsx("div",{className:"mt-2 flex items-center justify-end",children:e.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5 text-xs text-secondary",children:[e.jsx("input",{type:"checkbox",className:"accent-mono-400",checked:F,onChange:ve=>_(ve.target.checked)}),"Trend line"]})}),e.jsx("div",{className:"mt-1",children:e.jsx(Eo,{data:rt,xKey:"date",series:Je,xTickFormatter:pn,labelFormatter:Ot,onSelectX:La,selectedX:D})}),e.jsx("div",{role:"group","aria-label":"Filter the table to a single day",children:K.map(ve=>e.jsxs("button",{type:"button",className:"sr-only focus:not-sr-only focus:inline-block focus:rounded focus:border focus:border-strong focus:bg-surface-active focus:px-2 focus:py-1 focus:text-xs focus:text-strong","aria-pressed":D===ve.date,onClick:()=>La(ve.date),children:[Ot(ve.date),": ",ve.clicks," clicks, ",ve.impressions," impressions"]},ve.date))}),D&&e.jsxs("div",{className:"mt-1 flex items-center gap-2 text-xs",children:[e.jsxs("span",{className:"text-secondary",children:["Table showing ",Ot(D)]}),e.jsxs("button",{type:"button",className:"text-link hover:underline",onClick:()=>La(D),children:["Show all ",b.days," days"]})]}),b.position!==null&&(b.positionDays??b.days)<b.days&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position covers ",b.positionDays," of ",b.days," days. The rest have no property-level position recorded."]}),(b.position===null||b.position===void 0)&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position needs a property-level sync. Run ",e.jsx("code",{children:"canonry google sync"})," to record it."]})]})})(),e.jsxs("div",{className:"mt-3 grid gap-2 lg:grid-cols-4",children:[e.jsx("input",{className:"rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"date","aria-label":"Start date",title:"Start date (inclusive). Leave blank to use the window above.",value:U.startDate,onChange:b=>T(K=>({...K,startDate:b.target.value}))}),e.jsx("input",{className:"rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"date","aria-label":"End date",title:"End date (inclusive).",value:U.endDate,onChange:b=>T(K=>({...K,endDate:b.target.value}))}),e.jsx(Us,{value:U.query,onChange:b=>T(K=>({...K,query:b})),label:"Filter search queries",placeholder:"Contains query…"}),e.jsx(Us,{value:U.page,onChange:b=>T(K=>({...K,page:b})),label:"Filter page URLs",placeholder:"Contains page URL…"})]}),h.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Date"}),e.jsx("th",{className:"text-left",children:"Query"}),e.jsx("th",{className:"text-left",children:"Page"}),Object.values(un).map(b=>e.jsx("th",{className:"text-right","aria-sort":Ct?.key===b?Ct.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:()=>{dt.setPage(1),Ts(K=>K?.key===b?K.dir==="desc"?{key:b,dir:"asc"}:null:{key:b,dir:"desc"})},children:[Ql[b],Ct?.key===b?Ct.dir==="desc"?" ↓":" ↑":""]})},b))]})}),e.jsx("tbody",{children:Ns.map((b,K)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:b.date}),e.jsx("td",{className:"max-w-xs truncate text-strong",children:b.query}),e.jsx("td",{className:"max-w-xs text-secondary",children:e.jsx(xa,{value:b.page})}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:b.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:b.impressions.toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[(Number.isFinite(b.ctr)?b.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:b.position.toFixed(1)})]},`${b.date}:${b.query}:${b.page}:${K}`))})]})}),e.jsx(Rs,{page:re?dt.page:Math.floor(G/Ss)+1,pageSize:Ss,visibleRows:Ns.length,totalRows:re?ge:void 0,hasNextPage:re?void 0:W,disabled:Te,itemLabel:re?"matches":"rows",onPageChange:b=>{if(re){dt.setPage(b);return}const K=(b-1)*Ss;ae(K),en(K)}}),re&&ge>=sa?e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Results are capped at ",sa.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(xe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Coverage"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Index coverage"}),e.jsx(Me,{text:"Google's Indexing API is intended for eligible JobPosting and BroadcastEvent pages. Sitemap resubmission is the general-site bulk path."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[ee&&ee.notIndexed.length>0&&e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:R,onClick:()=>{fs()},children:R?"Requesting…":`Request indexing (${ee.notIndexed.length})`}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:ht,onClick:()=>{Ce(!0)},children:ht?"Loading…":"Reload saved coverage"})]})]}),ee&&ee.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const b=ee.summary.indexed+ee.summary.notIndexed,K=b>0?ee.summary.indexed/b:0,de=b>0?ee.summary.notIndexed/b:0,pe=54,Qe=2*Math.PI*pe,Je=Qe*(1-K),at=Qe*de,wt=Qe*K;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:pe,fill:"none",stroke:os.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:pe,fill:"none",stroke:Is.positiveDeep,strokeWidth:"14",strokeDasharray:Qe,strokeDashoffset:Je,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),ee.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:pe,fill:"none",stroke:os.textFaint,strokeWidth:"14",strokeDasharray:`${at} ${Qe-at}`,strokeDashoffset:-wt,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:[(K*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:ee.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:ee.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:["Not indexed",(ee.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-faint",children:["· ",(ee.reasonGroups??[]).length," ",(ee.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),ee.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:ee.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(b=>{const K=b==="indexed"?ee.indexed.length:b==="notIndexed"?ee.notIndexed.length:ee.deindexed.length,de=b==="indexed"?"Indexed":b==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",role:"tab","aria-selected":ot===b,className:`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${ot===b?"border-accent text-heading":"border-transparent text-secondary hover:border-mono-600 hover:text-strong"}`,onClick:()=>{cs(b),Zt(null)},children:[de," (",K,")"]},b)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[ot==="indexed"&&ee.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:$e.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.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:b.crawlTime?b.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:b.isMobileFriendly===!0?"Yes":b.isMobileFriendly===!1?"No":"—"})]},b.id))})]}),ot==="notIndexed"&&!jt&&(ee.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:(ee.reasonGroups??[]).map(b=>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:()=>Zt(b.reason),onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),Zt(b.reason))},tabIndex:0,role:"button","aria-label":`View ${b.reason} pages`,children:[e.jsx("td",{className:"text-strong",children:b.reason}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:b.count})]},b.reason))})]}),ot==="notIndexed"&&!jt&&(ee.reasonGroups??[]).length===0&&ee.notIndexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Indexing State"}),e.jsx("th",{className:"text-left",children:"Coverage"})]})}),e.jsx("tbody",{children:Wt.map(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.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:b.coverageState??"Unknown"})]},b.id))})]}),ot==="notIndexed"&&jt&&(()=>{const b=(ee.reasonGroups??[]).find(K=>K.reason===jt);return b?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:()=>Zt(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:b.reason}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[b.count," affected page",b.count!==1?"s":""]})]}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:R,onClick:()=>{Ut(b.urls.map(K=>K.url))},children:R?"Requesting…":`Request indexing (${b.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:gs.map(K=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:K.url}),e.jsx("td",{className:"text-secondary",children:K.crawlTime?K.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-strong transition-colors",disabled:R,onClick:()=>{Ut([K.url])},title:"Request indexing",children:"Index"})})]},K.id))})]})]}):null})(),ot==="deindexed"&&ee.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:yt.map((b,K)=>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.previousState}),e.jsx("td",{className:"text-secondary",children:b.currentState}),e.jsx("td",{className:"text-secondary",children:b.transitionDate.split("T")[0]})]},`${b.url}-${K}`))})]}),(ot==="indexed"&&ee.indexed.length===0||ot==="notIndexed"&&!jt&&ee.notIndexed.length===0||ot==="deindexed"&&ee.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),e.jsx(Rs,{page:ie,pageSize:Es,visibleRows:Math.min(Es,se.length-le),totalRows:se.length,onPageChange:ps,itemLabel:"URLs"})]}),e.jsxs("div",{className:"mt-4 border-t border-default pt-3",children:[e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between text-left text-xs text-secondary hover:text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400","aria-expanded":Mt,onClick:()=>Kt(b=>!b),children:[e.jsx("span",{children:"Coverage history"}),e.jsx("span",{children:Mt?"Hide snapshots":ct.length>0?`View ${ct.length} snapshots`:"View history"})]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["Current: ",ee.summary.indexed.toLocaleString()," indexed, ",ee.summary.notIndexed.toLocaleString()," not indexed.",Lt&&e.jsxs(e.Fragment,{children:[" Since the last snapshot: ",Lt.indexed>=0?"+":"",Lt.indexed.toLocaleString()," indexed, ",Lt.notIndexed>=0?"+":"",Lt.notIndexed.toLocaleString()," not indexed."]})]}),Mt&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:ct.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:ct.map(b=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:b.date}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:b.indexed.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:b.notIndexed.toLocaleString()})]},b.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:ht?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),e.jsxs(xe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Sitemaps"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Sitemap operations"}),e.jsx(Me,{text:"Submitting asks Google to refetch these sitemaps. Indexing is not guaranteed."})]})]}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:ye||!kt?.propertyId,onClick:()=>{Ma()},children:ye?"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:Re,onChange:b=>be(b.target.value),onKeyDown:b=>b.key==="Enter"&&void fn([Re.trim()])}),e.jsx(A,{type:"button",size:"sm",disabled:!ws||ze||!Re.trim(),onClick:()=>{fn([Re.trim()])},children:ze?"Submitting…":"Submit sitemap to Google"})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:!ws||ze||gn.length===0,onClick:()=>{fn(gn)},children:ze?"Resubmitting…":Jt}),e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:!ws||ze||!It?.length,onClick:()=>{Cl()},children:"Resubmit all files"}),Ee&&e.jsxs("span",{className:"text-xs text-muted",children:["Top level: ",Ee.indexes," index",Ee.indexes===1?"":"es",", ",Ee.files," file",Ee.files===1?"":"s"]}),gt&&e.jsxs("span",{className:"text-xs text-secondary",children:["Submitting ",gt.completed,"/",gt.total]})]}),!ws&&kt&&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:qe(Yr),children:"Reconnect"})]}),It&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:It.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Us,{value:vt,onChange:b=>{Ft(b),Ht.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:Ht.rows.flatMap(b=>{const K=wi(b),de=Si(b),pe=Ci(b),Qe=et[b.path]??[],Je=Ke.has(b.path),at=e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs text-strong",children:e.jsx(xa,{value:b.path})}),e.jsx("td",{className:"text-secondary",children:b.isSitemapsIndex?e.jsx("button",{type:"button",className:"text-secondary hover:text-strong","aria-expanded":Je,"aria-label":`${Je?"Collapse":"Expand"} files in ${b.path}`,onClick:()=>{Sl(b.path)},children:Be.has(b.path)?"Loading…":`${Je?"▾":"▸"} Index${et[b.path]?` (${Qe.length})`:""}`}):"Sitemap"}),e.jsx("td",{className:"text-secondary",children:pe}),e.jsx("td",{className:"text-secondary",children:b.lastSubmitted?b.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:b.lastDownloaded?b.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:K.toLocaleString()}),e.jsx("td",{className:"max-w-48 text-secondary",children:de||"—"}),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:!ws||ze,onClick:()=>{fn([b.path])},children:b.lastSubmitted?"Resubmit to Google":"Submit to Google"}),kt?.sitemapUrl===b.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:je,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{Vr(b.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:In.isPending,onClick:()=>{zr(b.path)},children:"Inspect URLs"})]})})]},b.path),wt=b.isSitemapsIndex&&Je?Qe.map(rt=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs pl-6 text-secondary",children:e.jsx(xa,{value:rt.path})}),e.jsx("td",{className:"text-secondary",children:"File"}),e.jsx("td",{className:"text-secondary",children:Ci(rt)}),e.jsx("td",{className:"text-secondary",children:rt.lastSubmitted?rt.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:rt.lastDownloaded?rt.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:wi(rt).toLocaleString()}),e.jsx("td",{className:"text-secondary",children:Si(rt)||"—"}),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:!ws||ze,onClick:()=>{fn([rt.path])},children:"Resubmit"}),kt?.sitemapUrl===rt.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:je,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{Vr(rt.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:In.isPending,onClick:()=>{zr(rt.path)},children:"Inspect URLs"})]})})]},`${b.path}:${rt.path}`)):[];return[at,...wt]})})]}),e.jsx(Rs,{page:Ht.page,pageSize:Ss,visibleRows:Ht.rows.length,totalRows:Ht.totalRows,onPageChange:Ht.setPage,itemLabel:"sitemaps"})]}):e.jsx("p",{className:"text-sm text-muted",children:"No sitemaps found for this property."})})]}),e.jsxs(xe,{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:b=>v(b.target.value),onKeyDown:b=>b.key==="Enter"&&void Jr()}),e.jsx(A,{type:"button",size:"sm",disabled:Ne||!kt?.propertyId||!p.trim(),onClick:qe(Jr),children:Ne?"Inspecting…":"Inspect URL"})]}),N&&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:N.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:N.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:Xr(N.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:Bt(N.crawlTime)})]})]})]}),e.jsxs(xe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Inspection log"})]}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:O,onClick:()=>{he(!0)},children:O?"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:Oe,onChange:b=>Fe(b.target.value)}),e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:O,onClick:()=>{he(!0)},children:"Apply filter"})]}),d.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:d.map(b=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:b.url}),e.jsx("td",{className:"text-neutral",children:b.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:b.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:b.coverageState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:Xr(b.isMobileFriendly??null)}),e.jsx("td",{className:"text-secondary",children:Bt(b.inspectedAt)})]},b.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No inspection history yet."})]}),e.jsxs(xe,{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"})]})}),y.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:y.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.previousState??"Unknown"}),e.jsx("td",{className:"text-neutral",children:b.currentState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:Bt(b.transitionDate)})]},`${b.url}:${b.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No deindexed transitions recorded."})]})]}),kt&&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:()=>ls(b=>!b),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 ${Tt?"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"})]})}),Tt&&e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(xe,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Property"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Pick the Search Console property"}),e.jsx(Me,{text:"The selected property is used for future syncs and URL inspections for this project."})]})]})}),e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:`gsc-property-${t}`,children:"Property URL"}),e.jsx("select",{id:`gsc-property-${t}`,className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none",value:M,disabled:Xe||c.length===0,onChange:b=>k(b.target.value),children:c.length===0?e.jsx("option",{value:"",children:Xe?"Loading properties…":"No properties available"}):c.map(b=>e.jsxs("option",{value:b.siteUrl,children:[b.siteUrl," · ",b.permissionLevel]},b.siteUrl))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:Xe,onClick:()=>{Jn(kt,!0)},children:Xe?"Refreshing…":"Refresh properties"}),e.jsx(A,{type:"button",size:"sm",disabled:!M||Ve,onClick:qe(Al),children:Ve?"Saving…":"Save property"})]})]})]}),e.jsxs(xe,{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:S,onChange:b=>$(b.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:b=>L(b.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(A,{type:"button",size:"sm",disabled:Rn.isPending||!kt.propertyId,onClick:qe(Pl),children:Rn.isPending?"Queueing…":"Queue sync"}),!kt.propertyId&&e.jsx("p",{className:"text-xs text-caution-400",children:"Select a Search Console property before queueing a sync."})]})]})]})})]})]})]})}const Mh=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function Lh({projectName:t,projectId:s}){const n=js(),[a,r]=l.useState(null),[o,i]=l.useState(null),[c,u]=l.useState(!1),h=we(Ir({client:H,path:{name:t}})),m=h.data?.find(z=>z.connectionType==="gbp"),x=!!m,g=a?{locationName:a}:void 0,d=we({...lc({client:H,path:{name:t}}),enabled:x}),f=we({...cc({client:H,path:{name:t},query:g}),enabled:x}),y=we({...dc({client:H,path:{name:t},query:g}),enabled:x}),j=we({...uc({client:H,path:{name:t},query:g}),enabled:x}),N=we({...mc({client:H,path:{name:t},query:g}),enabled:x}),P=we({...hc({client:H,path:{name:t},query:g}),enabled:x}),M=we({queryKey:["gbp-section-insights",t],queryFn:()=>xc(t),enabled:x});function k(){Nt(n,"gbp")}const p=Pt({...pc(),onSuccess:z=>{So({id:z.runId,projectId:s,kind:zs["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),Se({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),v=l.useSyncExternalStore(Co,ba,ba),S=Object.values(v.runs).some(z=>z.kind===zs["gbp-sync"]&&z.projectId===s),$=p.isPending||S,q=Pt({...gc(),onSuccess:()=>k()});if(l.useEffect(()=>{if(!a||!d.data)return;const z=d.data.locations.filter(re=>re.selected);(z.length<=1||!z.some(re=>re.locationName===a))&&r(null)},[a,d.data]),l.useEffect(()=>{if(!o||!d.data)return;(a?[a]:d.data.locations.filter(re=>re.selected).map(re=>re.locationName)).includes(o)||i(null)},[o,d.data,a]),h.isLoading)return null;if(!m){const z=[{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(xe,{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:z.map((re,ue)=>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:ue+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:re.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:re.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:re.note})]})]},re.title))})]})})}const L=f.data,Q=d.data?.locations??[],w=Q.filter(z=>z.selected),X=y.data?.keywords??[],C=j.data?.lodging??[],F=N.data?.placeActions??[],_=P.data?.places??[],D=Q.length>0?Q[0].accountName:m.domain,Z=a?Q.find(z=>z.locationName===a)?.displayName??null:null,oe=a?Q.filter(z=>z.locationName===a):w,ne=new Set(oe.map(z=>z.locationName)),U=C.filter(z=>ne.has(z.locationName)),T=F.filter(z=>ne.has(z.locationName)),G=_.filter(z=>ne.has(z.locationName)),ae=new Set(w.map(z=>z.locationName)),W=a?X:X.filter(z=>ae.has(z.locationName)),J=!a&&w.length>1,ge=(M.data??[]).filter(z=>!z.dismissed&&Mh.has(z.type)&&(!Z||z.query===Z||z.query===a||z.title.startsWith(Z)));return e.jsx("section",{className:"page-section-divider",children:e.jsxs(xe,{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(Me,{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(ce,{tone:"positive",children:"Connected"}),!te()&&e.jsx(De,{type:"button",variant:"outline",size:"sm",disabled:$,onClick:()=>p.mutate({client:H,path:{name:t},body:{}}),children:$?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-muted",children:[D?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-secondary",children:D})," · "]}):null,d.data?`${d.data.totalSelected} of ${d.data.totalDiscovered} locations tracked`:"Loading locations…"]}),w.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:z=>r(z.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"}),w.map(z=>e.jsx("option",{value:z.locationName,children:z.displayName},z.id))]})]}),w.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:[ge.length>0&&e.jsxs("div",{className:"mb-6 grid gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Needs attention"}),ge.map(z=>e.jsx("div",{className:["insight-card",Qh(z.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:[z.title,z.recommendation?.reason&&e.jsx(Me,{text:z.recommendation.reason})]})},z.id))]}),L&&e.jsx(Jh,{performance:L.performance,freshness:L.freshness,timeseries:L.timeseries}),L?.profileCompleteness&&e.jsx(Eh,{summary:L.profileCompleteness}),oe.length>0&&e.jsx(qh,{locations:oe,lodging:U,places:G,placeActions:T,expandedLocation:o,onToggleExpanded:z=>{i(re=>re===z?null:z)}}),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"}),y.data&&y.data.total>0&&e.jsxs("span",{className:"text-[11px] text-faint",children:[y.data.thresholdedPct,"% privacy-thresholded"]})]}),W.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"}),J&&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:W.slice(0,25).map(z=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-neutral",children:z.keyword}),J&&e.jsx("td",{className:"text-muted",children:Q.find(re=>re.locationName===z.locationName)?.displayName??z.locationName}),e.jsx("td",{className:"text-right font-mono text-strong",children:z.valueCount!==null?z.valueCount.toLocaleString():e.jsxs("span",{className:"text-muted",title:"Privacy floor — Google withheld the exact count",children:["<",z.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-faint",children:[z.periodStart,"–",z.periodEnd]})]},`${z.locationName}:${z.keyword}`))})]})]})]}),e.jsxs("div",{className:"mt-6 border-t border-default pt-4",children:[e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 text-xs font-medium text-secondary hover:text-strong",onClick:()=>u(z=>!z),"aria-expanded":c,children:[e.jsx("span",{"aria-hidden":"true",children:c?"▾":"▸"})," Manage locations (",Q.length,")"]}),c&&e.jsx("div",{className:"mt-3",children:Q.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"}),!te()&&e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:Q.map(z=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:z.displayName}),e.jsx("td",{className:"text-muted",children:z.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(ce,{tone:z.selected?"positive":"neutral",children:z.selected?"Tracked":"Not tracked"})}),!te()&&e.jsx("td",{className:"text-right",children:e.jsx(De,{type:"button",variant:"outline",size:"sm",disabled:q.isPending,onClick:()=>q.mutate({client:H,path:{name:t,locationName:z.locationName},body:{selected:!z.selected}}),children:z.selected?"Untrack":"Track"})})]},z.id))})]})})]})]})})}function Eh({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:Mn(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:Mn(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:Mn(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:Mn(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:Mn(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(Me,{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 ${zh(a.tone)}`,children:a.value}),a.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-faint",children:a.detail})]},a.label))})]})}function qh({locations:t,lodging:s,places:n,placeActions:a,expandedLocation:r,onToggleExpanded:o}){const i=new Map(s.map(h=>[h.locationName,h])),c=new Map(n.map(h=>[h.locationName,h])),u=new Map;for(const h of a){const m=u.get(h.locationName)??[];m.push(h),u.set(h.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(Me,{text:te()?"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest sync, not that every Google product lacks the information.":"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest Canonry sync, not that every Google product lacks the information."})]}),e.jsxs("span",{className:"text-[11px] text-faint",children:[t.length," location",t.length===1?"":"s"]})]}),e.jsx("div",{className:"data-table-wrapper",children:e.jsxs("table",{className:"data-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"min-w-[14rem]",children:"Location"}),e.jsx("th",{className:"min-w-[15rem]",children:"Owner profile"}),e.jsx("th",{className:"min-w-[11rem]",children:"Hotel data"}),e.jsx("th",{className:"min-w-[11rem]",children:"Public Maps"}),e.jsx("th",{className:"min-w-[10rem]",children:"CTAs"}),e.jsx("th",{className:"text-right",children:"Detail"})]})}),e.jsx("tbody",{children:t.map(h=>{const m=i.get(h.locationName)??null,x=c.get(h.locationName)??null,g=u.get(h.locationName)??[],d=r===h.locationName;return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-strong",children:h.displayName}),e.jsx("p",{className:"mt-1 text-xs text-faint",children:h.primaryCategoryDisplayName??"Primary category not returned"}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[e.jsx(ce,{tone:h.selected?"positive":"neutral",children:h.selected?"Tracked":"Not tracked"}),h.openStatus&&h.openStatus!=="OPEN"&&e.jsx(ce,{tone:h.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:Xo(h.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(Oh,{location:h})}),e.jsx("td",{children:e.jsx(Fh,{lodging:m})}),e.jsx("td",{children:e.jsx(Kh,{place:x,mapsUri:h.mapsUri})}),e.jsx("td",{children:e.jsx(Uh,{actions:g})}),e.jsx("td",{className:"text-right",children:e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>o(h.locationName),children:d?"Hide":"Details"})})]}),d&&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(Vh,{location:h,lodging:m,place:x,placeActions:g})})})]},h.id)})})]})})]})}function Dh(t){return[{label:"Description",tone:ln(t.description)?"positive":"neutral",value:ln(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:ln(t.primaryPhone)?"positive":"neutral",value:ln(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:ln(t.websiteUri)?"positive":"neutral",value:ln(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 Oh({location:t}){const s=Dh(t);return e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>e.jsxs(ce,{tone:n.tone,children:[n.label," ",n.value]},n.label))})}function Fh({lodging:t}){return e.jsx($r,{...Gh(t)})}function Gh(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 Kh({place:t,mapsUri:s}){return e.jsx($r,{..._h(t,s)})}function _h(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 Uh({actions:t}){return e.jsx($r,{...Bh(t)})}function Bh(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 $r({tone:t,label:s,detail:n}){return e.jsxs("div",{children:[e.jsx(ce,{tone:t,children:s}),e.jsx("p",{className:"mt-1.5 text-xs leading-5 text-faint",children:n})]})}function Vh({location:t,lodging:s,place:n,placeActions:a}){const r=s?Wh(s.attributes):[];return e.jsxs("div",{className:"grid gap-5 text-xs lg:grid-cols-3",children:[e.jsxs(za,{title:"Owner profile · Business Information",children:[e.jsx(Et,{label:"Primary category",value:t.primaryCategoryDisplayName??"Not returned"}),e.jsx(Et,{label:"Secondary categories",value:t.additionalCategories.length>0?t.additionalCategories.join(", "):"Not returned"}),e.jsx(Et,{label:"Description",value:ln(t.description)?t.description:"Not returned"}),e.jsx(Et,{label:"Hours",value:t.regularHours?"Returned by Google":"Not returned"}),e.jsx(Et,{label:"Service area",value:t.serviceArea?"Returned by Google":"Not returned"}),e.jsx(Et,{label:"Phone",value:t.primaryPhone??"Not returned"}),e.jsx(Et,{label:"Website",value:t.websiteUri??"Not returned"}),e.jsx(Et,{label:"Open status",value:Xo(t.openStatus)}),e.jsx(Et,{label:"Opening date",value:t.openingDate??"Not returned"})]}),e.jsx(za,{title:"Hotel data · Lodging API",children:s?e.jsxs(e.Fragment,{children:[e.jsx(Et,{label:"Last checked",value:ki(s.syncedAt)}),e.jsx(Et,{label:"Groups returned",value:String(s.populatedGroupCount)}),e.jsx(Et,{label:"Populated groups",value:r.length>0?r.join(", "):"None returned"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Lodging API snapshot was stored for this location."})}),e.jsxs(za,{title:"Public listing + CTAs",children:[n?e.jsxs(e.Fragment,{children:[e.jsx(Et,{label:"Places tier",value:n.tier}),e.jsx(Et,{label:"Last checked",value:ki(n.syncedAt)}),e.jsx(Et,{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(o=>e.jsxs("div",{className:"grid gap-0.5",children:[e.jsxs("span",{className:"font-medium text-neutral",children:[Sa(o.placeActionType),o.isPreferred?" · preferred":""]}),e.jsxs("span",{className:"text-faint",children:[Sa(o.providerType),o.uri?` · ${Hh(o.uri)}`:""]})]},o.placeActionLinkName))})})]})]})}function za({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 Et({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 Mn(t,s,n){return t===s?"positive":t===0?n:"caution"}function zh(t){switch(t){case"positive":return"text-positive";case"caution":return"text-caution";case"negative":return"text-negative";case"neutral":return"text-neutral"}}function Qh(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function ln(t){return typeof t=="string"&&t.trim().length>0}function Xo(t){return t?Sa(t):"Not returned"}function Sa(t){return t?t.toLowerCase().split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"Unknown"}function Hh(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function ki(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Wh(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&Yh(n)).map(([s])=>Sa(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function Yh(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function Jh({performance:t,freshness:s,timeseries:n}){const a=t.totals,r=fc.filter(f=>(a[f]??0)>0),o=yc.filter(f=>(a[f]??0)>0),i=Object.keys(a).filter(f=>(a[f]??0)>0&&bc(f)==="other").sort((f,y)=>(a[y]??0)-(a[f]??0)),c=Object.keys(a).filter(f=>(a[f]??0)===0).sort(),u=n.map(f=>{const y={date:f.date};for(const[j,N]of Object.entries(f.metrics))y[j]=N;return y}),h=n.find(f=>f.pending)?.date,m=n.length>0?n[n.length-1].date:void 0,x=u.length>0,g=s.dataThroughDate?`Data through ${Ot(s.dataThroughDate)}${s.pendingDays>0?` · ${s.pendingDays}d pending`:""}`:null,d=[...r,...i];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"}),g&&e.jsx("span",{className:"text-[11px] text-muted",children:g})]}),!x||r.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No profile action activity yet — run a sync."}):e.jsxs(e.Fragment,{children:[e.jsx(Ai,{data:u,metrics:r,kind:"line",firstPending:h,lastDate:m}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-x-5 gap-y-1",children:d.map(f=>e.jsxs("span",{className:"text-sm text-secondary",children:[va(f)," ",e.jsx("span",{className:"font-mono text-heading",children:(a[f]??0).toLocaleString()})]},f))})]})]}),x&&o.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(Ai,{data:u,metrics:o,kind:"area",firstPending:h,lastDate:m})]}),c.length>0&&e.jsxs("p",{className:"text-xs text-faint",children:["Not active: ",c.map(f=>va(f)).join(", ")]})]})}function Ai({data:t,metrics:s,kind:n,firstPending:a,lastDate:r}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(Ws,{width:"100%",height:"100%",children:e.jsxs(Ys,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Vn,{stroke:Bn,vertical:!1}),e.jsx(Js,{dataKey:"date",tick:Rt,tickLine:!1,axisLine:{stroke:is},tickFormatter:pn,minTickGap:24}),e.jsx(Xs,{tick:Rt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Zs,{...as,labelFormatter:Ot,formatter:(o,i)=>[typeof o=="number"?o.toLocaleString():String(o??0),va(String(i??""))]}),e.jsx(wa,{wrapperStyle:{fontSize:11,color:os.text},formatter:o=>va(o)}),a&&r&&e.jsx(xr,{x1:a,x2:r,fill:os.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:os.textDim,fontSize:10}}),s.map((o,i)=>n==="line"?e.jsx(As,{type:"monotone",dataKey:o,stroke:nt[i%nt.length],strokeWidth:2,dot:!1,isAnimationActive:!1},o):e.jsx(Fs,{type:"monotone",dataKey:o,stackId:"reach",stroke:nt[i%nt.length],fill:nt[i%nt.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},o))]})})})}function Xh(t){return qo($s(String(t)))}function Zh(t){return Bs($s(String(t)))}function Qa({children:t,label:s="More info",placement:n="top",className:a}){const r=l.useId(),[o,i]=l.useState(!1);return e.jsxs("span",{className:`relative inline-flex ${a??""}`,children:[e.jsx("button",{type:"button","aria-label":s,"aria-describedby":o?r:void 0,className:"inline-flex h-4 w-4 items-center justify-center rounded-full text-muted hover:text-strong focus:text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),onFocus:()=>i(!0),onBlur:()=>i(!1),children:e.jsx(nm,{className:"h-3.5 w-3.5","aria-hidden":!0})}),o&&e.jsx("span",{id:r,role:"tooltip",className:`absolute z-50 w-64 rounded border border-strong bg-bg-elevated px-3 py-2 text-xs font-normal leading-relaxed text-strong shadow-lg ${n==="top"?"bottom-full mb-2":"top-full mt-2"} left-1/2 -translate-x-1/2 whitespace-normal`,children:t})]})}const na=Ss;function yn(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function Ha(t){return t.toLocaleString()}function ex(t){const s=Number(t);return Number.isFinite(s)?`${(s*100).toFixed(1)}%`:"—"}function tx(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 sx(t){const s=t.filter(n=>n.kind===zs["backlink-extract"]&&!ko(n.status));return s.length===0?null:s.reduce((n,a)=>n.createdAt>a.createdAt?n:a)}function nx(t,s){const n=new Date(t??s).getTime(),a=Math.max(0,Math.floor((Date.now()-n)/1e3));if(a<60)return`${a}s`;const r=Math.floor(a/60),o=a%60;return o===0?`${r}m`:`${r}m ${o}s`}function ax({projectName:t}){const[s,n]=l.useState(null),[a,r]=l.useState(null),[o,i]=l.useState([]),[c,u]=l.useState(null),[h,m]=l.useState(null),[x,g]=l.useState(null),[d,f]=l.useState(Date.now()),[y,j]=l.useState(0),[N,P]=l.useState(!0),[M,k]=l.useState(!1),[p,v]=l.useState(null),S=l.useCallback(async()=>{P(!0),v(null);try{const[D,Z,oe,ne,U]=await Promise.all([vc().catch(()=>null),jc(t,{excludeCrawlers:!0}).catch(()=>null),Nc(t,{limit:na,offset:y,excludeCrawlers:!0}).catch(G=>{if(G instanceof hn&&G.code==="NOT_FOUND")return null;throw G}),wc(t).catch(()=>[]),Sc(t).catch(()=>[])]);u(D),n(Z),r(oe),i(ne);const T=sx(U);m(T)}catch(D){v(D instanceof Error?D.message:"Failed to load backlinks")}finally{P(!1)}},[t,y]);l.useEffect(()=>{S()},[S]),l.useEffect(()=>{if(!h)return;const D=h.id;let Z=!1;const oe=async()=>{try{const U=await hr(D);if(Z)return;ko(U.status)?(m(null),g(U),await S()):m(T=>T?.id===U.id?{...T,...U}:T)}catch{}},ne=window.setInterval(()=>{oe()},3e3);return()=>{Z=!0,window.clearInterval(ne)}},[h,S]),l.useEffect(()=>{if(!h)return;const D=window.setInterval(()=>f(Date.now()),1e3);return()=>window.clearInterval(D)},[h]),l.useEffect(()=>{if(!x||x.status==="failed")return;const D=window.setTimeout(()=>g(null),1e4);return()=>window.clearTimeout(D)},[x]);async function $(){k(!0),v(null);try{const D=await kc(t);m(D)}catch(D){D instanceof hn&&D.code==="MISSING_DEPENDENCY"?v("DuckDB is not installed. Visit the Backlinks admin page to install it."):v(D instanceof Error?D.message:"Failed to trigger extract")}finally{k(!1)}}const q=l.useMemo(()=>o.slice().sort((D,Z)=>D.queriedAt.localeCompare(Z.queriedAt)).map(D=>({date:D.queriedAt,linkingDomains:D.totalLinkingDomains})),[o]),L=a?.rows??[],Q=a?.total??0,w=s?.excludedLinkingDomains??0,X=Math.floor(y/na)+1;return l.useEffect(()=>{y>0&&y>=Q&&j(0)},[y,Q]),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(xe,{className:"surface-card p-4 mb-4 border-negative-800/60",children:e.jsx("p",{className:"text-sm text-negative",children:p})}),h&&e.jsx(xe,{className:"surface-card p-4 mb-4 border-info-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(em,{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(ce,{tone:"neutral",children:h.status}),e.jsxs("span",{className:"text-sm text-secondary tabular-nums",children:[nx(h.startedAt??null,h.createdAt)," elapsed · refreshing every 3s"]}),e.jsxs("span",{className:"sr-only",children:["now=",d]})]}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Refreshing this project from the current Common Crawl release."})]})]})}),x&&!h&&e.jsx(xe,{className:`surface-card p-4 mb-4 ${x.status==="failed"?"border-negative-800/60":"border-positive-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[x.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(tm,{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 ${x.status==="failed"?"text-negative":"text-positive"}`,children:x.status==="failed"?"Extract failed":"Extract complete"}),x.error?e.jsx("p",{className:"text-sm text-secondary mt-1",children:Cc(x.error)}):x.status!=="failed"?e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),C()]});function C(){return N?e.jsx(xe,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading backlinks…"})}):F()}function F(){const D=s!==null&&s.totalLinkingDomains>0,Z=x?.status==="failed",oe=s!==null&&s.totalLinkingDomains===0&&!Z,ne=c?.status==="ready",U=c?.status==="failed",T=c&&(c.status==="downloading"||c.status==="querying"||c.status==="queued");return D?_(e.jsxs(e.Fragment,{children:[!te()&&e.jsxs(e.Fragment,{children:[e.jsxs(A,{type:"button",variant:"outline",size:"sm",disabled:M||h!==null,onClick:qe($),children:[e.jsx(To,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":M?"Queuing…":"Re-run extract"]}),e.jsx(Qa,{label:"About re-running",children:"Re-queries the current release for this project without downloading it again."})]}),!te()&&e.jsx(A,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:yn("/backlinks"),children:"Open admin"})})]})):e.jsx(xe,{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(sm,{className:"h-5 w-5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1",children:[!c&&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."}),!te()&&e.jsx("div",{className:"mt-4",children:e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:yn("/backlinks"),children:"Set up backlinks"})})})]}),T&&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 (",c.status,c.phaseDetail?` — ${c.phaseDetail}`:"","). Backlinks will appear here once it finishes."]}),!te()&&e.jsx("div",{className:"mt-4",children:e.jsx(A,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:yn("/backlinks"),children:"View sync status"})})})]}),U&&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:c.error??"The workspace release sync failed. Retry from the Backlinks admin page."}),!te()&&e.jsx("div",{className:"mt-4",children:e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:yn("/backlinks"),children:"Go to Backlinks admin"})})})]}),ne&&!T&&!oe&&!Z&&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:c.release})," is ready. Run an extract for this project."]}),!te()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(A,{type:"button",size:"sm",disabled:M||h!==null,onClick:qe($),children:[e.jsx(Un,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":M?"Queuing…":"Run extract"]}),e.jsx(Qa,{label:"About extraction",children:"Queries the current release for this project without downloading it again."})]})]}),Z&&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."}),!te()&&e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:yn("/backlinks"),children:"Go to Backlinks admin"})})})]}),oe&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No referring domains found"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["The latest release found no referring domains for ",s.targetDomain,". Try a newer release or re-run this extract."]}),!te()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:yn("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(A,{type:"button",variant:"outline",size:"sm",disabled:M||h!==null,onClick:qe($),children:[e.jsx(Un,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":M?"Queuing…":"Re-run extract"]}),e.jsxs(Qa,{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 _(D){if(!s)return null;const Z="Linking hosts",oe="linking hosts",ne="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:Ha(s.totalLinkingDomains)})}),e.jsxs("p",{className:"metric-card-sub",children:["unique domains linking to ",s.targetDomain]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("p",{className:"metric-card-eyebrow",children:["Total ",oe]}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:Ha(s.totalHosts)})}),e.jsxs("p",{className:"metric-card-sub",children:["aggregate ",oe," across referring domains"]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsx("p",{className:"metric-card-eyebrow",children:"Top-10 concentration"}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:ex(s.top10HostsShare)})}),e.jsxs("p",{className:"metric-card-sub",children:["share of ",oe," from the 10 largest linking domains"]})]})]}),e.jsxs("p",{className:"text-xs text-muted mt-2",children:[e.jsx("span",{className:"text-secondary",children:"Common Crawl"})," · ",ne," ",e.jsx("code",{className:"text-secondary",children:s.release})," · queried ",tx(s.queriedAt),w>0&&e.jsxs(e.Fragment,{children:[" · ",w," excluded domain",w===1?"":"s"]})]}),q.length>=2&&e.jsxs(xe,{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(Ws,{width:"100%",height:"100%",children:e.jsxs(Ys,{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:nt[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:nt[0],stopOpacity:0})]})}),e.jsx(Js,{dataKey:"date",tick:Rt,stroke:is,tickFormatter:Xh}),e.jsx(Xs,{tick:Rt,stroke:is,allowDecimals:!1}),e.jsx(Zs,{contentStyle:as.contentStyle,labelStyle:as.labelStyle,itemStyle:as.itemStyle,labelFormatter:Zh}),e.jsx(Fs,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:nt[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(xe,{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:Z})]})}),e.jsxs("tbody",{children:[L.map(U=>e.jsxs("tr",{className:"border-b border-mono-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-strong",children:U.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-secondary tabular-nums",children:Ha(U.numHosts)})]},U.linkingDomain)),L.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-muted",colSpan:2,children:w>0&&Q===0?`Every referring domain in this ${ne} was a crawler/proxy host (${w} hidden).`:`No referring domains in this ${ne}.`})})]})]})}),e.jsx(Rs,{page:X,pageSize:na,visibleRows:L.length,totalRows:Q,onPageChange:U=>j((U-1)*na)})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:D})]})}}function rx({projectName:t}){const s=we({...Ac({client:H,path:{name:t}}),staleTime:Ao}),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:_n(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:Vt()?"text-sm text-secondary":"text-sm text-muted",children:n.reason==="no-queries"?"Add queries to start tracking AI citations.":Vt()?Qs:"Run a sweep to see which engines cite this project."})]});const{providersCiting:r,providersMentioning:o,providersConfigured:i}=n.summary;return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsxs("h2",{className:"flex items-center gap-2",children:["Cited by ",r," of ",i," engines",e.jsx(Me,{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 ",o," of ",i," engine answers",e.jsx(Me,{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(ix,{data:n}),e.jsx(ox,{data:n}),n.competitorGaps.length>0&&e.jsx(ux,{data:n})]})}function ix({data:t}){const{totalQueries:s,queriesCitedAndMentioned:n,queriesCitedOnly:a,queriesMentionedOnly:r,queriesInvisible:o}=t.summary;return e.jsxs("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4 mb-4",children:[e.jsx(aa,{label:"Cited + mentioned",value:`${n} / ${s}`,helper:"In sources AND named in answer",tone:n>0?"positive":"neutral"}),e.jsx(aa,{label:"Cited only",value:`${a} / ${s}`,helper:"In sources, not named in answer",tone:a>0?"positive-dim":"neutral"}),e.jsx(aa,{label:"Mentioned only",value:`${r} / ${s}`,helper:"Named in answer, no source link",tone:r>0?"caution":"neutral"}),e.jsx(aa,{label:"Invisible",value:`${o} / ${s}`,helper:"No engine cites or mentions",tone:o>0?"negative":"neutral"})]})}function aa({label:t,value:s,helper:n,tone:a}){const r=a==="positive"?"text-positive":a==="positive-dim"?"text-positive-400/70":a==="caution"?"text-caution":a==="negative"?"text-negative":"text-heading";return e.jsxs("div",{className:"rounded-md border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:t}),e.jsx("p",{className:`mt-1 text-2xl font-semibold tabular-nums ${r}`,children:s}),e.jsx("p",{className:"text-[11px] text-muted",children:n})]})}function ox({data:t}){const s=l.useMemo(()=>{const n=new Set;for(const a of t.byQuery)for(const r of a.providers)n.add(r.provider);return Array.from(n).sort()},[t.byQuery]);return t.byQuery.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No query coverage rows."}):e.jsxs("div",{children:[e.jsx(lx,{}),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(Cn,{provider:n})},n)),e.jsx("th",{className:"text-right",children:"Cite"}),e.jsx("th",{className:"text-right",children:"Ment"})]})}),e.jsx("tbody",{children:t.byQuery.map(n=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:n.query}),s.map(a=>{const r=n.providers.find(o=>o.provider===a);return e.jsx("td",{className:"text-center",children:r==null?e.jsx(am,{className:"inline h-3.5 w-3.5 text-mono-700","aria-label":"no data"}):e.jsx(cx,{provider:r})},a)}),e.jsx("td",{className:"text-right tabular-nums",children:e.jsxs("span",{className:n.totalProviders>0&&n.citedCount===n.totalProviders?"text-positive":n.citedCount>0?"text-positive-400/70":"text-muted",children:[n.citedCount,"/",n.totalProviders]})}),e.jsx("td",{className:"text-right tabular-nums",children:e.jsxs("span",{className:n.totalProviders>0&&n.mentionedCount===n.totalProviders?"text-info-300":n.mentionedCount>0?"text-info-400/70":"text-muted",children:[n.mentionedCount,"/",n.totalProviders]})})]},n.queryId))})]})})]})}function lx(){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(Nn,{active:!0,tone:"cited"}),e.jsx("span",{children:"cited (in sources)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Nn,{active:!0,tone:"mentioned"}),e.jsx("span",{children:"mentioned (in answer)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Nn,{active:!1,tone:"cited"}),e.jsx(Nn,{active:!1,tone:"mentioned"}),e.jsx("span",{children:"neither"})]})]})}function cx({provider:t}){const s=dx(t);return e.jsxs("span",{className:"inline-flex items-center justify-center gap-1",title:s,children:[e.jsx(Nn,{active:t.cited,tone:"cited"}),e.jsx(Nn,{active:t.mentioned,tone:"mentioned"})]})}function dx(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 Nn({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 ux({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(Me,{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(Cn,{provider:s.provider})}),e.jsx("td",{className:"text-neutral",children:s.citingCompetitors.join(", ")})]},`${s.queryId}::${s.provider}`))})]})})]})}const Wn="__cited__",Yn="__mentioned__",rs="__mentionShare__";function Zo(t){const s=t,{dataStartDate:n,dataEndDate:a}=s;return typeof n!="string"||typeof a!="string"?null:{start:$s(n),end:$s(a),sweepCount:s.sweepCount??1}}function Ca(t){const s=Zo(t);if(!s)return"Sweep date unavailable";const n=Bs(s.start),a=Bs(s.end);return n===a?n:`${n} – ${a} · ${s.sweepCount} sweeps combined`}function mx(t){const s=Zo(t);return s?qo(s.start):""}function An(t){return t.trim().toLowerCase()}function vr(t){return Math.round(t*1e3)/10}function jr(t){return t.byProvider??{}}function hx(t,s,n){const a=t.buckets.length>0,r=t.buckets.length===1;if(n==="overall"){const u=s==="cited"?Wn:Yn,h=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(x=>({date:x.startDate,[u]:vr(x[h])})),series:[u],hasData:a,singleBucket:r}}const o=s==="mentioned"?"mentionRate":"citationRate",i=[...new Set(t.buckets.flatMap(u=>Object.keys(jr(u))))].sort();return{rows:t.buckets.map(u=>{const h={date:u.startDate},m=jr(u);for(const x of i){const g=m[x];h[x]=g?vr(g[o]):null}return h}),series:i,hasData:a,singleBucket:r}}function el(t){const s=t;return Object.hasOwn(s,"modelEvidenceByProvider")?s.modelEvidenceByProvider??{}:null}function xx(t){const s=t;return Object.hasOwn(s,"modelAttribution")?s.modelAttribution??{}:null}function px(t){return t.servedModelAttribution??{}}function gx(t){return t.modelServiceMismatch??{}}function fx(t){return t.modelPointerChanges??{}}function yx(t){return t.length>0?t.join(", "):null}function Pi(t,s){const n=An(s);return Object.entries(t).find(([a])=>An(a)===n)?.[1]}function Cs(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 bx(t,s){for(let n=t.length-1;n>=0;n-=1){const a=t[n];if(!Pi(jr(a),s))continue;const r=el(a);return r?Pi(r,s)??null:null}return null}function vx(t){const s=new Map;for(const[n,a]of Object.entries(t))for(const r of a.events){const o=s.get(r.bucketStartDate)??[];o.push({provider:n,event:r}),s.set(r.bucketStartDate,o)}return[...s.entries()].sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>({bucketStartDate:n,events:[...a].sort((r,o)=>r.provider.localeCompare(o.provider)||r.event.observedAt.localeCompare(o.event.observedAt))}))}function jx(t){const s={},n=[];for(const[a,r]of Object.entries(t)){const o=r.events.filter(i=>!i.fromPreWindowAnchor);for(const i of r.events)i.fromPreWindowAnchor&&n.push({provider:a,event:i});o.length>0&&(s[a]={...r,events:o})}return{buckets:vx(s),beforeWindow:n.sort((a,r)=>a.event.observedAt.localeCompare(r.event.observedAt)||a.provider.localeCompare(r.provider))}}function Nx(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 wx(t){const s=[];for(const[n,a]of Object.entries(t)){const r=a.eventTotal??a.events.length;r>a.events.length&&s.push({provider:n,shown:a.events.length,total:r})}return s.sort((n,a)=>n.provider.localeCompare(a.provider))}function Sx(t){const s=t.buckets.map(a=>{const r=a.mentionShare;return{date:a.startDate,[rs]:r?.rate==null?null:vr(r.rate)}}),n=s.map(a=>a[rs]).filter(a=>typeof a=="number"&&Number.isFinite(a));return{rows:s,series:[rs],hasData:n.length>0,singleBucket:n.length===1}}function Cx(t,s,n){return s==="mentionShare"?Sx(t):hx(t,s,n)}function Ri(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 Ii(t){const[,s,n]=t.slice(0,10).split("-");return!s||!n?t:`${s}/${n}`}function $i(t){return t>0?`+${t}`:`${t}`}function kx(t){if(t.length===0)return null;if(t.length<=2)return`Query set changed: ${t.map(n=>`${$i(n.delta)} on ${Ii(n.date)}`).join(", ")}`;const s=[...t].sort((n,a)=>a.date.localeCompare(n.date))[0];return`Query set changed ${t.length} times (latest ${$i(s.delta)} on ${Ii(s.date)})`}const Ax=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],cn={"non-brand":"Non-brand queries",branded:"Branded queries",unknown:"Unclassified queries"},Gs="min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",Nr=new Intl.NumberFormat("en",{style:"percent",maximumFractionDigits:1});function tl(t){return t.kind==="project"?"Whole site":t.kind==="group"?`${t.label} · Group`:t.kind==="market"?`${t.label} · Market`:t.label}function ms({value:t,unit:s}){return t.rate===null?e.jsx("span",{className:"text-sm text-secondary",children:t.reason==="not-applicable"?"Not applicable":"Not measured"}):e.jsxs("span",{className:"inline-flex flex-col gap-1",children:[e.jsx("strong",{className:"tabular-nums text-heading",children:Nr.format(t.rate)}),e.jsxs("span",{className:"text-sm tabular-nums text-secondary",children:[t.numerator," of ",t.denominator,s?` ${s}`:""]})]})}function Px(t){const s=new Map;for(const n of t){const a=s.get(n.queryKey);a?a.rows.push(n):s.set(n.queryKey,{queryKey:n.queryKey,query:n.query,rows:[n]})}return[...s.values()]}function Rx({population:t}){const s=t.trend.flatMap(n=>{const a={createdAt:n.createdAt,mentioned:n.mentionCoverage.rate,cited:n.citationCoverage.rate};return n.continuity.state==="comparable"||n.continuity.state==="first"?[a]:[{createdAt:n.createdAt,mentioned:null,cited:null},a]});return s.length===0?e.jsx("p",{className:"py-6 text-sm text-secondary",children:"No measured trend for this selection."}):e.jsxs(e.Fragment,{children:[e.jsxs("ul",{"aria-label":"Trend legend",className:"flex gap-5 py-3 text-sm text-secondary",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{"aria-hidden":"true",className:"h-0.5 w-5",style:{backgroundColor:nt[1]}}),"Mentioned"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{"aria-hidden":"true",className:"h-0.5 w-5",style:{backgroundColor:Is.positive}}),"Cited"]})]}),e.jsx("div",{className:"visibility-trend-chart",role:"img","aria-label":`${cn[t.queryClass]} mention and citation trend`,children:e.jsx(Ws,{width:"100%",height:"100%",children:e.jsxs(Ys,{data:s,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Vn,{stroke:Bn,vertical:!1}),e.jsx(Js,{dataKey:"createdAt",tick:Rt,tickLine:!1,axisLine:{stroke:is},tickFormatter:n=>new Date(String(n)).toLocaleDateString(void 0,{month:"short",day:"numeric"}),minTickGap:24}),e.jsx(Xs,{domain:[0,1],tick:Rt,tickLine:!1,axisLine:!1,width:48,tickFormatter:n=>Nr.format(Number(n))}),e.jsx(Zs,{formatter:n=>typeof n=="number"?Nr.format(n):"Not measured",labelFormatter:n=>new Date(String(n)).toLocaleDateString()}),e.jsx(As,{type:"linear",dataKey:"mentioned",name:"Mentioned",stroke:nt[1],strokeWidth:2,connectNulls:!1,isAnimationActive:!1,dot:{r:3}}),e.jsx(As,{type:"linear",dataKey:"cited",name:"Cited",stroke:Is.positive,strokeWidth:2,connectNulls:!1,isAnimationActive:!1,dot:{r:3}})]})})}),e.jsxs("details",{className:"py-3 text-sm text-secondary",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3",children:"Trend data and comparability"}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"}),e.jsx("th",{children:"Comparison"})]})}),e.jsx("tbody",{children:t.trend.map(n=>e.jsxs("tr",{children:[e.jsx("td",{children:new Date(n.createdAt).toLocaleDateString()}),e.jsx("td",{children:e.jsx(ms,{value:n.mentionCoverage})}),e.jsx("td",{children:e.jsx(ms,{value:n.citationCoverage})}),e.jsx("td",{children:n.continuity.state.replaceAll("-"," ")})]},n.runId))})]})})]})]})}function Ix({report:t,onSelectionChange:s}){const[n,a]=l.useState(""),r=l.useRef(null),o=l.useRef(null),i=l.useId(),{selection:c,scopeOptions:u,filterOptions:h}=t,m=tl(c.scope),x=u.filter(d=>`${d.kind==="project"?"Whole site":d.label} ${d.kind}`.toLocaleLowerCase().includes(n.trim().toLocaleLowerCase()));l.useEffect(()=>{const d=f=>{r.current?.open&&f.target instanceof Node&&!r.current.contains(f.target)&&(r.current.open=!1)};return document.addEventListener("pointerdown",d),()=>document.removeEventListener("pointerdown",d)},[]);const g=(d,f,y,j)=>e.jsxs("label",{className:"min-w-0",children:[e.jsx("span",{className:"mb-1 block text-sm font-medium text-heading",children:d}),e.jsx("select",{"aria-label":d,className:Gs,value:y,onChange:N=>s({[f]:N.target.value||void 0,measurementQueryKey:void 0}),children:j.map(N=>e.jsx("option",{value:N.value,children:N.label},N.value))})]});return e.jsx("div",{className:"visibility-filter-container",children:e.jsxs("div",{className:"visibility-report-filters","data-has-scope":u.length>1,role:"group","aria-label":"Visibility filters",children:[u.length>1?e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{id:`${i}-label`,className:"mb-1 block text-sm font-medium text-heading",children:"Measurement scope"}),e.jsxs("details",{ref:r,className:"relative",onToggle:d=>{d.currentTarget.open&&(a(""),o.current?.focus())},onKeyDown:d=>{d.key==="Escape"&&(d.preventDefault(),d.currentTarget.open=!1,d.currentTarget.querySelector("summary")?.focus())},children:[e.jsxs("summary",{id:`${i}-value`,"aria-labelledby":`${i}-label ${i}-value`,className:`${Gs} visibility-scope-trigger`,children:[m,e.jsx(Hs,{size:16,"aria-hidden":"true",className:"shrink-0 text-secondary"})]}),e.jsxs("div",{className:"visibility-scope-menu",children:[e.jsx("input",{ref:o,type:"search","aria-label":"Search scopes",className:Gs,placeholder:"Search groups, markets, properties",value:n,onChange:d=>a(d.target.value)}),e.jsxs("div",{className:"mt-2 max-h-72 overflow-y-auto",children:[x.map(d=>e.jsxs("button",{className:"flex min-h-11 w-full items-center justify-between gap-3 rounded px-2 text-left text-sm text-primary hover:bg-surface-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400","aria-current":c.scope.kind===d.kind&&c.scope.id===d.id?"true":void 0,onClick:()=>{r.current&&(r.current.open=!1,r.current.querySelector("summary")?.focus()),s({measurementScope:d.kind,measurementScopeKey:d.kind==="project"?void 0:d.id})},children:[e.jsx("span",{className:"min-w-0 break-words",children:d.kind==="project"?"Whole site":d.label}),e.jsx("span",{className:"shrink-0 text-right text-xs text-secondary",children:d.kind==="group"?e.jsxs(e.Fragment,{children:["Group",e.jsxs("span",{className:"block",children:[d.targetCount," properties"]})]}):d.kind==="market"?e.jsxs(e.Fragment,{children:["Market",e.jsx("span",{className:"block",children:"query context"})]}):d.kind==="property"?"Property":`${d.targetCount} properties`})]},`${d.kind}:${d.id}`)),x.length===0?e.jsx("p",{className:"py-3 text-sm text-secondary",children:"No matching scopes."}):null]})]})]})]}):null,g("Query type","queryClass",c.queryClass,[{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"},{value:"all",label:"All classes, separate"},{value:"unknown",label:"Unclassified"}]),g("Answer engine","measurementProvider",c.provider??"",[{value:"",label:"All engines"},...h.providers.map(d=>({value:d,label:d}))]),g("Search location","measurementLocation",c.location.kind==="exact"?c.location.value:c.location.kind==="none"?"none":"",[{value:"",label:"All locations"},...h.locations.filter(d=>d.kind!=="all").map(d=>({value:d.kind==="exact"?d.value:"none",label:d.kind==="exact"?d.value:"No location"}))])]})})}function $x({report:t,isRefreshing:s=!1,onSelectionChange:n,onManageQueries:a,onPage:r,onSearch:o,search:i="",queryKey:c,answerSelection:u,evidenceReport:h,isEvidenceLoading:m=!1,evidenceError:x,onRetryEvidence:g,onEvidencePage:d}){const f=l.useRef(null),y=l.useRef(void 0),j=h??t,N=j.populations.filter(w=>[...w.queries.items,...w.evidence.items].some(X=>X.queryKey===c)),P=u?[u.queryClass]:(N.length?N:m?[]:t.populations.slice(0,1)).map(w=>w.queryClass),M=c?JSON.stringify([u??c,P]):void 0,k=l.useId();l.useEffect(()=>{if(!M){s||(y.current=void 0);return}if(y.current===M)return;const w=f.current?.querySelectorAll('[aria-label="Measured answers"]');if(w?.length){for(const X of w){const C=X.closest("details[data-query-results]");C&&(C.open=!0)}w[0].focus({preventScroll:!0}),w[0].scrollIntoView?.({block:"start"}),y.current=M}},[M,s]);const{selection:p,filterOptions:v}=t,S=p.measurement,$=tl(p.scope),q=new Map(t.scopeOptions.filter(w=>w.kind==="property").map(w=>[w.id,w.label])),L=w=>{const X=j.populations.find(C=>C.queryClass===w.queryClass)?.evidence;return{items:X?.items.filter(C=>C.queryKey===c&&(!u||C.provider===u.provider&&C.model===u.model&&C.location===u.location&&(u.runId===null||C.runId===u.runId)))??[],nextCursor:X?.nextCursor}},Q=(w,X,C,F,_)=>e.jsxs("div",{className:"min-w-40 flex-1",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-1",children:[e.jsx("label",{htmlFor:`${k}-${X}`,className:"text-sm font-medium text-heading",children:w}),e.jsx(Me,{text:_})]}),e.jsx("select",{id:`${k}-${X}`,className:Gs,value:C,onChange:D=>n({[X]:D.target.value||void 0,measurementQueryKey:void 0}),children:F.map(D=>e.jsx("option",{value:D.value,children:D.label},D.value))})]});return e.jsxs("section",{ref:f,className:"visibility-report","aria-label":"AI visibility results",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 border-b border-default pb-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(ce,{tone:S.state==="measured"?"positive":"neutral",children:S.state==="measured"?"Complete":S.state==="partial"?"Partial":"Not measured"}),S.completedAt?e.jsx("span",{className:"text-sm text-secondary",children:new Date(S.completedAt).toLocaleString()}):null,S.awaitingSweep?e.jsxs("span",{role:"status",className:"inline-flex items-center gap-1 text-sm text-secondary",children:[e.jsxs("span",{children:[S.pendingAssignmentCount," query assignments pending across project"]}),e.jsx(Me,{text:`Measured under revision ${S.measuredRevision??"unavailable"}. Project has ${S.pendingAssignmentCount} assignments awaiting sweep. Existing results stay visible until those assignments are measured.`})]}):null]}),a?e.jsx(A,{variant:"outline",onClick:a,children:"Manage queries"}):null]}),p.provenance.kind==="legacy-simple"?e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 border-b border-default py-3 text-sm text-secondary",children:[e.jsx("p",{children:"Legacy results have no frozen query classification."}),p.queryClass!=="unknown"&&p.queryClass!=="all"?e.jsx(A,{variant:"outline",onClick:()=>n({queryClass:"unknown",measurementQueryKey:void 0}),children:"View unclassified results"}):null]}):null,e.jsx(Ix,{report:t,onSelectionChange:n}),e.jsxs("details",{className:"border-b border-default text-sm text-secondary",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3",children:"More filters"}),e.jsxs("div",{className:"flex flex-wrap gap-4 pb-3",children:[e.jsxs("label",{className:"min-w-40 flex-1",children:[e.jsx("span",{className:"mb-1 block text-sm font-medium text-heading",children:"Start date (UTC)"}),e.jsx("input",{type:"date",className:Gs,value:p.time.from?.slice(0,10)??"",onChange:w=>n({measurementFrom:w.target.value?`${w.target.value}T00:00:00.000Z`:void 0})})]}),e.jsxs("label",{className:"min-w-40 flex-1",children:[e.jsx("span",{className:"mb-1 block text-sm font-medium text-heading",children:"End date (UTC)"}),e.jsx("input",{type:"date",className:Gs,value:p.time.to?.slice(0,10)??"",onChange:w=>n({measurementTo:w.target.value?`${w.target.value}T23:59:59.999Z`:void 0})})]}),Q("AI model","measurementModel",p.model??"",[{value:"",label:"All models"},...Array.from(new Set(v.models.filter(w=>!p.provider||w.provider===p.provider).map(w=>w.model))).map(w=>({value:w,label:w}))],"Filter by the AI model recorded with each answer. This does not change the model used by future sweeps."),Q("Results from","measurementRunId",p.run.explicit?p.run.id??"":"",[{value:"",label:"Latest saved sweep"},...[...t.populations[0].trend].reverse().map(w=>({value:w.runId,label:new Date(w.createdAt).toLocaleString()}))],"Choose a saved AI sweep to view its results. No new sweep starts.")]})]}),t.populations.map(w=>{const X=Px(w.queries.items),C=p.mode==="advanced"?7:6;return e.jsxs("section",{"aria-label":cn[w.queryClass],className:"py-4",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("h2",{children:cn[w.queryClass]}),e.jsx(Me,{text:w.queryClass==="non-brand"?"Queries that do not name the measured identity. Geography alone is not a brand.":w.queryClass==="branded"?"Queries that name the measured identity.":"The measured definition could not establish a query class. These answers are not included in branded or non-brand rates."})]}),e.jsxs("div",{className:"flex flex-wrap gap-x-8 gap-y-4 border-y border-default py-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center gap-1 text-sm text-secondary",children:[e.jsx("span",{children:p.mode==="advanced"&&p.scope.kind!=="property"?"Answers mentioning a property":"Mentioned answers"}),p.mode==="advanced"?e.jsx(Me,{text:"An answer counts when it mentions any assigned property. This does not mean every property was mentioned."}):null]}),e.jsx(ms,{value:w.summary.mentionCoverage,unit:"answers"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center gap-1 text-sm text-secondary",children:[e.jsx("span",{children:p.mode==="advanced"&&p.scope.kind!=="property"?"Answers citing a property":"Cited answers"}),p.mode==="advanced"?e.jsx(Me,{text:"An answer counts when it cites a matching URL for any assigned property. This does not mean every property was cited."}):null]}),e.jsx(ms,{value:w.summary.citationCoverage,unit:"answers"})]}),p.mode==="advanced"&&p.scope.kind!=="property"?e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-sm text-secondary",children:"Properties mentioned"}),e.jsx(ms,{value:w.summary.propertyReach,unit:"properties"})]}):null,e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-sm text-secondary",children:"Queries measured"}),e.jsx("strong",{className:"tabular-nums text-heading",children:w.summary.queryCount})]})]}),e.jsx(Rx,{population:w}),p.mode==="advanced"?e.jsxs("details",{className:"border-t border-default text-sm text-secondary","aria-label":`${cn[w.queryClass]} property outcomes`,children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3",children:"Property outcomes"}),e.jsx("div",{className:"flex flex-wrap gap-x-8 gap-y-3 pb-4",children:[["bothSignals","mentioned and cited"],["mentionedOnly","mentioned only"],["citedOnly","cited only"],["neither","neither signal"],["notMeasured","not measured"]].map(([F,_])=>e.jsxs("div",{children:[e.jsx("strong",{className:"block tabular-nums text-heading",children:w.summary.outcomes[F]}),e.jsx("span",{className:"text-sm text-secondary",children:_}),F==="notMeasured"?e.jsx(Me,{text:"No eligible completed measurement for this selection. This is not the same as a measured answer with neither signal."}):null]},F))})]}):null,p.mode==="advanced"&&p.scope.kind!=="property"&&(w.breakdown.groups.length>0||w.breakdown.properties.length>0)?e.jsx(Tx,{population:w,scope:p.scope.kind,onSelectionChange:n},`${p.scope.kind}:${p.scope.id}`):null,e.jsxs("details",{className:"border-t border-default","data-query-results":w.queryClass,"aria-label":`${cn[w.queryClass]} query results`,children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-5 text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",children:[e.jsx("span",{className:"font-semibold",children:"Query results"}),e.jsxs("span",{className:"ml-3 text-sm font-normal text-secondary",children:[w.queries.total," ",w.queries.total===1?"result":"results"," · ",$]})]}),e.jsxs("div",{className:"pb-5",children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center justify-between gap-3",children:[o?e.jsx("input",{type:"search","aria-label":`Search ${cn[w.queryClass]}`,placeholder:"Search queries",className:`${Gs} max-w-sm`,value:i,onChange:F=>o(F.target.value)}):null,e.jsx(Me,{text:p.mode==="advanced"?"Each tracked query is grouped once on this page. Its engine rows retain the recorded model, location, property scope, and answer counts. Mentioned and Cited count answers matching any assigned property, not the percentage of properties found.":"Each tracked query is grouped once on this page. Its engine rows retain the recorded model, location, and answer counts. Mentioned counts answers naming your brand. Cited counts answers linking to your site."})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table measurement-responsive-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),p.mode==="advanced"?e.jsx("th",{children:"Properties"}):null,e.jsx("th",{children:"Answer engine"}),e.jsx("th",{children:"Search location"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"}),e.jsx("th",{className:"measurement-table-actions",children:e.jsx("span",{className:"sr-only",children:"Evidence"})})]})}),X.map(F=>e.jsxs("tbody",{"data-query-key":F.queryKey,children:[e.jsx("tr",{className:"bg-surface-subtle",children:e.jsx("th",{scope:"rowgroup",colSpan:C,className:"measurement-query-cell text-sm font-medium normal-case tracking-normal text-heading",children:F.query})}),F.rows.map(_=>e.jsxs("tr",{children:[e.jsx("td",{"aria-label":`Query: ${F.query}`,className:"measurement-query-cell text-secondary",children:e.jsx("span",{"aria-hidden":"true",children:"↳"})}),p.mode==="advanced"?e.jsx("td",{className:"measurement-target-cell",children:_.targetKeys.length===1?q.get(_.targetKeys[0])??_.targetKeys[0]:_.targetKeys.length>1?e.jsxs("details",{children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-2 text-secondary",children:[_.targetKeys.length," properties"]}),e.jsx("ul",{className:"max-h-48 space-y-2 overflow-y-auto py-2 text-sm text-secondary",children:_.targetKeys.map(D=>e.jsx("li",{children:q.get(D)??D},D))})]}):"No properties"}):null,e.jsxs("td",{children:[_.provider,_.model?e.jsx("span",{className:"block text-sm text-secondary",children:_.model}):null]}),e.jsx("td",{children:_.location??"No location"}),e.jsx("td",{children:e.jsx(ms,{value:_.mentionCoverage})}),e.jsx("td",{children:e.jsx(ms,{value:_.citationCoverage})}),e.jsx("td",{className:"measurement-table-actions",children:e.jsx(A,{variant:"ghost","aria-label":`View answers for ${_.query} · ${_.provider}`,onClick:()=>n({measurementQueryKey:_.queryKey,measurementAnswer:JSON.stringify({queryKey:_.queryKey,queryClass:w.queryClass,provider:_.provider,model:_.model,location:_.location,runId:p.run.id,revision:p.revision})}),children:"View answers"})})]},JSON.stringify([_.provider,_.model,_.location])))]},F.queryKey))]})}),w.queries.items.length===0?e.jsx("p",{className:"py-4 text-sm text-secondary",children:"No measured queries match this selection."}):e.jsxs("p",{className:"mt-3 text-sm text-secondary",children:[X.length," ",X.length===1?"query":"queries"," · ",w.queries.items.length," ",w.queries.items.length===1?"engine result":"engine results"," shown of ",w.queries.total," results"]}),w.queries.nextCursor&&r?e.jsx(A,{variant:"outline",onClick:()=>r(w.queries.nextCursor),children:"Next queries"}):null,c&&P.includes(w.queryClass)?e.jsxs("section",{tabIndex:-1,className:"scroll-mt-6 border-t border-default py-5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400","aria-label":"Measured answers","aria-busy":m,children:[e.jsxs("div",{className:"section-head",children:[e.jsx("h3",{children:"Answers"}),e.jsx(A,{variant:"ghost",onClick:F=>{y.current=void 0,F.currentTarget.closest("details[data-query-results]")?.querySelector("summary")?.focus(),n({measurementQueryKey:void 0,measurementAnswer:void 0})},children:"Close answers"})]}),m?e.jsx("p",{role:"status",className:"py-4 text-sm text-secondary",children:"Loading saved answers…"}):x?e.jsxs("div",{role:"alert",className:"py-4 text-sm text-secondary",children:[e.jsxs("p",{children:["Saved answers unavailable: ",x]}),g?e.jsx(A,{variant:"outline",onClick:g,children:"Retry answers"}):null]}):e.jsxs(e.Fragment,{children:[L(w).items.map(F=>e.jsxs("article",{className:"border-b border-default py-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("strong",{className:"text-sm text-heading",children:F.provider}),F.model?e.jsx("span",{className:"text-sm text-secondary",children:F.model}):null,e.jsx("span",{className:"text-sm text-secondary",children:F.location??"No location"}),e.jsx("span",{className:"text-sm text-secondary",children:new Date(F.createdAt).toLocaleString()}),e.jsx(ce,{tone:"neutral",children:F.mentioned===null?"Mention not checked":F.mentioned?"Mentioned":"Not mentioned"}),e.jsx(ce,{tone:"neutral",children:F.cited===null?"Citation not checked":F.cited?"Cited":"Not cited"})]}),e.jsx("h4",{className:"mt-3 text-sm font-medium text-heading",children:F.query}),e.jsx("p",{className:"mt-3 max-w-prose whitespace-pre-wrap text-sm leading-6 text-primary",children:F.answerText??"Answer text unavailable."}),e.jsx("ul",{className:"mt-3 space-y-2",children:F.sources.map(_=>{const D=Ds(_);return e.jsx("li",{className:"break-all text-sm",children:D?e.jsx("a",{href:D,target:"_blank",rel:"noreferrer",className:"text-link hover:underline",children:_}):e.jsx("span",{className:"text-secondary",children:_})},_)})})]},F.answerId)),L(w).items.length===0?e.jsx("p",{className:"py-4 text-sm text-secondary",children:L(w).nextCursor?"No matching answers on this page. Continue to the next answers.":"No matching saved answers on this page."}):null,L(w).nextCursor&&d?e.jsx(A,{variant:"outline",onClick:()=>d(L(w).nextCursor),children:"Next answers"}):null]})]}):null]})]}),e.jsxs("details",{className:"border-t border-default","aria-label":`${cn[w.queryClass]} competitors`,children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-5 text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",children:[e.jsx("span",{className:"font-semibold",children:"Competitors"}),e.jsx("span",{className:"ml-3 text-sm font-normal text-secondary",children:w.competitorAvailability.state==="unavailable"?"Not available":`${w.competitors.length} measured`})]}),e.jsxs("div",{className:"pb-5",children:[w.competitorAvailability.state==="unavailable"?e.jsx("p",{className:"text-sm text-secondary",children:"Competitor rates unavailable for this historical definition."}):w.competitors.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No measured competitors in this selection."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Competitor"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"})]})}),e.jsx("tbody",{children:w.competitors.map(F=>e.jsxs("tr",{children:[e.jsx("td",{children:F.domain}),e.jsx("td",{children:e.jsx(ms,{value:F.mentionCoverage})}),e.jsx("td",{children:e.jsx(ms,{value:F.citationCoverage})})]},F.domain))})]})}),w.observedCompetitors.length>0?e.jsxs("details",{className:"mt-4 text-sm",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3 text-heading",children:"Other names in answers"}),e.jsx("ul",{className:"divide-y divide-default",children:w.observedCompetitors.map(F=>e.jsxs("li",{className:"flex items-center justify-between gap-4 py-3",children:[e.jsx("span",{children:F.name}),e.jsxs("span",{className:"tabular-nums text-secondary",children:[F.answerCount," ",F.answerCount===1?"answer":"answers"]})]},F.name))}),e.jsx("p",{className:"py-2 text-secondary",children:"Observed names, not additions to your tracked competitors."})]}):null]})]})]},w.queryClass)})]})}function Tx({population:t,scope:s,onSelectionChange:n}){const[a,r]=l.useState(()=>s==="project"&&t.breakdown.groups.length>0?"groups":"properties"),o=xn({rows:t.breakdown[a],getSearchText:i=>i.label});return e.jsxs("section",{className:"border-t border-default py-5","aria-label":"Scope breakdown",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[e.jsx("div",{className:"flex gap-2",children:["groups","properties"].map(i=>e.jsx(A,{variant:a===i?"secondary":"ghost",onClick:()=>{r(i),o.setPage(1)},children:i==="groups"?"Groups":"Properties"},i))}),e.jsx("input",{type:"search","aria-label":"Search breakdown",placeholder:"Search",value:o.query,onChange:i=>o.setQuery(i.target.value),className:`${Gs} max-w-sm`})]}),e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:a==="groups"?"Group":"Property"}),e.jsx("th",{children:"Queries"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"})]})}),e.jsx("tbody",{children:o.rows.map(i=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("button",{className:"min-h-11 text-left text-link hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>n({measurementScope:a==="groups"?"group":"property",measurementScopeKey:i.id}),children:i.label})}),e.jsx("td",{children:i.queryCount}),e.jsx("td",{children:e.jsx(ms,{value:i.mentionCoverage})}),e.jsx("td",{children:e.jsx(ms,{value:i.citationCoverage})})]},i.id))})]})}),o.rows.length===0?e.jsxs("p",{className:"py-3 text-sm text-secondary",children:["No ",a," match this search."]}):null,e.jsx(Rs,{page:o.page,pageSize:o.pageSize,visibleRows:o.rows.length,totalRows:o.totalRows,itemLabel:a,onPageChange:o.setPage})]})}function Mx({projectName:t,selection:s,onSelectionChange:n,onManageQueries:a,fallback:r,showUnmeasuredFallback:o=!1}){const[i,c]=l.useState(),[u,h]=l.useState(""),[m,x]=l.useState(),g={scope:s.measurementScope,scopeKey:s.measurementScopeKey,queryClass:s.queryClass,provider:s.provider,model:s.model,location:s.location,from:s.from,to:s.to,revision:s.revision,runId:s.measurementRunId},d=we({...ei({client:H,path:{name:t},query:{...g,limit:25,cursor:i,search:u||void 0}}),retry:!1,placeholderData:Rr}),f={...g,queryKey:s.queryKey,queryClass:s.answer?.queryClass??s.queryClass,provider:s.answer?.provider??s.provider,model:s.answer?s.answer.model??void 0:s.model,location:s.answer?s.answer.location??"none":s.location,runId:s.answer?.runId??d.data?.selection.run.id??s.measurementRunId,revision:s.answer?.revision??d.data?.selection.revision??s.revision,limit:50},y=JSON.stringify(f),j=we({...ei({client:H,path:{name:t},query:{...f,cursor:m?.selection===y?m.cursor:void 0}}),enabled:!!s.queryKey&&!!d.data&&!d.isPlaceholderData,retry:!1});return d.data?.selection.availability.state==="unsupported"?e.jsx(e.Fragment,{children:r}):o&&d.data?.selection.mode==="simple"&&d.data.selection.measurement.state==="not-measured"?e.jsx(e.Fragment,{children:r}):d.error?e.jsxs("section",{className:"page-section-divider",role:"alert",children:[e.jsx("h2",{children:"AI visibility unavailable"}),e.jsx("p",{className:"my-3 text-sm text-secondary",children:_n(d.error)}),e.jsx(A,{variant:"outline",onClick:()=>{c(void 0),d.refetch()},children:"Retry"})]}):d.data?e.jsx("div",{"aria-busy":d.isFetching,children:e.jsx($x,{report:d.data,isRefreshing:d.isFetching,queryKey:s.queryKey,answerSelection:s.answer,evidenceReport:j.data,isEvidenceLoading:j.isFetching||!!s.queryKey&&j.isPending,evidenceError:j.error?_n(j.error):void 0,onRetryEvidence:()=>{j.refetch()},onEvidencePage:j.isFetching?void 0:N=>x({selection:y,cursor:N}),search:u,onSearch:N=>{h(N),c(void 0)},onPage:d.isFetching?void 0:c,onSelectionChange:N=>{(!("measurementQueryKey"in N)||Object.keys(N).some(P=>P!=="measurementQueryKey"&&P!=="measurementAnswer"))&&c(void 0),x(void 0),n(N)},onManageQueries:a})}):e.jsx("section",{className:"page-section-divider",role:"status","aria-label":"Loading AI visibility",children:e.jsx("div",{className:"h-64 animate-pulse rounded-md bg-surface"})})}const Lx=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],Ex=[{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:"On non-brand queries, the share of answer-text brand mentions for you and tracked competitors that were you. Pooled only when query classification is unavailable."}],Tr=nt[2],qx="var(--chart-tooltip-bg)",Dx={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",local:"Local"};function Ps(t){const s=An(t);return Dx[s]??t.charAt(0).toUpperCase()+t.slice(1)}function Ks(t){return Math.round(t*10)/10}function Ox(t){return t===Wn||t===Yn||t===rs}function sl(t){return t===Wn?"Cited":t===Yn?"Mentioned":t===rs?"Mention share":Ps(t)}function qn(t,s){return t===Wn?Is.positive:t===Yn?nt[1]:t===rs?Tr:dm(An(t),s)}function Fx(t,s){for(const n of t){const a=n[s];if(typeof a=="number"&&Number.isFinite(a))return a}return null}function Gx(t){return t.map(s=>s.trim().toLowerCase()).filter(Boolean).sort().join(`
|
|
1
|
+
import{j as e,r as l,u as we,L as vs,h as js,o as Pt,B as Rr,C as Il,k as $l,l as Tl,D as Ml}from"./vendor-tanstack-CYBjbqVr.js";import{T as ce,t as Ll,a as El,M as fo,I as Me,s as yo,B as A,b as ql,u as bo,C as Dl,P as Cn,h as Ol,c as Fl,d as dn,g as vo,e as jo,f as xe,i as H,j as te,k as Nt,l as qe,m as Gl,n as Kl,o as _l,p as No,q as Ul,r as Bl,S as un,v as Vl,w as zl,x as Ds,y as Bt,z as Ql,A as Xr,D as wo,G as Dt,E as Ir,F as Hl,H as Wl,J as Yl,K as Jl,L as Zr,N as Se,O as Xl,Q as Zl,R as Ea,U as ec,V as tc,W as sc,X as nc,Y as ac,Z as rc,_ as ic,$ as oc,a0 as lc,a1 as cc,a2 as dc,a3 as uc,a4 as mc,a5 as hc,a6 as xc,a7 as So,a8 as zs,a9 as pc,aa as Co,ab as ba,ac as gc,ad as De,ae as fc,af as yc,ag as bc,ah as va,ai as vc,aj as jc,ak as Nc,al as hn,am as wc,an as Sc,ao as Cc,ap as ko,aq as hr,ar as kc,as as Ao,at as Ac,au as _n,av as Qs,aw as Vt,ax as ei,ay as Pc,az as Rc,aA as Hn,aB as Ic,aC as $c,aD as Tc,aE as Mc,aF as Lc,aG as Gn,aH as mn,aI as Ec,aJ as Po,aK as qc,aL as Dc,aM as Oc,aN as ti,aO as Fc,aP as Gc,aQ as Kc,aR as _c,aS as Uc,aT as Bc,aU as Vc,aV as zc,aW as Qc,aX as Hc,aY as Wc,aZ as Yc,a_ as Jc,a$ as Xc,b0 as Zc,b1 as ed,b2 as td,b3 as sd,b4 as nd,b5 as ad,b6 as rd,b7 as id,b8 as od,b9 as ld,ba as cd,bb as dd,bc as ud,bd as md,be as ys,bf as hd,bg as lt,bh as xd,bi as pd,bj as gd,bk as fd,bl as yd,bm as bd,bn as vd,bo as jd,bp as Nd,bq as wd,br as Sd,bs as Cd,bt as kd,bu as Ad,bv as Pd,bw as Rd,bx as Id,by as $d,bz as Td,bA as Md,bB as Ld,bC as Ed,bD as qd,bE as Dd,bF as Od,bG as Fd,bH as Gd,bI as Kd,bJ as _d,bK as Ud,bL as Bd,bM as Vd,bN as zd,bO as Qd,bP as Hd,bQ as Wd,bR as Yd,bS as Jd,bT as Xd,bU as Ro,bV as qa,bW as Zd,bX as si,bY as eu,bZ as tu,b_ as su,b$ as nu,c0 as au,c1 as ru,c2 as iu,c3 as Io,c4 as ou,c5 as lu,c6 as cu,c7 as du,c8 as uu,c9 as mu,ca as hu,cb as xu,cc as ni,cd as pu,ce as gu,cf as fu,cg as yu,ch as bu,ci as vu,cj as ju,ck as Nu,cl as wu,cm as Su,cn as Cu,co as ku,cp as Au,cq as Pu,cr as Ru,cs as ja,ct as Iu,cu as Da,cv as $u,cw as Tu,cx as Mu,cy as Lu,cz as Eu,cA as qu,cB as Du,cC as Ou,cD as Fu,cE as Gu,cF as $o,cG as Ku,cH as _u,cI as Uu,cJ as Bu,cK as Vu,cL as zu,cM as Zn,cN as Qu,cO as Hu,cP as Wu,cQ as ai,cR as Yu}from"./index-DJWMbOc5.js";import{C as Hs,e as Ju,q as Na,U as Xu,r as Zu,L as em,s as tm,i as sm,P as Un,D as To,t as nm,u as am,E as rm,p as im,v as om,w as Mo}from"./vendor-lucide-BovNTc41.js";import{R as lm}from"./RunRow-C9u35nrm.js";import{u as xn,D as Us,a as Rs,b as Lo,M as xa,c as Ss,S as cm}from"./SiteHealthSection-DIeYA2HJ.js";import{C as Bn,f as pn,a as is,b as Rt,c as Ot,d as as,e as nt,g as os,h as Is,M as Eo,i as qo,o as $s,j as Bs,p as dm}from"./ChartPrimitives-DLEICrrL.js";import{u as um,a as mm,b as hm,t as xm,e as pm,c as mt}from"./extract-error-message-B5OYNTJO.js";import{R as Ws,C as Ys,a as Vn,X as Js,Y as Xs,T as Zs,b as xr,L as wa,A as Fs,d as As,e as gm}from"./vendor-recharts-FA0uySU7.js";import{A as fm}from"./AuditHistoryPanel-G2iVWlbn.js";import{a as ym,b as bm}from"./v2-overview-adapter-COMP5UGt.js";import"./vendor-radix-BpmvLvpp.js";import"./vendor-markdown-9tTeP8v7.js";import"./vendor-yaml-GWJz5H2G.js";function Vs(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 vm(t,s,n=800){const a=[];if(!/^\d{4}-\d{2}-\d{2}$/.test(t)||!/^\d{4}-\d{2}-\d{2}$/.test(s))return a;for(let r=t;r<=s&&(a.push(r),!(a.length>=n));r=jm(r,1));return a}function jm(t,s){if(!Number.isFinite(s))return t;const n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t);if(!n?.[1]||!n[2]||!n[3])return t;const a=new Date(Date.UTC(Number(n[1]),Number(n[2])-1,Number(n[3])+Math.trunc(s)));if(Number.isNaN(a.getTime()))return t;const r=a.getUTCFullYear(),o=String(a.getUTCMonth()+1).padStart(2,"0"),i=String(a.getUTCDate()).padStart(2,"0");return`${r}-${o}-${i}`}function Nm(t,s){if(!Number.isFinite(t)||!Number.isFinite(s)||s<=0)return null;const n=(t-s)/s;return Number.isFinite(n)?n:null}function wm(t,s){const n=Nm(t,s);return n===null?null:Math.round(n*100)}function Oa(t,s,n="vs prior 7 days"){return t.deltaPct===null?t.prior===0?"First baseline week":"":t.deltaPct>0?`Up ${t.deltaPct}% ${n} (${Vs(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${Vs(t.prior)} ${s})`:`Flat ${n} (${Vs(t.prior)} ${s})`}const Do=30;function ri(t){return Math.round(t*10)/10}function Sm(t){return t.prior>=Do&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% vs prior`:`${t.deltaAbs>0?"+":""}${ri(t.deltaAbs)} vs ${ri(t.prior)}`}function Cm(t,s,n){return t.prior>=Do&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% ${n}`:`${t.deltaAbs>0?"+":""}${Vs(Math.round(t.deltaAbs))} ${s} ${n}`}const km=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function Oo(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function Fo(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 Go(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(Oo).map(Fo).filter(Boolean)):new Set}function Ko(t,s){const n=Oo(t).map(Fo).filter(Boolean).filter(a=>!km.has(a)).filter(a=>!s.has(a));return[...new Set(n)].sort().join(" ")}function Am(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function Pm(t,s){const n=Go(t);if(s.length<=1||n.size===0)return[...s];const a=new Set,r=[];for(const o of s){if(o.category!=="content"){r.push(o);continue}const i=Ko(Am(o),n);!i||a.has(i)||(a.add(i),r.push(o))}return r}function Rm(t){const s=Go(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const a=new Set;return n.filter(r=>{const o=Ko(r.query,s);return!o||a.has(o)?!1:(a.add(o),!0)})}const Im=1e6;function $m(t,s="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:s}).format(t/Im)}const _o={queryClass:"all"},Tm=["all","non-brand","branded"];function Mm(t){return typeof t=="string"&&Tm.includes(t)}function Uo(t){const s=Mm(t.class)?t.class:_o.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 Lm(t,s){return s===null||t===null?!1:t!==s}function Em(t){return{scope:t.scope==="group"&&t.groupKey?`group:${t.groupKey}`:void 0,class:t.queryClass===_o.queryClass?void 0:t.queryClass}}function qm(t,s){if(!(typeof t!="string"||t.length>16384||!s))try{const n=JSON.parse(t);if(typeof n!="object"||n===null||Array.isArray(n))return;const a=n,r=i=>typeof i=="string"&&i.trim().length>0,o=i=>i===null||r(i);return a.queryKey!==s||!r(a.provider)||a.queryClass!=="branded"&&a.queryClass!=="non-brand"&&a.queryClass!=="unknown"||!o(a.model)||!o(a.location)||!o(a.runId)||a.revision!==null&&(typeof a.revision!="number"||!Number.isSafeInteger(a.revision)||a.revision<=0)?void 0:{queryKey:s,queryClass:a.queryClass,provider:a.provider,model:a.model,location:a.location,runId:a.runId,revision:a.revision}}catch{return}}function Dm(t){const s=h=>typeof t[h]=="string"&&t[h]!==""?t[h]:void 0,n=Uo({scope:s("scope"),class:s("class")}),a=s("measurementScope")??(n.scope==="group"?"group":"project"),r=s("measurementScopeKey")??(s("measurementScope")?void 0:n.groupKey),o=s("queryClass")??s("class"),i={measurementScope:r&&(a==="group"||a==="market"||a==="property")?a:"project",queryClass:o==="all"||o==="branded"||o==="unknown"?o:"non-brand"};i.measurementScope!=="project"&&(i.measurementScopeKey=r);for(const[h,m]of[["measurementProvider","provider"],["measurementModel","model"],["measurementLocation","location"],["measurementFrom","from"],["measurementTo","to"],["measurementRunId","measurementRunId"],["measurementQueryKey","queryKey"]]){const x=s(h);x!==void 0&&(i[m]=x)}const c=Number(t.measurementRevision);Number.isSafeInteger(c)&&c>0&&(i.revision=c);const u=qm(t.measurementAnswer,i.queryKey);return u&&(i.answer=u),i}function Om(t,s){const n={...t,...s};return["measurementScope","measurementScopeKey","queryClass","measurementProvider","measurementModel","measurementLocation","measurementFrom","measurementTo","measurementRevision","measurementRunId"].some(a=>a in s)?(n.measurementQueryKey=void 0,n.measurementAnswer=void 0):"measurementQueryKey"in s&&!("measurementAnswer"in s)&&(n.measurementAnswer=void 0),"measurementScope"in s&&(n.scope=void 0,n.measurementQueryKey=void 0,s.measurementScope==="project"&&(n.measurementScopeKey=void 0)),"queryClass"in s&&(n.class=void 0),n}function pr({state:t,label:s}){return e.jsx(ce,{tone:El(t),children:s??Ll(t)})}const tn=[{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],ii={"non-brand":"Non-brand",branded:"Branded",pooled:"All queries"},Fm={"non-brand":"On queries that do not contain your name: of the brand names written into the answer text, the share that were yours. Branded queries are scored separately because you are named on nearly all of them and a competitor cannot be.",branded:"On queries that contain your name: of the brand names written into the answer text, the share that were yours. This is recognition, not competitive placement, and it is never pooled with the non-brand figure.",pooled:"This project has no brand name or domain to match on, so branded and non-brand queries could not be separated. This figure pools both and is not a competitive read. Set a display name or aliases to split them."},Gm="Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other.";function Km(t,s){if(s.unavailable)return{headline:"No data",numeric:!1,detail:"could not load, refresh to retry",showRows:!1};if(s.noRun)return{headline:"No data",numeric:!1,detail:"no sweep has run yet",showRows:!1};if(t.snapshotsTotal===0)return s.otherClassHasData?{headline:"No non-brand queries",numeric:!1,detail:"every tracked query names your brand",showRows:!1}:{headline:"No queries",numeric:!1,detail:"none tracked",showRows:!1};if(t.snapshotsWithAnswerText===0)return{headline:"No answers",numeric:!1,detail:"no answer text in this run",showRows:!1};if(!s.hasCompetitors)return{headline:"Add competitors",numeric:!1,detail:`you were named in ${t.projectMentionSnapshots} of ${t.snapshotsWithAnswerText} answers`,showRows:!1};const n=t.projectMentionSnapshots+t.competitorMentionSnapshots;return n===0||t.score===null?{headline:"No mentions",numeric:!1,detail:`no brand named in ${t.snapshotsWithAnswerText} answers`,showRows:!1}:{headline:`${t.score}`,numeric:!0,detail:`${t.projectMentionSnapshots} of ${n} brand mentions`,showRows:!0}}function _m({breakdown:t,projectLabel:s,competitorDomains:n}){const a=t.projectMentionSnapshots+t.competitorMentionSnapshots;if(a===0)return null;const r=new Map(t.perCompetitor.map(i=>[i.domain,i.mentionSnapshots])),o=[{label:`${s} (you)`,mentions:t.projectMentionSnapshots,isYou:!0},...n.map(i=>({label:i,mentions:r.get(i)??0,isYou:!1}))].sort((i,c)=>c.mentions-i.mentions||(i.label<c.label?-1:1));return e.jsxs("table",{className:"mention-share-table",children:[e.jsx("caption",{className:"sr-only",children:"Brand mentions by domain, most mentioned first"}),e.jsx("thead",{children:e.jsxs("tr",{className:"mention-share-row mention-share-row-head",children:[e.jsx("th",{scope:"col",className:"mention-share-row-label",children:"Domain"}),e.jsx("th",{"aria-hidden":"true"}),e.jsxs("th",{scope:"col",className:"mention-share-count",children:["Mentions",e.jsx(Me,{text:Gm})]}),e.jsx("th",{scope:"col",className:"mention-share-share",children:"Share"})]})}),e.jsx("tbody",{className:"mention-share-rows",children:o.map(i=>{const c=i.mentions/a*100;return e.jsxs("tr",{className:"mention-share-row",children:[e.jsx("th",{scope:"row",className:`mention-share-row-label ${i.isYou?"text-heading font-medium":"text-secondary"}`,children:i.label}),e.jsx("td",{"aria-hidden":"true",children:e.jsx("div",{className:"mention-share-bar",children:e.jsx("div",{className:`mention-share-bar-fill ${i.isYou?"bg-positive-500/70":"bg-mono-500/60"}`,style:{width:`${c>0?Math.max(c,1.5):0}%`}})})}),e.jsx("td",{className:"mention-share-count",children:i.mentions}),e.jsxs("td",{className:"mention-share-share",children:[c.toFixed(1),"%"]})]},i.label)})})]})}function Um({summary:t,projectLabel:s,competitorDomains:n}){const[a,r]=l.useState("non-brand"),o=l.useId(),i=t.scope==="pooled",c=!i&&t.branded.snapshotsTotal>0,u=c?a:"non-brand",h=i?"pooled":u,m=u==="branded"?t.branded:t.breakdown,x=u==="branded"?t.breakdown:t.branded,g=Km(m,{hasCompetitors:n.length>0,unavailable:t.unavailable===!0,noRun:t.breakdown.snapshotsTotal===0&&t.branded.snapshotsTotal===0,otherClassHasData:x.snapshotsTotal>0}),d=h==="non-brand"?fo[t.tone]:"text-secondary";function f(y){const j=tn.findIndex(P=>P.value===u);let N=null;y.key==="ArrowRight"||y.key==="ArrowDown"?N=(j+1)%tn.length:y.key==="ArrowLeft"||y.key==="ArrowUp"?N=(j-1+tn.length)%tn.length:y.key==="Home"?N=0:y.key==="End"&&(N=tn.length-1),N!==null&&(y.preventDefault(),r(tn[N].value),y.currentTarget.querySelectorAll('[role="radio"]')[N]?.focus())}return e.jsxs("div",{className:"mention-share",children:[e.jsxs("div",{className:"mention-share-head",children:[e.jsxs("div",{className:"mention-share-label",children:[e.jsx("h3",{id:o,className:"mention-share-label-text",children:"Mention share"}),e.jsx(Me,{text:Fm[h]})]}),c?e.jsx("div",{role:"radiogroup","aria-labelledby":o,className:"segmented flex-wrap",onKeyDown:f,children:tn.map(y=>{const j=y.value===u;return e.jsx("button",{type:"button",role:"radio","aria-checked":j,tabIndex:j?0:-1,onClick:()=>r(y.value),className:`segmented-option min-h-11 ${j?"segmented-option-active":""}`,children:y.label},y.value)})}):e.jsx("span",{className:"mention-share-class",children:ii[h]})]}),g.numeric?e.jsxs("p",{className:`mention-share-value ${d}`,children:[g.headline,e.jsx("span",{className:"text-faint",children:"%"})]}):e.jsx("p",{className:"mention-share-value-text",children:g.headline}),e.jsxs("p",{className:"mention-share-caption",children:[e.jsx("span",{className:"mention-share-caption-scope",children:ii[h]}),` · ${g.detail}`]}),i&&e.jsx("p",{className:"mention-share-note",children:"Set a brand name to split branded from non-brand."}),g.showRows&&e.jsx(_m,{breakdown:m,projectLabel:s,competitorDomains:n})]})}const sn=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],oi=5;function Bm(t){switch(t){case"non-brand":return"Counts queries that do not name your brand.";case"branded":return"Counts queries that name your brand.";default:return"Counts every tracked query, so share of voice is not shown."}}function Vm(t){return t?t.evidence.answeredResults>0||t.evidence.sourceResults>0?"measured":"not-measured":"unavailable"}function Fa(t){return t==="unavailable"?"Unavailable":"Not measured"}function Bo(t){switch(t){case"own":return"Your domain";case"direct-competitor":return"Competitor";case"ota-aggregator":return"Aggregator";case"editorial-media":return"Editorial";case"other":return"Other";default:return"Unclassified"}}function zm({value:t,onChange:s}){function n(a){const r=sn.findIndex(c=>c.value===t);let o=null;if(a.key==="ArrowRight"||a.key==="ArrowDown"?o=(r+1)%sn.length:a.key==="ArrowLeft"||a.key==="ArrowUp"?o=(r-1+sn.length)%sn.length:a.key==="Home"?o=0:a.key==="End"&&(o=sn.length-1),o===null)return;a.preventDefault();const i=sn[o];s(i.value),a.currentTarget.querySelectorAll('[role="radio"]')[o].focus()}return e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"block text-sm font-medium text-heading",children:"History"}),e.jsx("div",{role:"radiogroup","aria-label":"Competitor history window",className:"segmented",onKeyDown:n,children:sn.map(a=>{const r=a.value===t;return e.jsx("button",{type:"button",role:"radio","aria-checked":r,tabIndex:r?0:-1,onClick:()=>s(a.value),className:`segmented-option min-h-11 ${r?"segmented-option-active":""}`,children:a.label},a.value)})})]})}function gr({row:t,isProject:s=!1,metricState:n="measured",shareContext:a,canManage:r,onPin:o,onUnpin:i}){const c=!s&&r&&!t.pinned&&!!o,u=!s&&r&&t.pinned&&!!i,h=n==="measured",m=h&&t.sampleUrls.length>0,[x,g]=l.useState(!1),[d,f]=l.useState(null);async function y(j,N){if(!(!N||x)){g(!0),f(null);try{await N(t.domain)===!1&&f(`Could not ${j} competitor. Try again.`)}catch{f(`Could not ${j} competitor. Try again.`)}finally{g(!1)}}}return e.jsxs("tr",{children:[e.jsxs("th",{scope:"row",className:"font-medium text-heading",children:[t.label,s?e.jsx("span",{className:"ml-1 text-secondary",children:"(you)"}):null]}),e.jsx("td",{className:"text-secondary",children:s?"Your brand":Bo(t.surfaceClass)}),e.jsx("td",{className:"tabular-nums text-strong",children:h?ql(t.shareOfVoice,a):Fa(n)}),e.jsx("td",{className:"tabular-nums text-secondary",children:h?t.mentionCount:Fa(n)}),e.jsx("td",{className:"tabular-nums text-secondary",children:h?t.citationCount:Fa(n)}),e.jsx("td",{className:"text-right",children:c||u||m?e.jsxs("div",{className:"flex min-w-max items-start justify-end gap-2",children:[m?e.jsxs("details",{className:"inline-disclosure text-left text-xs text-secondary",children:[e.jsx("summary",{children:"Source URLs"}),e.jsx("ul",{className:"mt-2 max-w-72 space-y-1 font-mono text-[11px] font-normal",children:t.sampleUrls.map(j=>e.jsx("li",{className:"break-all",children:j},j))})]}):null,u&&i?e.jsxs(A,{type:"button",size:"sm",variant:"outline",disabled:x,onClick:()=>{y("unpin",i)},children:["Unpin"," ",e.jsx("span",{className:"sr-only",children:t.domain})]}):null,c&&o?e.jsxs(A,{type:"button",size:"sm",variant:"outline",disabled:x,onClick:()=>{y("pin",o)},children:["Pin"," ",e.jsx("span",{className:"sr-only",children:t.domain})]}):null,d?e.jsx("span",{role:"alert",className:"sr-only",children:d}):null]}):e.jsx("span",{className:"text-faint",children:"—"})})]})}function fr({children:t}){return e.jsx("tr",{className:"competitor-landscape-group",children:e.jsx("th",{scope:"rowgroup",colSpan:6,children:t})})}function Qm({rows:t,shareContext:s,canManage:n,onPin:a}){const[r,o]=l.useState(!1),i=r?t:t.slice(0,oi);return e.jsxs("tbody",{children:[e.jsx(fr,{children:"Observed in this window"}),i.map(c=>e.jsx(gr,{row:{...c,pinned:!1},shareContext:s,canManage:n,onPin:a},c.domain)),t.length>oi?e.jsx("tr",{children:e.jsx("td",{colSpan:6,children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("span",{className:"text-sm text-secondary",children:["Showing ",i.length," of ",t.length," observed competitors."]}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11 text-sm","aria-expanded":r,"aria-label":r?"Show fewer observed competitors":`Show all ${t.length} observed competitors`,onClick:()=>o(c=>!c),children:r?"Show fewer":`Show all ${t.length}`})]})})}):null]})}function Hm({onAddCompetitor:t}){const s=l.useId(),[n,a]=l.useState(""),[r,o]=l.useState(!1),[i,c]=l.useState(null);async function u(){const h=n.trim();if(!(!h||r)){o(!0),c(null);try{if(await t(h)===!1){c("Could not add competitor. Try again.");return}a("")}catch{c("Could not add competitor. Try again.")}finally{o(!1)}}}return e.jsxs("details",{className:"inline-disclosure competitor-landscape-manage",children:[e.jsx("summary",{children:"Manage competitors"}),e.jsxs("form",{className:"mt-3 flex flex-wrap items-end gap-2",onSubmit:h=>{h.preventDefault(),u()},"aria-busy":r,children:[e.jsxs("label",{htmlFor:s,className:"min-w-56 flex-1 text-sm font-medium text-heading",children:["Competitor domain",e.jsx("input",{id:s,type:"text",value:n,onChange:h=>a(h.target.value),placeholder:"competitor.com",className:"mt-1 h-10 w-full rounded-md border border-default bg-surface px-3 text-sm text-primary placeholder-mono-600 focus:outline-none focus:ring-2 focus:ring-mono-400"})]}),e.jsx(A,{type:"submit",size:"sm",className:"min-h-10",disabled:r||!n.trim(),children:r?"Adding…":"Add competitor"}),i?e.jsx("p",{role:"alert",className:"w-full text-sm text-negative",children:i}):null]})]})}function Wm({window:t,landscape:s,pinnedFallback:n=[],canWrite:a,isEmbed:r,onWindowChange:o,onPin:i,onUnpin:c,onAddCompetitor:u,error:h,onRetry:m,isLoading:x=!1,scopeLabel:g}){const d=a&&!r,f=s?.pinned??n,y=s?.observed??[],j=s?.otherSources??[],N=s?.evidence,P=Vm(s),M=s?.marketState?.draft?.pendingCompetitorDomains.length??0;return e.jsxs("section",{"aria-labelledby":"competitor-landscape-title","aria-busy":x,className:"competitor-landscape",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Competitive"}),e.jsx("h2",{id:"competitor-landscape-title",children:"Competitor landscape"}),g?e.jsx("p",{className:"supporting-copy mt-1",children:g}):null,s?e.jsx("p",{className:"supporting-copy mt-1",children:Bm(s.filters?.queryClass)}):null,s?.reason?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:yo(s.reason)}):null]}),e.jsx(zm,{value:t,onChange:o})]}),h?e.jsxs("div",{role:"alert",className:"flex flex-wrap items-center gap-3 border-y border-negative-800/40 bg-negative-950/20 py-3 text-sm text-negative",children:[e.jsx("span",{children:h}),m?e.jsx(A,{type:"button",size:"sm",variant:"outline",onClick:m,children:"Retry competitor history"}):null]}):null,x&&!s&&f.length===0?e.jsx("div",{role:"status","aria-live":"polite",className:"h-48 animate-pulse rounded-md bg-surface-subtle",children:e.jsx("span",{className:"sr-only",children:"Loading competitor history"})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"competitor-table-wrap",children:e.jsxs("table",{className:"competitor-table","aria-label":"Competitor landscape",children:[e.jsx("caption",{className:"sr-only",children:"Pinned competitors followed by competitors observed in the selected history window."}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Competitor"}),e.jsx("th",{scope:"col",children:"Type"}),e.jsx("th",{scope:"col",children:"Share of voice"}),e.jsx("th",{scope:"col",children:"Mentions"}),e.jsx("th",{scope:"col",children:"Citations"}),e.jsx("th",{scope:"col",children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsxs("tbody",{children:[s?e.jsxs(e.Fragment,{children:[e.jsx(fr,{children:"You"}),e.jsx(gr,{row:s.project,shareContext:s,isProject:!0,metricState:P,canManage:!1})]}):null,e.jsx(fr,{children:"Pinned"}),f.length>0?f.map(k=>e.jsx(gr,{row:{...k,pinned:!0},shareContext:s,metricState:P,canManage:d,onUnpin:c},k.domain)):e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"text-secondary",children:"No pinned competitors."})})]}),s&&y.length>0?e.jsx(Qm,{shareContext:s,rows:y,canManage:d,onPin:i},JSON.stringify([t,s.project.domain,s.scope,s.filters])):null]})}),N?e.jsxs("details",{className:"group text-sm text-secondary",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer list-none flex-wrap items-center justify-between gap-x-4 gap-y-1 rounded-md hover:text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500 [&::-webkit-details-marker]:hidden",children:[e.jsxs("span",{className:"flex flex-wrap items-center gap-x-4 gap-y-1",children:[e.jsxs("span",{children:[N.answeredResults," ",N.answeredResults===1?"answer":"answers"]}),N.missingAnswerTextResults>0?e.jsx("span",{className:"text-caution",children:"Answer data incomplete"}):null,N.incompleteSourceResults>0?e.jsx("span",{className:"text-caution",children:"Citation data incomplete"}):null]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:["About these results",e.jsx(Hs,{size:14,"aria-hidden":"true",className:"transition-transform group-open:rotate-180 motion-reduce:transition-none"})]})]}),e.jsxs("div",{className:"max-w-prose space-y-2 pb-2 pt-1",children:[y.length===0?e.jsx("p",{children:"No additional competitors were identified in this period."}):null,e.jsxs("p",{children:[N.sourceResults," ",N.sourceResults===1?"result includes":"results include"," source URLs."]}),N.missingAnswerTextResults>0?e.jsxs("p",{children:[N.missingAnswerTextResults," ",N.missingAnswerTextResults===1?"result has":"results have"," no answer text and ",N.missingAnswerTextResults===1?"is":"are"," excluded from mention share."]}):null,N.incompleteSourceResults>0?e.jsxs("p",{children:[N.incompleteSourceResults," ",N.incompleteSourceResults===1?"result has an incomplete source list":"results have incomplete source lists",". Recorded citations still count; missing citations are not treated as confirmed misses."]}):null,N.excludedProbeResults+N.excludedNonCompletedResults>0?e.jsxs("p",{children:[N.excludedProbeResults+N.excludedNonCompletedResults," test or unfinished ",N.excludedProbeResults+N.excludedNonCompletedResults===1?"result is":"results are"," excluded."]}):null,s.truncated?e.jsx("p",{children:"Lists include up to 100 observed competitors and 100 other sources. All pinned competitors are included."}):null]})]}):null,M>0?e.jsx("p",{className:"text-sm text-secondary",children:s?.scope.kind==="all-markets"?`${M} competitor${M===1?" is":"s are"} pending publication across markets.`:`${M} competitor${M===1?" is":"s are"} pending publication for this market.`}):null,(s?.observedNames?.length??0)>0?e.jsxs("details",{className:"inline-disclosure text-sm text-secondary",children:[e.jsx("summary",{children:"Names observed in answers"}),e.jsx("p",{children:"Names are observations. Only classified competitor domains enter share of voice."}),e.jsx("ul",{children:s?.observedNames?.map(k=>e.jsxs("li",{children:[k.name," · ",k.answerCount," answers"]},k.name))})]}):null,j.length>0?e.jsxs("details",{className:"inline-disclosure",children:[e.jsxs("summary",{children:["Other observed sources (",j.length,")"]}),e.jsx("ul",{className:"mt-3 space-y-2 text-sm text-secondary",children:j.map(k=>e.jsxs("li",{children:[e.jsxs("span",{children:[k.label," · ",Bo(k.surfaceClass)," · ",k.citationCount," citations"]}),k.sampleUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1 font-mono text-[11px] text-muted",children:k.sampleUrls.map(p=>e.jsx("li",{className:"break-all",children:p},p))}):null]},k.domain))})]}):null]}),d&&u?e.jsx(Hm,{onAddCompetitor:u}):null]})}function li({history:t,maxDots:s=12}){const n=t.slice(-s);if(n.length===0)return e.jsx("span",{className:"text-[11px] text-faint",children:"No data"});const a={cited:"bg-positive-400","not-cited":"bg-mono-600",lost:"bg-negative-400",emerging:"bg-caution-400 ring-1 ring-caution-300/60"},r={cited:"rounded-full","not-cited":"rounded-sm",lost:"rotate-45 rounded-[1px]",emerging:"rounded-full"},o=n.length-1,i=new Date(n[0].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),c=new Date(n[o].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),u=n.map((h,m)=>{const x=new Date(h.createdAt).toLocaleDateString();return`${m===o?"Latest run, ":""}${x}: ${h.citationState}${h.model?`, model ${h.model}`:""}`}).join("; ");return e.jsxs("div",{className:"flex items-center gap-1",role:"img","aria-label":`Citation history across ${n.length} runs. ${u}`,children:[e.jsx("span",{className:"text-[9px] text-faint shrink-0","aria-hidden":"true",children:i}),e.jsx("div",{className:"flex items-center gap-[3px]",title:`${n.length} runs`,"aria-hidden":"true",children:n.map((h,m)=>{const x=!!(h.model&&m>0&&n[m-1]?.model&&n[m-1].model!==h.model),g=m===o;return e.jsx("span",{className:`h-2.5 w-2.5 ${r[h.citationState]??"rounded-sm"} ${a[h.citationState]??"bg-mono-700"} ${x?"ring-1 ring-caution-300/80 ring-offset-1 ring-offset-bg":""} ${g?"outline outline-1 outline-offset-2 outline-mono-400":""}`,title:[h.citationState,new Date(h.createdAt).toLocaleDateString(),h.model?`model ${h.model}`:null,x?"model changed":null,g?"latest run":null].filter(Boolean).join(" · ")},`${h.runId}:${h.createdAt}`)})}),e.jsxs("span",{className:"text-[9px] shrink-0 text-secondary","aria-hidden":"true",children:[c," ",e.jsx("span",{className:"text-faint",children:"latest"})]})]})}function yr(t){const s=new Map;for(const a of t)for(const r of a.runHistory){const o=s.get(r.createdAt);o?o.states.push(r.citationState):s.set(r.createdAt,{states:[r.citationState],runId:r.runId})}return[...s.entries()].sort(([a],[r])=>a.localeCompare(r)).map(([a,{states:r,runId:o}])=>({runId:o,createdAt:a,citationState:r.includes("cited")?"cited":r.includes("emerging")?"emerging":"not-cited"}))}const Ym=320;function Jm(t){return t==="branded"?"Branded":t==="non-brand"?"Non-brand":"Unclassified"}function Xm(t){return[t.phrase,t.location??"",...t.rawItems.map(s=>s.provider)].join(" ")}function ci(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 di(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 ui(t,s){const n=s==="mentions"?"mentioned":"cited",a=s==="mentions"?"Mentioned":"Cited";if(t.length===0)return"Awaiting first run";if(t.length===1)return"First observation";const r=t[t.length-1].citationState,o=t[t.length-2].citationState;if(o!=="cited"&&r==="cited")return`Newly ${n}`;if(o==="cited"&&r!=="cited")return"Lost since last run";let i=0;for(let c=t.length-1;c>=0&&t[c].citationState===r;c--)i++;return r==="cited"?i<=1?`${a} in latest run`:`${a} for ${i} runs`:i<=1?`Not ${n} in latest run`:`Not ${n} across ${i} runs`}function Zm(t,s){return t.map(n=>Vo(n,s))}function Vo(t,s){return s==="citations"?t:{...t,citationState:ci(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:ci(n,s)}))}}function mi(t,s){const n=s==="mentions"?"mention":"citation",a=s==="mentions"?"Mention":"Citation";if(t.length===0)return{key:s,label:`${a} pending`,tone:"pending"};const r=t[t.length-1].citationState,o=t.length>=2?t[t.length-2].citationState:null,i=r==="cited"||r==="emerging",c=o==="cited"||o==="emerging";return r==="lost"||o!==null&&c&&!i?{key:s,label:`Lost ${n}`,tone:"negative"}:r==="emerging"||o!==null&&!c&&i?{key:s,label:`New ${n}`,tone:"positive"}:o===null&&i?{key:s,label:`First ${n}`,tone:"positive"}:i?{key:s,label:s==="mentions"?"Still mentioned":"Still cited",tone:"neutral"}:{key:s,label:`No ${n}`,tone:"neutral"}}function eh(t){const s=yr(Zm(t,"mentions")),n=yr(t);return[mi(s,"mentions"),mi(n,"citations")]}function th({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 hi({items:t}){return e.jsx("div",{className:"mt-1 flex flex-wrap gap-1","aria-label":"Latest run mention and citation signals",children:eh(t).map(s=>e.jsx(th,{signal:s},s.key))})}function sh({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:a}=bo(),[r,o]=l.useState(new Set),[i,c]=l.useState("mentions"),[u,h]=l.useState(n),[m,x]=l.useState("all"),g=l.useMemo(()=>{const p=new Map;for(const v of t){const S=v.query,$=v.queryClass??null,q=s?v.location??null:null,L=JSON.stringify([S,$,q]),Q=p.get(L)??{key:L,phrase:S,queryClass:$,location:q,items:[],rawItems:[]};Q.items.push(Vo(v,i)),Q.rawItems.push(v),p.set(L,Q)}return[...p.values()]},[t,i,s]),d=l.useMemo(()=>g.filter(p=>m==="all"||(m==="unclassified"?p.queryClass===null:p.queryClass===m)),[g,m]),f=xn({rows:d,getSearchText:Xm}),y=f.rows.map(p=>p.key),j=y.length>0&&y.every(p=>r.has(p)),N=p=>{o(v=>{const S=new Set(v);return S.has(p)?S.delete(p):S.add(p),S})},P=i==="mentions"?"mentioned":"cited",M=i==="mentions"?"Mention History":"Citation History",k=i==="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":i==="mentions",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${i==="mentions"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>c("mentions"),children:"Mentions"}),e.jsx("button",{type:"button",role:"tab","aria-selected":i==="citations",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${i==="citations"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>c("citations"),children:"Citations"})]}),e.jsx("span",{className:"text-[11px] text-muted",children:i==="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:()=>{o(p=>{const v=new Set(p);for(const S of y)j?v.delete(S):v.add(S);return v})},children:j?"Collapse page":"Expand page"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Density"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-bg-elevated/60 border border-subtle",role:"tablist","aria-label":"Evidence row density",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":u==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${u==="compact"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>h("compact"),children:"Compact"}),e.jsx("button",{type:"button",role:"tab","aria-selected":u==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${u==="detailed"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>h("detailed"),children:"Detailed"})]})]})]})]}),g.length>0?e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-3",children:[e.jsx(Us,{value:f.query,onChange:f.setQuery,label:"Filter tracked queries",placeholder:"Filter query, location, or provider",className:"w-full max-w-md"}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-secondary",children:["Query class",e.jsxs("select",{value:m,onChange:p=>{x(p.target.value),f.setPage(1)},className:"h-9 rounded-md border border-default bg-surface px-3 text-sm text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500",children:[e.jsx("option",{value:"all",children:"All queries"}),e.jsx("option",{value:"branded",children:"Branded"}),e.jsx("option",{value:"non-brand",children:"Non-brand"}),e.jsx("option",{value:"unclassified",children:"Unclassified"})]})]})]}):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:M}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:f.rows.map(({key:p,phrase:v,queryClass:S,location:$,items:q,rawItems:L})=>{const Q=r.has(p),w=q.map(D=>D.citationState),X=w.includes("cited")?"cited":w.includes("emerging")?"emerging":w.includes("lost")?"lost":w.every(D=>D==="pending")?"pending":"not-cited",C=yr(q),F=q.filter(D=>D.citationState===Dl.cited||D.citationState==="emerging").length,_=ui(C,i);return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"cursor-pointer hover:bg-mono-800/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>N(p),onKeyDown:D=>{(D.key==="Enter"||D.key===" ")&&(D.preventDefault(),N(p))},tabIndex:0,role:"button","aria-expanded":Q,children:[e.jsx("td",{children:e.jsx(Ju,{size:14,className:`transition-transform duration-150 text-muted ${Q?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-heading",children:v}),s&&e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-muted",children:$??"No location"}),e.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[e.jsx(ce,{tone:"neutral",className:"whitespace-nowrap",children:Jm(S)}),q.map(D=>e.jsx(Cn,{provider:D.provider},D.id))]})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pr,{state:X,label:di(X,i)}),e.jsxs("span",{className:"text-[11px] text-muted",title:`${F} of ${q.length} engines ${k}`,children:[F,"/",q.length]})]})}),e.jsx("td",{children:e.jsx(li,{history:C})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:_}),e.jsx(hi,{items:L})]}),e.jsx("td",{})]}),Q&&q.map((D,Z)=>e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"bg-surface",children:[e.jsx("td",{}),e.jsx("td",{className:"evidence-query-cell pl-5",children:e.jsx(Cn,{provider:D.provider})}),e.jsx("td",{children:e.jsx(pr,{state:D.citationState,label:di(D.citationState,i)})}),e.jsx("td",{children:e.jsx(li,{history:D.runHistory})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:ui(D.runHistory,i)}),e.jsx(hi,{items:[L[Z]??D]})]}),e.jsx("td",{children:e.jsx(A,{variant:"ghost",size:"sm",type:"button",onClick:oe=>{oe.stopPropagation(),a(D.id)},children:"View"})})]}),u==="detailed"&&e.jsxs("tr",{className:"bg-surface-subtle",children:[e.jsx("td",{}),e.jsx("td",{colSpan:5,className:"px-5 pb-4",children:e.jsx(rh,{item:D,onViewFull:()=>a(D.id)})})]})]},D.id))]},p)})})]})}),f.totalRows===0&&(f.hasQuery||m!=="all")?e.jsx("p",{className:"supporting-copy mt-3",children:"No tracked queries match this filter."}):null,e.jsx(Rs,{page:f.page,pageSize:f.pageSize,visibleRows:f.rows.length,totalRows:f.totalRows,onPageChange:f.setPage,itemLabel:f.hasQuery||m!=="all"?"matches":"queries"}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",P==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function nh(t){const s=(t.matchedTerms??[]).filter(r=>r.trim().length>2),n=[...(t.mentionedCompetitorDomains??[]).flatMap(r=>{const o=Fl(r);return o.length>=4?[o]:[]}),...t.recommendedCompetitors??[]].filter(r=>r.trim().length>2),a=[];return s.length>0&&a.push({terms:s,className:"answer-highlight-brand"}),n.length>0&&a.push({terms:n,className:"answer-highlight-competitor"}),a}function xi(t,s){const n=s.toLowerCase().replace(/^www\./,"");return(t.citedCompetitorDomains??[]).some(a=>a.toLowerCase().replace(/^www\./,"")===n)}function ah(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 rh({item:t,onViewFull:s}){if(!(t.answerSnippet.trim().length>0))return e.jsx("p",{className:"text-[11px] text-muted italic",children:"No answer text captured for this run."});const{body:a,truncated:r}=ah(t.answerSnippet,Ym),o=nh(t);return e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Answer text"}),e.jsx("p",{className:"text-sm leading-relaxed text-neutral",children:Ol(a,o)}),(t.citedDomains.length>0||(t.mentionedCompetitorDomains?.length??0)>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(i=>e.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[11px] ${xi(t,i)?"border-negative-900/40 bg-negative-950/30 text-negative":"border-mono-700/60 bg-bg-elevated/60 text-neutral"}`,children:[i,xi(t,i)?" · competitor source":""]},`c-${i}`)),t.citedDomains.length>6&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.citedDomains.length-6," more"]})]}),(t.mentionedCompetitorDomains?.length??0)>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-negative-500/80",children:"Competitors in answer:"}),t.mentionedCompetitorDomains.slice(0,4).map(i=>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:i},`co-${i}`)),t.mentionedCompetitorDomains.length>4&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.mentionedCompetitorDomains.length-4," more"]})]})]}),r&&e.jsx("button",{type:"button",className:"text-[11px] font-medium text-positive-400 hover:text-positive",onClick:i=>{i.stopPropagation(),s()},children:"View full answer →"})]})}function ea({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})]})}function Ra({windows:t,value:s,onChange:n,label:a,formatOption:r,disabled:o=!1}){return e.jsx("div",{className:"segmented",role:"group","aria-label":a,children:t.map(i=>e.jsx("button",{type:"button","aria-pressed":s===i,disabled:o,className:`segmented-option ${s===i?"segmented-option-active":""}`,onClick:()=>n(i),children:r?r(i):i},i))})}const Ga=nt[0],Ka=nt[1],pi=nt[2],gi=nt[3],ih=["both","server","ga4"],fi={fontSize:11,paddingTop:6},yi=new Set(["Pages crawled trend","Page fetches trend","Visits trend"]),bi=t=>typeof t=="number"?Vs(Math.round(t)):String(t),es=t=>typeof t=="number"&&Number.isFinite(t)?t:0;function _a(t,s){if(!t||s<2)return Array(s).fill(null);const n=t.endIndex-t.startIndex;if(n<=0)return Array(s).fill(null);const a=(t.end-t.start)/n;return Array.from({length:s},(r,o)=>o<t.startIndex||o>t.endIndex?null:t.start+(o-t.startIndex)*a)}function Ua({label:t,value:s,caption:n,tooltip:a}){return e.jsxs("div",{className:"rounded-lg border border-default bg-bg/40 px-4 py-3 flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-1 mb-1",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted",children:t}),e.jsx(Me,{text:a})]}),e.jsx("p",{className:"text-xl font-semibold text-primary tabular-nums",children:s}),e.jsx("p",{className:"text-xs text-muted mt-0.5",children:n})]})}function oh(t,s){return n=>{const{cx:a,cy:r,index:o,key:i}=n,c=o??-1;return!(t[c]!=null&&t[c-1]==null&&t[c+1]==null)||a===void 0||r===void 0?e.jsx("g",{},i):e.jsx("circle",{cx:a,cy:r,r:2.6,fill:s,stroke:"none"},i)}}function lh({projectName:t,sinceMinutes:s}){const[n,a]=l.useState(!0),[r,o]=l.useState(!0),[i,c]=l.useState("both"),u=um(t,{sinceMinutes:s,granularity:"day",limit:1}),h=mm(t),x=we({...vo({client:H,path:{name:t}}),enabled:!!t,staleTime:dn}).data?.connected===!0,g=we({...jo({client:H,path:{name:t},query:{window:s>=2160*60?"90d":s>=720*60?"30d":"7d"}}),enabled:!!t&&x,staleTime:dn}),d=l.useMemo(()=>u.data?.series?.points??[],[u.data]),f=l.useMemo(()=>{const $=g.data;return new Map(($?.days??[]).map(q=>[q.date,q.sessions]))},[g.data]),y=l.useMemo(()=>{const $=L=>L.measured!==!1;if(d.length===0||$(d[0]))return null;const q=d.findIndex($)-1;return q<0?{from:d[0].bucket,to:d[d.length-1].bucket}:{from:d[0].bucket,to:d[q].bucket}},[d]),j=u.data?.series?.coverageStart??null,N=u.data?.series?.trends,P=l.useMemo(()=>{const $=_a(N?.crawlerContentHits,d.length),q=_a(N?.aiUserFetchHits,d.length),L=_a(N?.aiReferralLandedHits,d.length);return d.map((Q,w)=>({...Q,crawlerContentHits:Q.measured!==!1?es(Q.crawlerContentHits):null,aiUserFetchHits:Q.measured!==!1?es(Q.aiUserFetchHits):null,aiReferralLandedHits:Q.measured!==!1?es(Q.aiReferralLandedHits):null,ga4Visits:f.get(Q.bucket)??null,crawlTrend:$[w],fetchTrend:q[w],visitTrend:L[w]}))},[d,f,N]),M=u.data?.totals,k=M&&{crawlers:es(M.crawlerContentHits),fetches:es(M.aiUserFetchHits),visits:es(M.aiReferralLandedHits)},p=l.useMemo(()=>d.reduce(($,q)=>({crawlers:$.crawlers+es(q.crawlerContentHits),fetches:$.fetches+es(q.aiUserFetchHits),visits:$.visits+es(q.aiReferralLandedHits)}),{crawlers:0,fetches:0,visits:0}),[d]),v=k??p,S=v.crawlers>0||v.fetches>0||v.visits>0;if(u.isLoading)return e.jsx(xe,{className:"surface-card p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading AI traffic history…"})});if(u.isError)return e.jsxs(xe,{className:"surface-card p-5",children:[e.jsx("p",{className:"text-sm text-secondary",children:"Could not load AI traffic history."}),e.jsx("p",{className:"text-xs text-muted mt-1",children:"The request failed, so this is not a reading of zero activity. Retry, or check the traffic source."})]});if(!S){const $=h.data?.sources,q=$!==void 0&&$.length===0,L=!q&&j===null;return e.jsxs(xe,{className:"surface-card p-5",children:[e.jsx("p",{className:"text-sm text-secondary",children:q?"No server-side traffic source connected yet.":L?"No AI activity recorded yet.":"No AI activity recorded in this period."}),e.jsx("p",{className:"text-xs text-muted mt-1",children:q?"Connect a traffic source to see how AI engines read this site over time.":L?"The source is connected but has not reported anything yet. A new source can take a few hours to appear.":"The window was measured and nothing was recorded. Try a longer range."})]})}return e.jsxs(xe,{className:"surface-card p-5",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3 mb-5",children:[e.jsx(Ua,{label:"AI crawlers",value:Vs(v.crawlers),caption:"pages crawled",tooltip:"Requests from AI crawlers for a real content page. Robots.txt and sitemap re-fetches are excluded, because they are not a page an engine read."}),e.jsx(Ua,{label:"AI page fetches",value:Vs(v.fetches),caption:"reading a page to answer",tooltip:"An AI engine fetching a page live while answering someone, rather than crawling it for an index."}),e.jsx(Ua,{label:"AI visitors",value:Vs(v.visits),caption:"arrived from an AI answer",tooltip:"Visits your server answered that came from an AI engine. Requests answered with a redirect are excluded: a redirect is a hop, not an arrival."})]}),d.length>0&&e.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-5 gap-y-1 pb-3 mb-4 border-b border-default text-xs text-muted",children:[e.jsx("span",{className:"text-secondary font-semibold",children:"Latest day (UTC)"}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:es(d[d.length-1].crawlerContentHits).toLocaleString()}),"pages crawled"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:es(d[d.length-1].aiUserFetchHits).toLocaleString()}),"page fetches"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:es(d[d.length-1].aiReferralLandedHits).toLocaleString()}),"visits, server"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:f.get(d[d.length-1].bucket)?.toLocaleString()??"—"}),"visits, GA4"]}),e.jsx("span",{className:"text-faint",children:"still filling"})]}),e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Machines reading your site"}),e.jsx(Me,{text:"Crawlers index pages for later. Page fetches happen while an engine is answering someone. Both are machines, not people."})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-secondary cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:n,onChange:$=>a($.target.checked),className:"accent-current"}),"Page fetches"]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-secondary cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:r,onChange:$=>o($.target.checked),className:"accent-current"}),"Trend line"]})]})]}),e.jsx(Ws,{width:"100%",height:206,children:e.jsxs(Ys,{data:P,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(Vn,{stroke:Bn,vertical:!1}),e.jsx(Js,{dataKey:"bucket",tick:Rt,stroke:is,tickFormatter:pn,minTickGap:28}),e.jsx(Xs,{tick:Rt,stroke:is,width:48,allowDecimals:!1}),e.jsx(Zs,{contentStyle:as.contentStyle,labelStyle:as.labelStyle,itemStyle:as.itemStyle,labelFormatter:Ot,formatter:bi}),y&&e.jsx(xr,{x1:y.from,x2:y.to,fill:"var(--color-overlay-hover)",fillOpacity:.5,stroke:"none",label:{value:"not measured",position:"insideTop",fontSize:10,fill:"var(--chart-neutral-text-dim, #71717a)"}}),e.jsx(wa,{wrapperStyle:fi,iconType:"plainline",iconSize:14,formatter:$=>yi.has($)?"":$}),e.jsx(Fs,{type:"monotone",dataKey:"crawlerContentHits",name:"Pages crawled",stroke:Ga,fill:Ga,fillOpacity:.22,strokeWidth:1.8}),n&&e.jsx(Fs,{type:"monotone",dataKey:"aiUserFetchHits",name:"Page fetches",stroke:Ka,fill:Ka,fillOpacity:.18,strokeWidth:1.6}),r&&e.jsx(As,{type:"linear",dataKey:"crawlTrend",name:"Pages crawled trend",dot:!1,tooltipType:"none",stroke:Ga,strokeWidth:1.4,strokeDasharray:"5 4",connectNulls:!0}),r&&n&&e.jsx(As,{type:"linear",dataKey:"fetchTrend",name:"Page fetches trend",dot:!1,tooltipType:"none",stroke:Ka,strokeWidth:1.3,strokeDasharray:"5 4",connectNulls:!0})]})}),e.jsxs("div",{className:"flex items-center justify-between gap-3 mt-5 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"People arriving from AI"}),e.jsx(Me,{text:"Two independent counts of the same thing. Server reads your own logs and misses nothing a browser blocks, but cannot see a page served from cache. GA4 needs the browser to run a tag. They rarely match, and neither is the correction of the other."})]}),e.jsx(Ra,{windows:ih,value:i,onChange:c,label:"Visit measurement source",formatOption:$=>$==="ga4"?"GA4":$==="both"?"Both":"Server"})]}),e.jsx(Ws,{width:"100%",height:176,children:e.jsxs(Ys,{data:P,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(Vn,{stroke:Bn,vertical:!1}),e.jsx(Js,{dataKey:"bucket",tick:Rt,stroke:is,tickFormatter:pn,minTickGap:28}),e.jsx(Xs,{tick:Rt,stroke:is,width:48,allowDecimals:!1}),e.jsx(Zs,{contentStyle:as.contentStyle,labelStyle:as.labelStyle,itemStyle:as.itemStyle,labelFormatter:Ot,formatter:bi}),y&&e.jsx(xr,{x1:y.from,x2:y.to,fill:"var(--color-overlay-hover)",fillOpacity:.5,stroke:"none",label:{value:"not measured",position:"insideTop",fontSize:10,fill:"var(--chart-neutral-text-dim, #71717a)"}}),e.jsx(wa,{wrapperStyle:fi,iconType:"plainline",iconSize:14,formatter:$=>yi.has($)?"":$}),i!=="ga4"&&e.jsx(As,{type:"monotone",dataKey:"aiReferralLandedHits",name:"Visits, server",stroke:pi,strokeWidth:2,dot:!1}),i!=="server"&&e.jsx(As,{type:"monotone",dataKey:"ga4Visits",name:"Visits, GA4",connectNulls:!1,stroke:gi,strokeWidth:1.8,strokeDasharray:"5 3",dot:oh(P.map($=>$.ga4Visits),gi)}),r&&i!=="ga4"&&e.jsx(As,{type:"linear",dataKey:"visitTrend",name:"Visits trend",dot:!1,tooltipType:"none",stroke:pi,strokeWidth:1.3,strokeDasharray:"5 4",connectNulls:!0})]})})]})}const ch=6,kn="__other__",wn="_socialTotal";function dh(t,s=ch){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,x)=>x[1]!==m[1]?x[1]-m[1]:m[0].localeCompare(x[0])),r=a.slice(0,s),o=new Set(r.map(([m])=>m)),i=Math.max(0,a.length-s),c=new Map;for(const m of t){let x=c.get(m.date);x||(x={date:m.date,[wn]:0},c.set(m.date,x));const g=o.has(m.source)?m.source:kn;x[g]=(x[g]??0)+m.sessions,x[wn]=(x[wn]??0)+m.sessions}const u=[...c.values()].sort((m,x)=>String(m.date).localeCompare(String(x.date))),h=r.map(([m])=>m);return i>0&&h.push(kn),{data:u,sources:h,otherCount:i}}function Sn(t){return t.replace(/\+/g," ")}function zo(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const vi="_totalSessions",ji="_organicSessions";function uh(t,s){const n=new Map;for(const i of s)n.set(i.date,{[vi]:i.sessions,[ji]:i.organicSessions});for(const i of t.days){let c=n.get(i.date);c||(c={[vi]:0,[ji]:0},n.set(i.date,c));for(const u of i.bySource)c[u.source]=(c[u.source]??0)+u.sessions}const a=[...n.entries()].sort(([i],[c])=>i.localeCompare(c)).map(([i,c])=>({date:i,...c})),r=a.map(i=>i.date),o=r.length>0?{start:r[0],end:r[r.length-1]}:null;return{data:a,sources:t.sources,dateRange:o}}const mh=["7d","30d","90d"],hh={"7d":10080,"30d":720*60,"90d":2160*60,all:2160*60},Os=nt,br=os.textDim,Qo=os.textFaint,Tn=25;function xh(t){return Lo(t.landingPage)}const ph=25,gh=10,Ba={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0};function ta(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function Ho(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 fh({projectName:t}){const{data:s,isLoading:n,isError:a}=hm(t);if(n)return e.jsx(xe,{className:"p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading server activity…"})});if(a)return e.jsx(xe,{className:"p-5",children:e.jsx("div",{className:"text-sm text-negative-400",children:"Failed to load server activity."})});const r=s?.sources??[];return e.jsxs("section",{children:[e.jsx("div",{className:"flex items-baseline justify-between mb-3",children:e.jsxs("div",{children:[e.jsx("div",{className:"eyebrow",children:"Server activity (last 24h)"}),e.jsx("h2",{className:"text-lg font-semibold text-primary",children:"Server activity"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["Crawler, AI fetch, and referral activity from connected sources."," ",!te()&&e.jsx(vs,{to:"/traffic",className:"text-link hover:underline",children:"Manage sources →"})]})]})}),r.length===0?e.jsx(xe,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-secondary",children:["No server traffic source connected yet."," ",!te()&&e.jsxs(e.Fragment,{children:[e.jsx(vs,{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(xe,{className:"overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-bg-elevated/50 text-[10px] uppercase tracking-wide text-muted",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Source"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Status"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Crawler hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI sessions 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Last sync"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium","aria-label":"open"})]})}),e.jsx("tbody",{children:r.map(o=>e.jsxs("tr",{className:"border-t border-default",children:[e.jsx("td",{className:"px-4 py-3 text-heading",children:o.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(ce,{tone:xm(o.status),children:o.status})}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:o.totals24h.crawlerHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:o.totals24h.aiUserFetchHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:o.totals24h.aiReferralLandedHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right text-secondary text-xs",children:o.lastSyncedAt?Ho(o.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:te()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(vs,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:o.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},o.id))})]})})]})}function yh({projectName:t}){const[s,n]=l.useState("30d");return e.jsxs("div",{className:"space-y-10",children:[e.jsx(fh,{projectName:t}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(Ra,{windows:mh,value:s,onChange:n,label:"Traffic time period"})}),e.jsx(bh,{projectName:t,window:s}),e.jsx(lh,{projectName:t,sinceMinutes:hh[s]})]})}function bh({projectName:t,window:s}){const n=js(),a=s??"30d",[r,o]=l.useState(null),[i,c]=l.useState(null),[u,h]=l.useState(!0),[m,x]=l.useState(!1),[g,d]=l.useState(!1),[f,y]=l.useState(null),[j,N]=l.useState(null),[P,M]=l.useState("sessions"),[k,p]=l.useState("desc"),[v,S]=l.useState("sessions"),[$,q]=l.useState("desc"),[L,Q]=l.useState("sessions"),[w,X]=l.useState("desc"),[C,F]=l.useState("sessions"),[_,D]=l.useState("desc"),[Z,oe]=l.useState(Ba),[ne,U]=l.useState([]),[T,G]=l.useState([]),[ae,W]=l.useState(!1);async function J(Y){h(!0),y(null);try{const Re=await n.fetchQuery({...vo({client:H,path:{name:t}}),staleTime:dn});if(Y.current)return;if(o(Re),!Re.connected){c(null),oe(Ba),U([]),G([]),h(!1);return}const be=a==="all"?void 0:a,je=await n.fetchQuery({...Gl({client:H,path:{name:t},query:be?{window:be}:void 0}),staleTime:dn}).then(ls=>ls),Gt=je.windowStart||je.windowEnd?{...je.windowStart?{startDate:je.windowStart}:{},...je.windowEnd?{endDate:je.windowEnd}:{}}:void 0,[ze,ft,Tt]=await Promise.all([n.fetchQuery({...jo({client:H,path:{name:t},query:be?{window:be}:void 0}),staleTime:dn}).catch(()=>Ba),n.fetchQuery({...Kl({client:H,path:{name:t},query:be?{window:be}:void 0}),staleTime:dn}).catch(()=>[]),n.fetchQuery({..._l({client:H,path:{name:t},query:Gt}),staleTime:dn}).catch(()=>[])]);if(Y.current)return;c(je),oe(ze),U(ft),G(Tt),h(!1)}catch(Re){if(Y.current)return;y(Re instanceof Error?Re.message:"Failed to load GA4 data"),h(!1)}}l.useEffect(()=>{const Y={current:!1};return J(Y),()=>{Y.current=!0}},[t,a,n]);async function ge(){x(!0),y(null),N(null);try{const Y=await No(t);N(`Synced ${Y.rowCount.toLocaleString()} page rows, ${Y.aiReferralCount.toLocaleString()} AI and ${Y.socialReferralCount.toLocaleString()} social referral rows (${Y.days} days)`),await Nt(n,"ga"),await J({current:!1})}catch(Y){y(Y instanceof Error?Y.message:"Sync failed")}finally{x(!1)}}async function z(){d(!0),y(null),N(null);try{await Ul(t),await Nt(n,"ga"),o({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),c(null),N("GA4 disconnected")}catch(Y){y(Y instanceof Error?Y.message:"Disconnect failed")}finally{d(!1)}}function re(Y){Pe.setPage(1),P===Y?p(Re=>Re==="desc"?"asc":"desc"):(M(Y),p("desc"))}function ue(Y){v===Y?q(Re=>Re==="desc"?"asc":"desc"):(S(Y),q("desc"))}function Oe(Y){L===Y?X(Re=>Re==="desc"?"asc":"desc"):(Q(Y),X("desc"))}const Fe=l.useMemo(()=>i?.topPages?[...i.topPages].sort((Y,Re)=>{const be=Y[P],je=Re[P];return typeof be=="string"&&typeof je=="string"?k==="asc"?be.localeCompare(je):je.localeCompare(be):k==="asc"?be-je:je-be}):[],[i?.topPages,P,k]),Pe=xn({rows:Fe,getSearchText:Y=>Lo(Y.landingPage),pageSize:gh}),tt=l.useMemo(()=>i?.aiReferrals?[...i.aiReferrals].sort((Y,Re)=>{const be=Y[v],je=Re[v];return typeof be=="string"&&typeof je=="string"?$==="asc"?be.localeCompare(je):je.localeCompare(be):$==="asc"?be-je:je-be}):[],[i?.aiReferrals,v,$]),it=l.useMemo(()=>i?.aiReferralLandingPages?[...i.aiReferralLandingPages].sort((Y,Re)=>{const be=Y[C],je=Re[C];return typeof be=="string"&&typeof je=="string"?_==="asc"?be.localeCompare(je):je.localeCompare(be):_==="asc"?be-je:je-be}):[],[i?.aiReferralLandingPages,C,_]),ke=xn({rows:it,getSearchText:xh,pageSize:ph}),Xe=ke.totalRows>0?`${ke.totalRows.toLocaleString()} ${ke.hasQuery?ke.totalRows===1?"match":"matches":ke.totalRows===1?"row":"rows"}`:ke.hasQuery&&(i?.aiReferralLandingPages.length??0)>0?"0 matches":"No landing-page rows";function _e(Y){ke.setPage(1),C===Y?D(Re=>Re==="desc"?"asc":"desc"):(F(Y),D("desc"))}const Ve=l.useMemo(()=>i?.socialReferrals?[...i.socialReferrals].sort((Y,Re)=>{const be=Y[L],je=Re[L];return typeof be=="string"&&typeof je=="string"?w==="asc"?be.localeCompare(je):je.localeCompare(be):w==="asc"?be-je:je-be}):[],[i?.socialReferrals,L,w]),{socialChartData:He,socialChartSources:Te,socialOtherCount:B}=l.useMemo(()=>{const Y=dh(T);return{socialChartData:Y.data,socialChartSources:Y.sources,socialOtherCount:Y.otherCount}},[T]),{chartData:O,chartSources:V,dateRange:Ne}=l.useMemo(()=>{const Y=uh(Z,ne);return{chartData:Y.data,chartSources:Y.sources,dateRange:Y.dateRange}},[Z,ne]);if(u&&!r)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!r?.connected)return te()?e.jsx(xe,{className:"p-5",children:e.jsx("div",{className:"text-sm text-secondary",children:"No Google Analytics 4 property connected yet."})}):e.jsx(vh,{projectName:t,onConnected:()=>{(async()=>(await Nt(n,"ga"),await J({current:!1})))()}});const Ie=i?.organicSharePctDisplay??"0%",ee=i?.channelBreakdown?.organic.sharePctDisplay??Ie,We=i?.channelBreakdown?.organic.sessions??i?.totalOrganicSessions??0,ht=i?.aiSessionsDeduped??0,Ze=i?.channelBreakdown?.ai.sessions??i?.aiSessionsBySession??0,ye=i?.channelBreakdown?.ai.sharePctDisplay??i?.aiSharePctBySessionDisplay??"0%",Ge=i?.paidAiSessionsBySession??0,It=i?.paidAiSharePctBySessionDisplay??"0%",xt=i?new Set(i.aiReferrals.map(Y=>Y.source.toLowerCase())).size:0,Ee=tt[0]??null,Ye=i?.totalDirectSessions??0,pt=i?.directSharePctDisplay??"0%",St=i?.channelBreakdown?.direct.sessions??Ye,Ke=i?.channelBreakdown?.direct.sharePctDisplay??pt,Le=i?.channelBreakdown?.other.sessions??i?.otherSessions??0,et=i?.channelBreakdown?.other.sharePctDisplay??i?.otherSharePctDisplay??"0%",Ue=i?.socialSessions??0,Be=i?.socialSharePctDisplay??"0%",$t=i?.channelBreakdown?.social.sessions??Ue,vt=i?.channelBreakdown?.social.sharePctDisplay??Be,Ft=i?new Set(i.socialReferrals.map(Y=>Y.source.toLowerCase())).size:0,gt=Ve[0]??null;return e.jsxs(e.Fragment,{children:[f&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative",children:f}),j&&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:j}),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:r.propertyId}),r.clientEmail&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"text-muted",children:r.clientEmail})]})]})]}),!te()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(A,{variant:"outline",size:"sm",disabled:m,onClick:qe(ge),children:[e.jsx(Na,{className:`w-3.5 h-3.5 mr-1.5 ${m?"animate-spin":""}`}),m?"Syncing…":"Sync"]}),e.jsxs(A,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:g,onClick:qe(z),children:[e.jsx(Xu,{className:"w-3.5 h-3.5 mr-1.5"}),"Disconnect"]})]})]}),e.jsxs("section",{children:[e.jsx("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(Me,{text:`Aggregated traffic metrics from Google Analytics 4.${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"})}.`:""} Distinct users are unavailable when the selected history extends beyond a stored aggregate. Organic sessions are Google organic search sessions specifically.`})]})]})}),i?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(Va,{value:ta(i.totalSessions),label:"Total Sessions",subtitle:i.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(Va,{value:ta(i.totalOrganicSessions),label:"Organic Sessions",subtitle:`${Ie} of total`,tone:"positive"}),e.jsx(Va,{value:i.totalUsers===null?"—":ta(i.totalUsers),label:"Total Users",subtitle:i.totalUsers===null?"Unavailable for this range":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."}),!te()&&e.jsxs(A,{variant:"outline",size:"sm",disabled:m,onClick:qe(ge),children:[e.jsx(Na,{className:`w-3.5 h-3.5 mr-1.5 ${m?"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(Me,{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."})]})]}),Ne&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(Ne.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(Ne.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),O.length>0&&e.jsxs(xe,{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:V.length>0?"AI vs. total sessions":"All sessions (baseline)"}),V.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),V.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(Ws,{width:"100%",height:"100%",children:e.jsxs(Ys,{data:O,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Js,{dataKey:"date",tick:Rt,tickLine:!1,axisLine:{stroke:is},tickFormatter:pn}),e.jsx(Xs,{tick:Rt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Zs,{...as,labelFormatter:Ot,formatter:(Y,Re)=>{const be=typeof Y=="number"?Y.toLocaleString():String(Y??0),je=String(Re??"");return je==="_totalSessions"?[be,"Total Sessions"]:je==="_organicSessions"?[be,"Organic Sessions"]:[be,je]}}),e.jsx(wa,{wrapperStyle:{fontSize:11,color:os.text},formatter:Y=>Y==="_totalSessions"?"Total Sessions":Y==="_organicSessions"?"Organic Sessions":Y}),e.jsx(Fs,{type:"monotone",dataKey:"_totalSessions",stroke:os.textFaint,fill:os.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),V.map((Y,Re)=>e.jsx(Fs,{type:"monotone",dataKey:Y,stackId:"ai",stroke:Os[Re%Os.length],fill:Os[Re%Os.length],fillOpacity:.4,strokeWidth:1.5},Y))]})})})]}),e.jsxs(xe,{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:"Sessions by channel"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(us,{label:"Organic",value:ee,hint:`${We.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(us,{label:"Social",value:vt,hint:`${$t.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(us,{label:"Direct",value:Ke,hint:`${St.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(us,{label:"Visitors from AI (at least)",value:ye,hint:Ge>0?`${Ze.toLocaleString()} sessions · ${Ge.toLocaleString()} paid`:`${Ze.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(us,{label:"Other channels",value:et,hint:`${Le.toLocaleString()} sessions`,tone:"neutral",tooltip:"Remaining GA4 session default channel groups after Known AI, Organic Search, Organic/Paid Social, and Direct are accounted for. This is a residual bucket, not a single source. It can include Referral, Email, Paid Search, Display, Cross-network, Shopping, Video, Affiliates, SMS, Mobile Push Notifications, Paid Other, and unclassified traffic."})]}),Ee&&e.jsxs("div",{className:"mt-4 rounded-lg border border-positive-800/40 bg-positive-500/6 px-4 py-3 text-sm text-positive-100",children:["Top AI referrer: ",e.jsx("span",{className:"font-medium",children:Ee.source})," via ",Ee.medium,", accounting for ",Ee.sessions.toLocaleString()," sessions.",Ge>0&&e.jsxs("span",{children:[" Paid AI: ",Ge.toLocaleString()," sessions (",It,")."]})]})]}),e.jsxs(xe,{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:"Where AI visitors came from"})]}),e.jsx("p",{className:"text-xs text-muted",children:i.aiReferrals.length>0?`${xt} 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(ts,{label:"Source",sortKey:"source",current:v,dir:$,onSort:ue,align:"left"}),e.jsx(ts,{label:"Medium",sortKey:"medium",current:v,dir:$,onSort:ue,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(ts,{label:"Sessions",sortKey:"sessions",current:v,dir:$,onSort:ue,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:tt.map(Y=>e.jsx(Nh,{referral:Y,totalSessions:ht},`${Y.source}:${Y.medium}:${Y.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(xe,{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:"Pages AI visitors landed on"})]}),e.jsx("p",{className:"text-xs text-muted",children:Xe})]}),i.aiReferralLandingPages.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Us,{value:ke.query,onChange:ke.setQuery,label:"Filter landing page URLs or query parameters",placeholder:"Filter URL or query parameters",className:"mb-4 max-w-md"}),ke.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(ts,{label:"Landing Page",sortKey:"landingPage",current:C,dir:_,onSort:_e,align:"left"}),e.jsx(ts,{label:"Source",sortKey:"source",current:C,dir:_,onSort:_e,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(ts,{label:"Sessions",sortKey:"sessions",current:C,dir:_,onSort:_e,align:"right"})]})}),e.jsx("tbody",{children:ke.rows.map(Y=>e.jsx(wh,{row:Y},`${Y.landingPage}:${Y.source}:${Y.medium}:${Y.sourceDimension}`))})]})}),e.jsx(Rs,{page:ke.page,pageSize:ke.pageSize,visibleRows:ke.rows.length,totalRows:ke.totalRows,onPageChange:ke.setPage,itemLabel:ke.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:()=>ke.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 visits recorded yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"Pages appear here once a GA4 sync records a visit that arrived from an AI engine."})]})]})]})]}),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(Me,{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."})]})]}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs(xe,{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:"Visits from social"})]}),i.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(us,{label:"Social Sessions",value:ta(Ue),hint:`${Ue.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(us,{label:"Share of Traffic",value:Be,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(us,{label:"Platforms",value:String(Ft),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."})]}),gt&&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:`${gt.source} via ${gt.medium}`,children:zo(Sn(gt.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:gt.medium,children:["via ",Sn(gt.medium)," · ",gt.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(us,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(us,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(us,{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."})]})]})]}),He.length>0&&e.jsxs(xe,{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:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social sessions"})]}),B>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",Te.length-1," sources · ",B," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(Ws,{width:"100%",height:"100%",children:e.jsxs(Ys,{data:He,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Js,{dataKey:"date",tick:Rt,tickLine:!1,axisLine:{stroke:is},tickFormatter:pn}),e.jsx(Xs,{tick:Rt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Zs,{...as,labelFormatter:Ot,formatter:(Y,Re)=>{const be=typeof Y=="number"?Y.toLocaleString():String(Y??0),je=String(Re??"");if(je===wn)return[be,"Total Social"];if(je===kn){const Gt=`Other (${B} source${B===1?"":"s"})`;return[be,Gt]}return[be,Sn(je)]}}),e.jsx(Fs,{type:"monotone",dataKey:wn,stroke:Qo,fill:os.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),Te.map((Y,Re)=>{const je=Y===kn?br:Os[Re%Os.length];return e.jsx(Fs,{type:"monotone",dataKey:Y,stackId:"social",stroke:je,fill:je,fillOpacity:.4,strokeWidth:1.5},Y)})]})})}),e.jsx(Ch,{sources:Te,otherCount:B})]}),e.jsxs(xe,{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:"Social sources"})]}),e.jsx("p",{className:"text-xs text-muted",children:i.socialReferrals.length>0?Ve.length>Tn&&!ae?`Top ${Tn} of ${Ve.length}`:`${Ve.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(ts,{label:"Source",sortKey:"source",current:L,dir:w,onSort:Oe,align:"left"}),e.jsx(ts,{label:"Medium",sortKey:"medium",current:L,dir:w,onSort:Oe,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(ts,{label:"Sessions",sortKey:"sessions",current:L,dir:w,onSort:Oe,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:(ae?Ve:Ve.slice(0,Tn)).map(Y=>e.jsx(Sh,{referral:Y,totalSessions:Ue},`${Y.source}:${Y.medium}:${Y.channelGroup}`))})]})}),Ve.length>Tn&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>W(Y=>!Y),className:"rounded-md border border-base px-3 py-1.5 text-xs text-secondary transition-colors hover:border-strong hover:text-strong",children:ae?`Show top ${Tn}`:`Show all ${Ve.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(Me,{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(Us,{value:Pe.query,onChange:Pe.setQuery,label:"Filter landing page URLs",placeholder:"Filter landing pages",className:"mb-4 max-w-md"}),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(ts,{label:"Landing Page",sortKey:"landingPage",current:P,dir:k,onSort:re,align:"left"}),e.jsx(ts,{label:"Sessions",sortKey:"sessions",current:P,dir:k,onSort:re,align:"right"}),e.jsx(ts,{label:"Organic",sortKey:"organicSessions",current:P,dir:k,onSort:re,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"})]})}),e.jsx("tbody",{children:Pe.rows.map(Y=>e.jsx(jh,{page:Y},Y.landingPage))})]})}),Pe.totalRows===0&&Pe.hasQuery&&e.jsx("p",{className:"text-sm text-secondary mt-3",children:"No landing pages match this filter"}),e.jsx(Rs,{page:Pe.page,pageSize:Pe.pageSize,visibleRows:Pe.rows.length,totalRows:Pe.totalRows,onPageChange:Pe.setPage,itemLabel:Pe.hasQuery?"matches":"pages"})]})]}),e.jsxs("div",{className:"mt-6 flex items-center justify-between text-xs text-muted",children:[e.jsx("span",{children:i?.lastSyncedAt?`Last synced ${Ho(i.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:i?`${i.topPages.length} pages · ${i.aiReferrals.length} AI rows · ${i.socialReferrals.length} social rows`:""})]})]})}function vh({projectName:t,onConnected:s}){const[n,a]=l.useState(""),[r,o]=l.useState(null),[i,c]=l.useState(null),[u,h]=l.useState(!1),[m,x]=l.useState(null),g=l.useRef(null),d=l.useCallback(y=>{const j=y.target.files?.[0];if(!j)return;x(null),o(j.name);const N=new FileReader;N.onload=()=>{const P=N.result;try{const M=JSON.parse(P);if(!M.client_email||!M.private_key){x("JSON file is missing required fields: client_email and private_key. Make sure you downloaded a service account key (not an OAuth client)."),c(null);return}c(P)}catch{x("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),c(null)}},N.onerror=()=>{x("Failed to read file."),c(null)},N.readAsText(j)},[]);async function f(){if(x(null),!n.trim()){x("Property ID is required.");return}if(!i){x("Please upload a service account key file.");return}h(!0);try{await Bl(t,{propertyId:n.trim(),keyJson:i});try{await No(t)}catch{}s()}catch(y){x(y instanceof Error?y.message:"Failed to connect GA4")}finally{h(!1)}}return e.jsxs(xe,{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:y=>a(y.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:g,type:"file",accept:".json,application/json",onChange:d,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>g.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(Zu,{className:"w-4 h-4 shrink-0"}),r?e.jsx("span",{className:"text-strong truncate",children:r}):e.jsx("span",{children:"Upload .json key file"})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Download from Google Cloud Console → IAM & Admin → Service Accounts → Keys → Add Key → JSON. The service account must have ",e.jsx("span",{className:"text-secondary",children:"Viewer"})," access on the GA4 property."]})]}),e.jsx(A,{variant:"default",size:"sm",disabled:u||!n.trim()||!i,onClick:qe(f),children:u?"Connecting & syncing…":"Connect GA4"})]})}function ts({label:t,sortKey:s,current:n,dir:a,onSort:r,align:o}){const i=n===s;return e.jsx("th",{className:`py-1 ${o==="right"?"text-right":"text-left"}`,children:e.jsxs("button",{type:"button",className:"font-medium cursor-pointer select-none hover:text-neutral transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-400 rounded",onClick:()=>r(s),"aria-label":`Sort by ${t}${i?` (currently ${a==="asc"?"ascending":"descending"})`:""}`,children:[t,i&&e.jsx("span",{className:"ml-0.5",children:a==="asc"?"↑":"↓"})]})})}const Wo={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function Va({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 ${Wo[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function us({value:t,label:s,hint:n,tone:a,tooltip:r}){return e.jsxs("div",{className:"rounded-lg border border-default bg-bg/40 px-4 py-3 flex flex-col",children:[e.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1 flex items-center gap-1",children:[s,r&&e.jsx(Me,{text:r})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${Wo[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function jh({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 Yo={session:"Session",first_user:"First Visit",manual_utm:"UTM"},Jo={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 Nh({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=Yo[t.sourceDimension]??t.sourceDimension,r=Jo[t.sourceDimension]??"",o=t.trafficClass==="paid"?"Paid":"Organic",i=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:i,children:o})}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:r,children:a})}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[n,"%"]})]})}function wh({row:t}){const s=Yo[t.sourceDimension]??t.sourceDimension,n=Jo[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(xa,{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 Sh({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=t.channelGroup==="Paid Social"?"Paid":"Organic",r=Sn(t.source),o=Sn(t.medium);return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 pr-3 text-strong truncate",title:t.source,children:r}),e.jsx("td",{className:"py-1.5 pr-3 text-muted truncate",title:t.medium,children:o}),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,"%"]})]})}function Ch({sources:t,otherCount:s}){const n=[{key:wn,color:Qo,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const r=t[a];if(r===kn)n.push({key:kn,color:br,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const o=Sn(r);n.push({key:r,color:Os[a%Os.length]??br,label:zo(o,32),tooltip:o})}}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 kh(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 Ah=["7d","30d","90d","all"],sa=500,Ni=[{key:"clicks",label:"Clicks",color:nt[1],format:t=>t.toLocaleString()},{key:"impressions",label:"Impressions",color:nt[4],format:t=>t.toLocaleString()},{key:"ctr",label:"CTR",color:Is.caution,format:t=>`${(t*100).toFixed(1)}%`},{key:"position",label:"Avg position",color:nt[2],inverted:!0,format:t=>t.toFixed(1)}],Es=25,Ph="canonry:google-oauth-complete",Rh=new Intl.NumberFormat(void 0,{maximumFractionDigits:1});function Ih(t,s,n){if(!t)return"no comparison period";const a=t.days;if(!t.comparable)return"property-level comparison unavailable";const r=t.change[s];if(r===null||!Number.isFinite(r)){const u=t.prior[s],h=t.trailing[s];return u!==null&&h!==null&&u<=0&&h>0?`new in the last ${a}d`:u===null||u<=0?`no prior ${a}d to compare`:h===null?`no value in the last ${a}d`:"comparison unavailable"}if(r===0)return`→ no change vs prior ${a}d`;const o=Math.abs(r*100),i=o<.1?"<0.1%":`${Rh.format(o)}%`;return`${(n?r<0:r>0)?"↑":"↓"} ${i} vs prior ${a}d`}function $h(t){if(!t)return"Tile percentages compare the selected window with the equal-length period before it.";const{days:s,basis:n,prior:a,trailing:r}=t,o=s===1?"day":"days",i=`${a.startDate} to ${a.endDate}`,c=`${r.startDate} to ${r.endDate}`,u=`Tile percentages compare these ${s} ${o} (${c}) with the ${s} ${o} before them (${i}).`;return n!=="split-window"?u:`${u} That is the trailing half of the selected window against its own earlier half: there is no equal-length period before the window with synced data to compare it against.`}function wi(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function Si(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 Ci(t){return t.isPending?"Processing":Number(t.errors??0)>0?"Errors":Number(t.warnings??0)>0?"Warnings":"Success"}function Th({projectName:t,refreshNonce:s}){const n=js(),[a,r]=l.useState(!1),[o,i]=l.useState([]),[c,u]=l.useState([]),[h,m]=l.useState([]),[x,g]=l.useState(null),[d,f]=l.useState([]),[y,j]=l.useState([]),[N,P]=l.useState(null),[M,k]=l.useState(""),[p,v]=l.useState(""),[S,$]=l.useState("30"),[q,L]=l.useState(!1),[Q,w]=l.useState("30d"),[X,C]=l.useState(["clicks","impressions"]),[F,_]=l.useState(!0),[D,Z]=l.useState(null),[oe,ne]=l.useState(0),[U,T]=l.useState({startDate:"",endDate:"",query:"",page:""}),[G,ae]=l.useState(0),[W,J]=l.useState(!1),[ge,z]=l.useState(0),[re,ue]=l.useState(!1),[Oe,Fe]=l.useState(""),[Pe,tt]=l.useState(!0),[it,ke]=l.useState(!1),[Xe,_e]=l.useState(!1),[Ve,He]=l.useState(!1),[Te,B]=l.useState(!1),[O,V]=l.useState(!1),[Ne,Ie]=l.useState(!1),[ee,We]=l.useState(null),[ht,Ze]=l.useState(!1),[ye,Ge]=l.useState(!1),[It,xt]=l.useState(null),[Ee,Ye]=l.useState(null),[pt,St]=l.useState([]),[Ke,Le]=l.useState(new Set),[et,Ue]=l.useState({}),[Be,$t]=l.useState(new Set),[vt,Ft]=l.useState(""),[gt,Y]=l.useState(null),[Re,be]=l.useState(""),[je,Gt]=l.useState(!1),[ze,ft]=l.useState(!1),[Tt,ls]=l.useState(!1),[Mt,Kt]=l.useState(!1),[ot,cs]=l.useState("indexed"),[Ct,Ts]=l.useState(null),zt=!!(U.query.trim()||U.page.trim()||Ct),Xt=Ct!==null,Qt=l.useMemo(()=>{if(!Ct)return h;const{key:b,dir:K}=Ct;return[...h].sort((de,pe)=>{const Qe=b===un.CTR?Number.isFinite(de.ctr)?de.ctr:0:de[b],Je=b===un.CTR?Number.isFinite(pe.ctr)?pe.ctr:0:pe[b];return K==="asc"?Qe-Je:Je-Qe})},[h,Ct]),dt=xn({rows:Qt,pageSize:Ss}),Ns=re?dt.rows:Qt,Ht=xn({rows:(It??[]).filter(b=>b.path.toLowerCase().includes(vt.trim().toLowerCase())),pageSize:Ss}),[ct,hs]=l.useState([]),[jt,Zt]=l.useState(null),[xs,ps]=l.useState(1),Lt=l.useMemo(()=>{if(ct.length<2)return null;const b=ct[ct.length-1],K=ct[ct.length-2];return{indexed:b.indexed-K.indexed,notIndexed:b.notIndexed-K.notIndexed}},[ct]);l.useEffect(()=>{ps(1)},[ee,ot,jt]);const E=l.useMemo(()=>jt?(ee?.reasonGroups??[]).find(b=>b.reason===jt):void 0,[ee,jt]),se=l.useMemo(()=>ee?ot==="indexed"?ee.indexed:ot==="deindexed"?ee.deindexed:ot==="notIndexed"?jt?E?.urls??[]:(ee.reasonGroups??[]).length===0?ee.notIndexed:[]:[]:[],[ee,ot,jt,E]),fe=Math.max(1,Math.ceil(se.length/Es)),ie=Math.min(Math.max(1,xs),fe),le=(ie-1)*Es,$e=l.useMemo(()=>ee?.indexed.slice(le,le+Es)??[],[ee,le]),Wt=l.useMemo(()=>ee?.notIndexed.slice(le,le+Es)??[],[ee,le]),yt=l.useMemo(()=>ee?.deindexed.slice(le,le+Es)??[],[ee,le]),gs=l.useMemo(()=>(E?.urls??[]).slice(le,le+Es),[E,le]),[R,me]=l.useState(!1),[st,Ae]=l.useState(null),[ut,ds]=l.useState(null),[_t,Yt]=l.useState(null);function $a(b,K){const de=pm(b),pe=kh(de);pe?(ds(pe),Ae(null)):(ds(null),Ae(de.message||K))}const kt=o.find(b=>b.connectionType==="gsc"),ws=(kt?.scopes??[]).includes("https://www.googleapis.com/auth/webmasters"),gn=pt.length>0?pt:(It??[]).map(b=>b.path),Pn=gn.filter(b=>It?.some(K=>K.path===b&&K.isSitemapsIndex)).length,Jt=Pn===1?"Resubmit sitemap index":Pn>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",Ta=h.length>0||d.length>0||y.length>0,Rn=Vl(),In=zl();async function Jn(b,K=!1){if(!b){u([]),k("");return}_e(!0);try{const{sites:de}=await n.fetchQuery({...ic({client:H,path:{name:t}}),staleTime:K?0:Dt});u(de),k(b.propertyId??de[0]?.siteUrl??""),ds(null)}catch(de){u([]),$a(de,"Failed to load Search Console properties")}finally{_e(!1)}}async function en(b){B(!0);const K=b??G;try{const de=zt?sa:Ss,pe=zt?0:K,Qe={limit:String(de)};U.startDate&&(Qe.startDate=U.startDate),U.endDate&&(Qe.endDate=U.endDate),U.query&&(Qe.query=U.query),U.page&&(Qe.page=U.page),pe>0&&(Qe.offset=String(pe)),Q&&Q!=="all"&&!U.startDate&&(Qe.window=Q);const Je=await n.fetchQuery({...Wl({client:H,path:{name:t},query:Qe}),staleTime:Dt}),at=Je.rows;zt?(J(!1),m(at),z(at.length),ue(!0)):(J(pe+at.length<Je.totalMatching),m(at),z(0),ue(!1))}catch(de){m([]),J(!1),z(0),Ae(de instanceof Error?de.message:"Failed to load GSC performance data")}finally{B(!1)}}async function I(){try{const b={};U.startDate&&(b.startDate=U.startDate),U.endDate&&(b.endDate=U.endDate),Q&&Q!=="all"&&!U.startDate&&(b.window=Q);const K=await n.fetchQuery({...Hl({client:H,path:{name:t},query:b}),staleTime:Dt});g(K)}catch{g(null)}}async function he(b=!1){V(!0);try{const K=Oe.trim()||void 0,de={limit:"20"};K&&(de.url=K);const[pe,Qe]=await Promise.all([n.fetchQuery({...ac({client:H,path:{name:t},query:de}),staleTime:b?0:Dt}),n.fetchQuery({...rc({client:H,path:{name:t}}),staleTime:b?0:Dt})]);f(pe),j(Qe)}catch(K){f([]),j([]),Ae(K instanceof Error?K.message:"Failed to load GSC inspection history")}finally{V(!1)}}async function Ce(b=!1){Ze(!0);try{const[K,de]=await Promise.all([n.fetchQuery({...Xl({client:H,path:{name:t}}),staleTime:b?0:Dt}),n.fetchQuery({...Zl({client:H,path:{name:t}}),staleTime:b?0:Dt}).catch(()=>[])]);We(K),hs(de)}catch(K){We(null),hs([]),Ae(K instanceof Error?K.message:"Failed to load coverage data")}finally{Ze(!1)}}async function Ut(b){me(!0),Ae(null);try{const K=await Zr(t,{urls:b}),{succeeded:de,failed:pe,total:Qe}=K.summary;Se({title:"Indexing requested",detail:pe===0?`${de} URL${de!==1?"s":""} submitted for indexing.`:`${de}/${Qe} submitted successfully, ${pe} failed.`,tone:pe===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(K){Ae(K instanceof Error?K.message:"Failed to request indexing")}finally{me(!1)}}async function fs(){me(!0),Ae(null);try{const b=await Zr(t,{urls:[],allUnindexed:!0}),{succeeded:K,failed:de,total:pe}=b.summary;Se({title:"Indexing requested",detail:de===0?`${K} unindexed URL${K!==1?"s":""} submitted for indexing.`:`${K}/${pe} submitted successfully, ${de} failed.`,tone:de===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(b){Ae(b instanceof Error?b.message:"Failed to request indexing")}finally{me(!1)}}async function Ma(){Ge(!0),Ae(null);try{const b=await Ea(t);n.setQueryData(ec({client:H,path:{name:t}}),b),xt(b.sitemaps),Ye(b.summary),St(b.preferredSubmissionUrls),Le(new Set),Ue({}),b.sitemaps.length===0&&Yt("No sitemaps found in this GSC property. Submit one here to start Google processing it.")}catch(b){Ae(b instanceof Error?b.message:"Failed to list sitemaps")}finally{Ge(!1)}}async function Sl(b){const K=Ke.has(b);if(Le(de=>{const pe=new Set(de);return K?pe.delete(b):pe.add(b),pe}),!(K||et[b])){$t(de=>new Set(de).add(b));try{const de=await Ea(t,b);Ue(pe=>({...pe,[b]:de.sitemaps}))}catch(de){Ae(de instanceof Error?de.message:"Failed to load sitemap files")}finally{$t(de=>{const pe=new Set(de);return pe.delete(b),pe})}}}async function fn(b){if(!ws||b.length===0)return;const K=[...new Set(b)];ft(!0),Ae(null),Y({completed:0,total:K.length});let de=0,pe=0,Qe=0,Je=null;try{for(let wt=0;wt<K.length;wt+=50){const rt=K.slice(wt,wt+50);try{const ve=await tc(t,rt);de+=ve.summary.accepted,pe+=ve.summary.failed,Qe+=rt.length,Y({completed:Qe,total:K.length})}catch(ve){Qe+=rt.length;const Ms=rt.length,$n=K.length-Qe,Xn=ve instanceof Error?ve.message:"The batch request failed",Ls=`${de} accepted, ${pe} failed, ${Ms} unconfirmed, ${$n} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;Je=`Sitemap submission stopped after a batch request failed. ${Ls} ${Xn}`,Ae(Je),Se({title:"Sitemap resubmission partially completed",detail:Ls,tone:"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"});return}}const at=K.length;Se({title:pe===0?"Sitemap submitted to Google":"Some sitemap submissions need attention",detail:pe===0?"Google accepted the sitemap submission/refetch request; indexing is not guaranteed.":`Google accepted ${de}/${at} sitemap submissions; ${pe} failed. Indexing is not guaranteed.`,tone:pe===0?"positive":"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"}),be("")}catch(at){Ae(at instanceof Error?at.message:"Failed to submit sitemap to Google")}finally{ft(!1),Y(null),await Ma(),Je&&Ae(Je)}}async function Cl(){ft(!0);const b=It??[];try{const K=b.filter(pe=>pe.isSitemapsIndex),de=[];for(let pe=0;pe<K.length;pe+=4)(await Promise.all(K.slice(pe,pe+4).map(async Je=>{const at=et[Je.path];if(at)return at;const wt=await Ea(t,Je.path);return Ue(rt=>({...rt,[Je.path]:wt.sitemaps})),wt.sitemaps}))).forEach((Je,at)=>{de.push(...Je.length>0?Je.map(wt=>wt.path):[K[pe+at].path])});await fn([...b.filter(pe=>!pe.isSitemapsIndex).map(pe=>pe.path),...de])}catch(K){Ae(K instanceof Error?K.message:"Failed to load sitemap files"),ft(!1)}}async function Vr(b){Gt(!0),Ae(null);try{await sc(t,"gsc",b),await Nt(n,"google"),i(K=>K.map(de=>de.connectionType==="gsc"?{...de,sitemapUrl:b}:de)),Se({title:"Default sitemap updated",detail:b,tone:"positive",dedupeKey:`gsc:sitemap-default:${t}`,dedupeMode:"replace"})}catch(K){Ae(K instanceof Error?K.message:"Failed to set the default sitemap")}finally{Gt(!1)}}async function zr(b){try{await In.mutateAsync({projectName:t,projectLabel:t,opts:b?{sitemapUrl:b}:void 0})}catch{}}async function Qr(){tt(!0),Ae(null);try{const[b,K]=await Promise.all([wo().catch(()=>null),n.fetchQuery({...Ir({client:H,path:{name:t}}),staleTime:Dt}).catch(()=>[])]);r(!!b?.google?.configured),i(K);const de=K.find(pe=>pe.connectionType==="gsc");await Promise.all([Jn(de),en(),I(),he(),Ce(),de?.propertyId?Ma():Promise.resolve()])}finally{tt(!1)}}l.useEffect(()=>{Qr()},[t,s]),l.useEffect(()=>{ae(0),Z(null),T(b=>b.startDate||b.endDate?{...b,startDate:"",endDate:""}:b),ne(b=>b+1),I()},[Q]);const Hr=l.useRef(!1);l.useEffect(()=>{if(!Hr.current){Hr.current=!0;return}ae(0),dt.setPage(1),en(0)},[oe]);function La(b){const K=D===b?null:b;Z(K),T(de=>({...de,startDate:K??"",endDate:K??""})),ne(de=>de+1)}const Wr=l.useRef(!1);l.useEffect(()=>{if(!Wr.current){Wr.current=!0;return}ae(0),en(0)},[Xt]);async function Yr(){if(!a){Ae("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}ke(!0),Ae(null),Yt(null);try{let b=function(ve){if(ve.source!==pe||ve.origin!==Qe||!ve.data||typeof ve.data!="object")return;const Ms=ve.data;Ms.type!==Ph||Ms.connectionType!=="gsc"||rt(!0)};const{authUrl:K,redirectUri:de}=await Jl(t,"gsc");if(!K.startsWith("https://accounts.google.com/")){Ae("Unexpected OAuth redirect URL. Please try again.");return}const pe=window.open(K,"_blank","width=600,height=700");if(!pe){window.location.assign(K);return}const Qe=de?new URL(de).origin:window.location.origin;let Je=!1,at=null;const wt=()=>{at!==null&&window.clearInterval(at),window.removeEventListener("message",b)},rt=async ve=>{if(!Je){Je=!0,wt(),Yt(ve?"Google connected. Refreshing access…":"Refreshing Google connection…");try{await Nt(n,"google"),await Qr()}finally{Yt(null)}}};window.addEventListener("message",b),Yt("Finish the Google consent flow in the popup. This page will refresh automatically."),at=window.setInterval(()=>{pe.closed&&rt(!1)},1e3)}catch(b){Ae(b instanceof Error?b.message:"Failed to start OAuth flow")}finally{ke(!1)}}async function kl(){Ae(null),Yt(null);try{await Yl(t,"gsc"),await Nt(n,"google"),i(b=>b.filter(K=>K.connectionType!=="gsc")),u([]),k("")}catch(b){Ae(b instanceof Error?b.message:"Failed to disconnect")}}async function Al(){if(M){He(!0),Ae(null);try{await oc(t,"gsc",M),await Nt(n,"google"),i(b=>b.map(K=>K.connectionType==="gsc"?{...K,propertyId:M}:K)),Se({title:"GSC property updated",detail:`${t} is now linked to ${M}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(b){Ae(b instanceof Error?b.message:"Failed to save GSC property")}finally{He(!1)}}}async function Pl(){Ae(null),Yt(null);try{await Rn.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(S,10)||void 0,full:q||void 0}}),await Nt(n,"gsc")}catch{}}async function Jr(){if(p.trim()){Ie(!0),Ae(null),Yt(null);try{const b=await nc(t,p.trim());await Nt(n,"gsc"),P(b),v(""),await he()}catch(b){Ae(b instanceof Error?b.message:"Failed to inspect URL")}finally{Ie(!1)}}}return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search Console"}),e.jsx("h2",{children:"Google Search Console"})]})}),ut&&e.jsx("div",{className:"mb-3 rounded-lg border border-caution-800/40 bg-caution-950/20 px-3 py-2.5 text-sm text-caution-200",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-caution-100",children:ut.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:ut.message}),(Ds(ut.enableUrl)||Ds(ut.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[Ds(ut.enableUrl)&&e.jsx("a",{href:Ds(ut.enableUrl),target:"_blank",rel:"noopener noreferrer",className:"font-medium text-caution-100 underline decoration-caution-500/50 underline-offset-2 hover:text-caution-50",children:"Enable Search Console API ↗"}),Ds(ut.indexingApiUrl)&&e.jsx("a",{href:Ds(ut.indexingApiUrl),target:"_blank",rel:"noopener noreferrer",className:"font-medium text-caution-100 underline decoration-caution-500/50 underline-offset-2 hover:text-caution-50",children:"Enable Indexing API ↗"})]})]}),e.jsx("button",{type:"button",className:"text-caution-400 hover:text-caution-200",onClick:()=>ds(null),children:"×"})]})}),st&&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:[st,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>Ae(null),children:"×"})]}),_t&&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:[_t,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>Yt(null),children:"×"})]}),Pe?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[kt?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:kt.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Coverage measured"," ",ee?.lastInspectedAt?Bt(ee.lastInspectedAt):"never"]}),e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:qe(kl),children:"Disconnect"})]}):e.jsxs(xe,{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(ce,{tone:a?"caution":"negative",children:a?"Ready to connect":"App credentials missing"})]}),e.jsxs("div",{className:"mt-3 rounded-lg border border-default bg-surface px-4 py-5",children:[e.jsx("p",{className:"text-sm text-neutral",children:a?"Generate a Google OAuth link for this project and have the client sign in with a Google account that already has access to the correct Search Console property.":"Set Google OAuth client credentials first. Once configured, you can generate a consent link for this project domain."}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[a?e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:it,onClick:qe(Yr),children:it?"Opening…":"Connect Google Search Console"}):e.jsx(A,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(vs,{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."})]})]})]}),(kt||Ta)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs(xe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Performance"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Search performance"}),e.jsx(Me,{text:`${$h(x?.periodComparison)} The optional trend line shows the fitted direction. Click any day to filter the table below to that date. Query and page filters match case-insensitive substrings and run on Apply filters. Filtering and sorting examine up to ${sa.toLocaleString()} matching rows while the table shows ${Ss} per page.`})]}),x?.window?.startDate&&x.window.endDate&&e.jsxs("p",{className:"text-xs text-muted",children:[x.window.startDate," to ",x.window.endDate,(x.window.daysSinceLatestData??0)>0&&` · latest data ${x.window.daysSinceLatestData} day${x.window.daysSinceLatestData===1?"":"s"} ago`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ra,{windows:Ah,value:Q,onChange:b=>{w(b),ae(0),dt.setPage(1)},label:"Search Console time period",formatOption:b=>b==="all"?"All":b}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:Te,onClick:()=>{ae(0),dt.setPage(1),en(0),I()},children:Te?"Loading…":"Apply filters"})]})]}),x&&x.daily.length>0&&(()=>{const{totals:b,daily:K,trends:de,periodComparison:pe}=x,Je=Ni.filter(ve=>X.includes(ve.key)).map(ve=>({dataKey:ve.key,label:ve.label,color:ve.color,axisId:ve.key,inverted:ve.inverted,formatValue:ve.format,trend:F?de?.[ve.key]??null:null})),at=ve=>b[ve]??null,wt=new Map(K.map(ve=>[ve.date,ve])),rt=K.length===0?[]:vm(K[0].date,K[K.length-1].date).map(ve=>wt.get(ve)??{date:ve});return e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:Ni.map(ve=>{const Ms=X.includes(ve.key),$n=at(ve.key),Xn=$n===null;return e.jsxs("button",{type:"button","aria-pressed":Ms,disabled:Xn,className:`rounded-md border px-3 py-2 text-left transition-colors ${Ms?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${Xn?"cursor-not-allowed opacity-50":""}`,onClick:()=>{C(Ls=>Ls.includes(ve.key)?Ls.length===1?Ls:Ls.filter(Rl=>Rl!==ve.key):[...Ls,ve.key])},children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2 w-2 rounded-full",style:{backgroundColor:Ms?ve.color:"transparent",border:`1px solid ${ve.color}`}}),e.jsx("span",{className:"text-xs text-secondary",children:ve.label})]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:$n===null?"—":ve.format($n)}),e.jsx("span",{className:"block text-[11px] tabular-nums text-muted",children:Ih(pe,ve.key,ve.inverted)})]},ve.key)})}),e.jsx("div",{className:"mt-2 flex items-center justify-end",children:e.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5 text-xs text-secondary",children:[e.jsx("input",{type:"checkbox",className:"accent-mono-400",checked:F,onChange:ve=>_(ve.target.checked)}),"Trend line"]})}),e.jsx("div",{className:"mt-1",children:e.jsx(Eo,{data:rt,xKey:"date",series:Je,xTickFormatter:pn,labelFormatter:Ot,onSelectX:La,selectedX:D})}),e.jsx("div",{role:"group","aria-label":"Filter the table to a single day",children:K.map(ve=>e.jsxs("button",{type:"button",className:"sr-only focus:not-sr-only focus:inline-block focus:rounded focus:border focus:border-strong focus:bg-surface-active focus:px-2 focus:py-1 focus:text-xs focus:text-strong","aria-pressed":D===ve.date,onClick:()=>La(ve.date),children:[Ot(ve.date),": ",ve.clicks," clicks, ",ve.impressions," impressions"]},ve.date))}),D&&e.jsxs("div",{className:"mt-1 flex items-center gap-2 text-xs",children:[e.jsxs("span",{className:"text-secondary",children:["Table showing ",Ot(D)]}),e.jsxs("button",{type:"button",className:"text-link hover:underline",onClick:()=>La(D),children:["Show all ",b.days," days"]})]}),b.position!==null&&(b.positionDays??b.days)<b.days&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position covers ",b.positionDays," of ",b.days," days. The rest have no property-level position recorded."]}),(b.position===null||b.position===void 0)&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position needs a property-level sync. Run ",e.jsx("code",{children:"canonry google sync"})," to record it."]})]})})(),e.jsxs("div",{className:"mt-3 grid gap-2 lg:grid-cols-4",children:[e.jsx("input",{className:"rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"date","aria-label":"Start date",title:"Start date (inclusive). Leave blank to use the window above.",value:U.startDate,onChange:b=>T(K=>({...K,startDate:b.target.value}))}),e.jsx("input",{className:"rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"date","aria-label":"End date",title:"End date (inclusive).",value:U.endDate,onChange:b=>T(K=>({...K,endDate:b.target.value}))}),e.jsx(Us,{value:U.query,onChange:b=>T(K=>({...K,query:b})),label:"Filter search queries",placeholder:"Contains query…"}),e.jsx(Us,{value:U.page,onChange:b=>T(K=>({...K,page:b})),label:"Filter page URLs",placeholder:"Contains page URL…"})]}),h.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Date"}),e.jsx("th",{className:"text-left",children:"Query"}),e.jsx("th",{className:"text-left",children:"Page"}),Object.values(un).map(b=>e.jsx("th",{className:"text-right","aria-sort":Ct?.key===b?Ct.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:()=>{dt.setPage(1),Ts(K=>K?.key===b?K.dir==="desc"?{key:b,dir:"asc"}:null:{key:b,dir:"desc"})},children:[Ql[b],Ct?.key===b?Ct.dir==="desc"?" ↓":" ↑":""]})},b))]})}),e.jsx("tbody",{children:Ns.map((b,K)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:b.date}),e.jsx("td",{className:"max-w-xs truncate text-strong",children:b.query}),e.jsx("td",{className:"max-w-xs text-secondary",children:e.jsx(xa,{value:b.page})}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:b.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:b.impressions.toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[(Number.isFinite(b.ctr)?b.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:b.position.toFixed(1)})]},`${b.date}:${b.query}:${b.page}:${K}`))})]})}),e.jsx(Rs,{page:re?dt.page:Math.floor(G/Ss)+1,pageSize:Ss,visibleRows:Ns.length,totalRows:re?ge:void 0,hasNextPage:re?void 0:W,disabled:Te,itemLabel:re?"matches":"rows",onPageChange:b=>{if(re){dt.setPage(b);return}const K=(b-1)*Ss;ae(K),en(K)}}),re&&ge>=sa?e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Results are capped at ",sa.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(xe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Coverage"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Index coverage"}),e.jsx(Me,{text:"Google's Indexing API is intended for eligible JobPosting and BroadcastEvent pages. Sitemap resubmission is the general-site bulk path."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[ee&&ee.notIndexed.length>0&&e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:R,onClick:()=>{fs()},children:R?"Requesting…":`Request indexing (${ee.notIndexed.length})`}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:ht,onClick:()=>{Ce(!0)},children:ht?"Loading…":"Reload saved coverage"})]})]}),ee&&ee.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const b=ee.summary.indexed+ee.summary.notIndexed,K=b>0?ee.summary.indexed/b:0,de=b>0?ee.summary.notIndexed/b:0,pe=54,Qe=2*Math.PI*pe,Je=Qe*(1-K),at=Qe*de,wt=Qe*K;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:pe,fill:"none",stroke:os.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:pe,fill:"none",stroke:Is.positiveDeep,strokeWidth:"14",strokeDasharray:Qe,strokeDashoffset:Je,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),ee.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:pe,fill:"none",stroke:os.textFaint,strokeWidth:"14",strokeDasharray:`${at} ${Qe-at}`,strokeDashoffset:-wt,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:[(K*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:ee.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:ee.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:["Not indexed",(ee.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-faint",children:["· ",(ee.reasonGroups??[]).length," ",(ee.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),ee.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:ee.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(b=>{const K=b==="indexed"?ee.indexed.length:b==="notIndexed"?ee.notIndexed.length:ee.deindexed.length,de=b==="indexed"?"Indexed":b==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",role:"tab","aria-selected":ot===b,className:`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${ot===b?"border-accent text-heading":"border-transparent text-secondary hover:border-mono-600 hover:text-strong"}`,onClick:()=>{cs(b),Zt(null)},children:[de," (",K,")"]},b)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[ot==="indexed"&&ee.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:$e.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.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:b.crawlTime?b.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:b.isMobileFriendly===!0?"Yes":b.isMobileFriendly===!1?"No":"—"})]},b.id))})]}),ot==="notIndexed"&&!jt&&(ee.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:(ee.reasonGroups??[]).map(b=>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:()=>Zt(b.reason),onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),Zt(b.reason))},tabIndex:0,role:"button","aria-label":`View ${b.reason} pages`,children:[e.jsx("td",{className:"text-strong",children:b.reason}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:b.count})]},b.reason))})]}),ot==="notIndexed"&&!jt&&(ee.reasonGroups??[]).length===0&&ee.notIndexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Indexing State"}),e.jsx("th",{className:"text-left",children:"Coverage"})]})}),e.jsx("tbody",{children:Wt.map(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.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:b.coverageState??"Unknown"})]},b.id))})]}),ot==="notIndexed"&&jt&&(()=>{const b=(ee.reasonGroups??[]).find(K=>K.reason===jt);return b?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:()=>Zt(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:b.reason}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[b.count," affected page",b.count!==1?"s":""]})]}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:R,onClick:()=>{Ut(b.urls.map(K=>K.url))},children:R?"Requesting…":`Request indexing (${b.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:gs.map(K=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:K.url}),e.jsx("td",{className:"text-secondary",children:K.crawlTime?K.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-strong transition-colors",disabled:R,onClick:()=>{Ut([K.url])},title:"Request indexing",children:"Index"})})]},K.id))})]})]}):null})(),ot==="deindexed"&&ee.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:yt.map((b,K)=>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.previousState}),e.jsx("td",{className:"text-secondary",children:b.currentState}),e.jsx("td",{className:"text-secondary",children:b.transitionDate.split("T")[0]})]},`${b.url}-${K}`))})]}),(ot==="indexed"&&ee.indexed.length===0||ot==="notIndexed"&&!jt&&ee.notIndexed.length===0||ot==="deindexed"&&ee.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),e.jsx(Rs,{page:ie,pageSize:Es,visibleRows:Math.min(Es,se.length-le),totalRows:se.length,onPageChange:ps,itemLabel:"URLs"})]}),e.jsxs("div",{className:"mt-4 border-t border-default pt-3",children:[e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between text-left text-xs text-secondary hover:text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400","aria-expanded":Mt,onClick:()=>Kt(b=>!b),children:[e.jsx("span",{children:"Coverage history"}),e.jsx("span",{children:Mt?"Hide snapshots":ct.length>0?`View ${ct.length} snapshots`:"View history"})]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["Current: ",ee.summary.indexed.toLocaleString()," indexed, ",ee.summary.notIndexed.toLocaleString()," not indexed.",Lt&&e.jsxs(e.Fragment,{children:[" Since the last snapshot: ",Lt.indexed>=0?"+":"",Lt.indexed.toLocaleString()," indexed, ",Lt.notIndexed>=0?"+":"",Lt.notIndexed.toLocaleString()," not indexed."]})]}),Mt&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:ct.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:ct.map(b=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:b.date}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:b.indexed.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:b.notIndexed.toLocaleString()})]},b.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:ht?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),e.jsxs(xe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Sitemaps"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Sitemap operations"}),e.jsx(Me,{text:"Submitting asks Google to refetch these sitemaps. Indexing is not guaranteed."})]})]}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:ye||!kt?.propertyId,onClick:()=>{Ma()},children:ye?"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:Re,onChange:b=>be(b.target.value),onKeyDown:b=>b.key==="Enter"&&void fn([Re.trim()])}),e.jsx(A,{type:"button",size:"sm",disabled:!ws||ze||!Re.trim(),onClick:()=>{fn([Re.trim()])},children:ze?"Submitting…":"Submit sitemap to Google"})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:!ws||ze||gn.length===0,onClick:()=>{fn(gn)},children:ze?"Resubmitting…":Jt}),e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:!ws||ze||!It?.length,onClick:()=>{Cl()},children:"Resubmit all files"}),Ee&&e.jsxs("span",{className:"text-xs text-muted",children:["Top level: ",Ee.indexes," index",Ee.indexes===1?"":"es",", ",Ee.files," file",Ee.files===1?"":"s"]}),gt&&e.jsxs("span",{className:"text-xs text-secondary",children:["Submitting ",gt.completed,"/",gt.total]})]}),!ws&&kt&&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:qe(Yr),children:"Reconnect"})]}),It&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:It.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Us,{value:vt,onChange:b=>{Ft(b),Ht.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:Ht.rows.flatMap(b=>{const K=wi(b),de=Si(b),pe=Ci(b),Qe=et[b.path]??[],Je=Ke.has(b.path),at=e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs text-strong",children:e.jsx(xa,{value:b.path})}),e.jsx("td",{className:"text-secondary",children:b.isSitemapsIndex?e.jsx("button",{type:"button",className:"text-secondary hover:text-strong","aria-expanded":Je,"aria-label":`${Je?"Collapse":"Expand"} files in ${b.path}`,onClick:()=>{Sl(b.path)},children:Be.has(b.path)?"Loading…":`${Je?"▾":"▸"} Index${et[b.path]?` (${Qe.length})`:""}`}):"Sitemap"}),e.jsx("td",{className:"text-secondary",children:pe}),e.jsx("td",{className:"text-secondary",children:b.lastSubmitted?b.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:b.lastDownloaded?b.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:K.toLocaleString()}),e.jsx("td",{className:"max-w-48 text-secondary",children:de||"—"}),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:!ws||ze,onClick:()=>{fn([b.path])},children:b.lastSubmitted?"Resubmit to Google":"Submit to Google"}),kt?.sitemapUrl===b.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:je,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{Vr(b.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:In.isPending,onClick:()=>{zr(b.path)},children:"Inspect URLs"})]})})]},b.path),wt=b.isSitemapsIndex&&Je?Qe.map(rt=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs pl-6 text-secondary",children:e.jsx(xa,{value:rt.path})}),e.jsx("td",{className:"text-secondary",children:"File"}),e.jsx("td",{className:"text-secondary",children:Ci(rt)}),e.jsx("td",{className:"text-secondary",children:rt.lastSubmitted?rt.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:rt.lastDownloaded?rt.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:wi(rt).toLocaleString()}),e.jsx("td",{className:"text-secondary",children:Si(rt)||"—"}),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:!ws||ze,onClick:()=>{fn([rt.path])},children:"Resubmit"}),kt?.sitemapUrl===rt.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:je,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{Vr(rt.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:In.isPending,onClick:()=>{zr(rt.path)},children:"Inspect URLs"})]})})]},`${b.path}:${rt.path}`)):[];return[at,...wt]})})]}),e.jsx(Rs,{page:Ht.page,pageSize:Ss,visibleRows:Ht.rows.length,totalRows:Ht.totalRows,onPageChange:Ht.setPage,itemLabel:"sitemaps"})]}):e.jsx("p",{className:"text-sm text-muted",children:"No sitemaps found for this property."})})]}),e.jsxs(xe,{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:b=>v(b.target.value),onKeyDown:b=>b.key==="Enter"&&void Jr()}),e.jsx(A,{type:"button",size:"sm",disabled:Ne||!kt?.propertyId||!p.trim(),onClick:qe(Jr),children:Ne?"Inspecting…":"Inspect URL"})]}),N&&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:N.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:N.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:Xr(N.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:Bt(N.crawlTime)})]})]})]}),e.jsxs(xe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Inspection log"})]}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:O,onClick:()=>{he(!0)},children:O?"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:Oe,onChange:b=>Fe(b.target.value)}),e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:O,onClick:()=>{he(!0)},children:"Apply filter"})]}),d.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:d.map(b=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:b.url}),e.jsx("td",{className:"text-neutral",children:b.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:b.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:b.coverageState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:Xr(b.isMobileFriendly??null)}),e.jsx("td",{className:"text-secondary",children:Bt(b.inspectedAt)})]},b.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No inspection history yet."})]}),e.jsxs(xe,{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"})]})}),y.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:y.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.previousState??"Unknown"}),e.jsx("td",{className:"text-neutral",children:b.currentState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:Bt(b.transitionDate)})]},`${b.url}:${b.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No deindexed transitions recorded."})]})]}),kt&&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:()=>ls(b=>!b),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 ${Tt?"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"})]})}),Tt&&e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(xe,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Property"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Pick the Search Console property"}),e.jsx(Me,{text:"The selected property is used for future syncs and URL inspections for this project."})]})]})}),e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:`gsc-property-${t}`,children:"Property URL"}),e.jsx("select",{id:`gsc-property-${t}`,className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none",value:M,disabled:Xe||c.length===0,onChange:b=>k(b.target.value),children:c.length===0?e.jsx("option",{value:"",children:Xe?"Loading properties…":"No properties available"}):c.map(b=>e.jsxs("option",{value:b.siteUrl,children:[b.siteUrl," · ",b.permissionLevel]},b.siteUrl))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:Xe,onClick:()=>{Jn(kt,!0)},children:Xe?"Refreshing…":"Refresh properties"}),e.jsx(A,{type:"button",size:"sm",disabled:!M||Ve,onClick:qe(Al),children:Ve?"Saving…":"Save property"})]})]})]}),e.jsxs(xe,{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:S,onChange:b=>$(b.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:b=>L(b.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(A,{type:"button",size:"sm",disabled:Rn.isPending||!kt.propertyId,onClick:qe(Pl),children:Rn.isPending?"Queueing…":"Queue sync"}),!kt.propertyId&&e.jsx("p",{className:"text-xs text-caution-400",children:"Select a Search Console property before queueing a sync."})]})]})]})})]})]})]})}const Mh=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function Lh({projectName:t,projectId:s}){const n=js(),[a,r]=l.useState(null),[o,i]=l.useState(null),[c,u]=l.useState(!1),h=we(Ir({client:H,path:{name:t}})),m=h.data?.find(z=>z.connectionType==="gbp"),x=!!m,g=a?{locationName:a}:void 0,d=we({...lc({client:H,path:{name:t}}),enabled:x}),f=we({...cc({client:H,path:{name:t},query:g}),enabled:x}),y=we({...dc({client:H,path:{name:t},query:g}),enabled:x}),j=we({...uc({client:H,path:{name:t},query:g}),enabled:x}),N=we({...mc({client:H,path:{name:t},query:g}),enabled:x}),P=we({...hc({client:H,path:{name:t},query:g}),enabled:x}),M=we({queryKey:["gbp-section-insights",t],queryFn:()=>xc(t),enabled:x});function k(){Nt(n,"gbp")}const p=Pt({...pc(),onSuccess:z=>{So({id:z.runId,projectId:s,kind:zs["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),Se({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),v=l.useSyncExternalStore(Co,ba,ba),S=Object.values(v.runs).some(z=>z.kind===zs["gbp-sync"]&&z.projectId===s),$=p.isPending||S,q=Pt({...gc(),onSuccess:()=>k()});if(l.useEffect(()=>{if(!a||!d.data)return;const z=d.data.locations.filter(re=>re.selected);(z.length<=1||!z.some(re=>re.locationName===a))&&r(null)},[a,d.data]),l.useEffect(()=>{if(!o||!d.data)return;(a?[a]:d.data.locations.filter(re=>re.selected).map(re=>re.locationName)).includes(o)||i(null)},[o,d.data,a]),h.isLoading)return null;if(!m){const z=[{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(xe,{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:z.map((re,ue)=>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:ue+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:re.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:re.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:re.note})]})]},re.title))})]})})}const L=f.data,Q=d.data?.locations??[],w=Q.filter(z=>z.selected),X=y.data?.keywords??[],C=j.data?.lodging??[],F=N.data?.placeActions??[],_=P.data?.places??[],D=Q.length>0?Q[0].accountName:m.domain,Z=a?Q.find(z=>z.locationName===a)?.displayName??null:null,oe=a?Q.filter(z=>z.locationName===a):w,ne=new Set(oe.map(z=>z.locationName)),U=C.filter(z=>ne.has(z.locationName)),T=F.filter(z=>ne.has(z.locationName)),G=_.filter(z=>ne.has(z.locationName)),ae=new Set(w.map(z=>z.locationName)),W=a?X:X.filter(z=>ae.has(z.locationName)),J=!a&&w.length>1,ge=(M.data??[]).filter(z=>!z.dismissed&&Mh.has(z.type)&&(!Z||z.query===Z||z.query===a||z.title.startsWith(Z)));return e.jsx("section",{className:"page-section-divider",children:e.jsxs(xe,{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(Me,{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(ce,{tone:"positive",children:"Connected"}),!te()&&e.jsx(De,{type:"button",variant:"outline",size:"sm",disabled:$,onClick:()=>p.mutate({client:H,path:{name:t},body:{}}),children:$?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-muted",children:[D?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-secondary",children:D})," · "]}):null,d.data?`${d.data.totalSelected} of ${d.data.totalDiscovered} locations tracked`:"Loading locations…"]}),w.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:z=>r(z.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"}),w.map(z=>e.jsx("option",{value:z.locationName,children:z.displayName},z.id))]})]}),w.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:[ge.length>0&&e.jsxs("div",{className:"mb-6 grid gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Needs attention"}),ge.map(z=>e.jsx("div",{className:["insight-card",Qh(z.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:[z.title,z.recommendation?.reason&&e.jsx(Me,{text:z.recommendation.reason})]})},z.id))]}),L&&e.jsx(Jh,{performance:L.performance,freshness:L.freshness,timeseries:L.timeseries}),L?.profileCompleteness&&e.jsx(Eh,{summary:L.profileCompleteness}),oe.length>0&&e.jsx(qh,{locations:oe,lodging:U,places:G,placeActions:T,expandedLocation:o,onToggleExpanded:z=>{i(re=>re===z?null:z)}}),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"}),y.data&&y.data.total>0&&e.jsxs("span",{className:"text-[11px] text-faint",children:[y.data.thresholdedPct,"% privacy-thresholded"]})]}),W.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"}),J&&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:W.slice(0,25).map(z=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-neutral",children:z.keyword}),J&&e.jsx("td",{className:"text-muted",children:Q.find(re=>re.locationName===z.locationName)?.displayName??z.locationName}),e.jsx("td",{className:"text-right font-mono text-strong",children:z.valueCount!==null?z.valueCount.toLocaleString():e.jsxs("span",{className:"text-muted",title:"Privacy floor — Google withheld the exact count",children:["<",z.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-faint",children:[z.periodStart,"–",z.periodEnd]})]},`${z.locationName}:${z.keyword}`))})]})]})]}),e.jsxs("div",{className:"mt-6 border-t border-default pt-4",children:[e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 text-xs font-medium text-secondary hover:text-strong",onClick:()=>u(z=>!z),"aria-expanded":c,children:[e.jsx("span",{"aria-hidden":"true",children:c?"▾":"▸"})," Manage locations (",Q.length,")"]}),c&&e.jsx("div",{className:"mt-3",children:Q.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"}),!te()&&e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:Q.map(z=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:z.displayName}),e.jsx("td",{className:"text-muted",children:z.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(ce,{tone:z.selected?"positive":"neutral",children:z.selected?"Tracked":"Not tracked"})}),!te()&&e.jsx("td",{className:"text-right",children:e.jsx(De,{type:"button",variant:"outline",size:"sm",disabled:q.isPending,onClick:()=>q.mutate({client:H,path:{name:t,locationName:z.locationName},body:{selected:!z.selected}}),children:z.selected?"Untrack":"Track"})})]},z.id))})]})})]})]})})}function Eh({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:Mn(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:Mn(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:Mn(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:Mn(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:Mn(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(Me,{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 ${zh(a.tone)}`,children:a.value}),a.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-faint",children:a.detail})]},a.label))})]})}function qh({locations:t,lodging:s,places:n,placeActions:a,expandedLocation:r,onToggleExpanded:o}){const i=new Map(s.map(h=>[h.locationName,h])),c=new Map(n.map(h=>[h.locationName,h])),u=new Map;for(const h of a){const m=u.get(h.locationName)??[];m.push(h),u.set(h.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(Me,{text:te()?"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest sync, not that every Google product lacks the information.":"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest Canonry sync, not that every Google product lacks the information."})]}),e.jsxs("span",{className:"text-[11px] text-faint",children:[t.length," location",t.length===1?"":"s"]})]}),e.jsx("div",{className:"data-table-wrapper",children:e.jsxs("table",{className:"data-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"min-w-[14rem]",children:"Location"}),e.jsx("th",{className:"min-w-[15rem]",children:"Owner profile"}),e.jsx("th",{className:"min-w-[11rem]",children:"Hotel data"}),e.jsx("th",{className:"min-w-[11rem]",children:"Public Maps"}),e.jsx("th",{className:"min-w-[10rem]",children:"CTAs"}),e.jsx("th",{className:"text-right",children:"Detail"})]})}),e.jsx("tbody",{children:t.map(h=>{const m=i.get(h.locationName)??null,x=c.get(h.locationName)??null,g=u.get(h.locationName)??[],d=r===h.locationName;return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-strong",children:h.displayName}),e.jsx("p",{className:"mt-1 text-xs text-faint",children:h.primaryCategoryDisplayName??"Primary category not returned"}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[e.jsx(ce,{tone:h.selected?"positive":"neutral",children:h.selected?"Tracked":"Not tracked"}),h.openStatus&&h.openStatus!=="OPEN"&&e.jsx(ce,{tone:h.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:Xo(h.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(Oh,{location:h})}),e.jsx("td",{children:e.jsx(Fh,{lodging:m})}),e.jsx("td",{children:e.jsx(Kh,{place:x,mapsUri:h.mapsUri})}),e.jsx("td",{children:e.jsx(Uh,{actions:g})}),e.jsx("td",{className:"text-right",children:e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>o(h.locationName),children:d?"Hide":"Details"})})]}),d&&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(Vh,{location:h,lodging:m,place:x,placeActions:g})})})]},h.id)})})]})})]})}function Dh(t){return[{label:"Description",tone:ln(t.description)?"positive":"neutral",value:ln(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:ln(t.primaryPhone)?"positive":"neutral",value:ln(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:ln(t.websiteUri)?"positive":"neutral",value:ln(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 Oh({location:t}){const s=Dh(t);return e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>e.jsxs(ce,{tone:n.tone,children:[n.label," ",n.value]},n.label))})}function Fh({lodging:t}){return e.jsx($r,{...Gh(t)})}function Gh(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 Kh({place:t,mapsUri:s}){return e.jsx($r,{..._h(t,s)})}function _h(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 Uh({actions:t}){return e.jsx($r,{...Bh(t)})}function Bh(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 $r({tone:t,label:s,detail:n}){return e.jsxs("div",{children:[e.jsx(ce,{tone:t,children:s}),e.jsx("p",{className:"mt-1.5 text-xs leading-5 text-faint",children:n})]})}function Vh({location:t,lodging:s,place:n,placeActions:a}){const r=s?Wh(s.attributes):[];return e.jsxs("div",{className:"grid gap-5 text-xs lg:grid-cols-3",children:[e.jsxs(za,{title:"Owner profile · Business Information",children:[e.jsx(Et,{label:"Primary category",value:t.primaryCategoryDisplayName??"Not returned"}),e.jsx(Et,{label:"Secondary categories",value:t.additionalCategories.length>0?t.additionalCategories.join(", "):"Not returned"}),e.jsx(Et,{label:"Description",value:ln(t.description)?t.description:"Not returned"}),e.jsx(Et,{label:"Hours",value:t.regularHours?"Returned by Google":"Not returned"}),e.jsx(Et,{label:"Service area",value:t.serviceArea?"Returned by Google":"Not returned"}),e.jsx(Et,{label:"Phone",value:t.primaryPhone??"Not returned"}),e.jsx(Et,{label:"Website",value:t.websiteUri??"Not returned"}),e.jsx(Et,{label:"Open status",value:Xo(t.openStatus)}),e.jsx(Et,{label:"Opening date",value:t.openingDate??"Not returned"})]}),e.jsx(za,{title:"Hotel data · Lodging API",children:s?e.jsxs(e.Fragment,{children:[e.jsx(Et,{label:"Last checked",value:ki(s.syncedAt)}),e.jsx(Et,{label:"Groups returned",value:String(s.populatedGroupCount)}),e.jsx(Et,{label:"Populated groups",value:r.length>0?r.join(", "):"None returned"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Lodging API snapshot was stored for this location."})}),e.jsxs(za,{title:"Public listing + CTAs",children:[n?e.jsxs(e.Fragment,{children:[e.jsx(Et,{label:"Places tier",value:n.tier}),e.jsx(Et,{label:"Last checked",value:ki(n.syncedAt)}),e.jsx(Et,{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(o=>e.jsxs("div",{className:"grid gap-0.5",children:[e.jsxs("span",{className:"font-medium text-neutral",children:[Sa(o.placeActionType),o.isPreferred?" · preferred":""]}),e.jsxs("span",{className:"text-faint",children:[Sa(o.providerType),o.uri?` · ${Hh(o.uri)}`:""]})]},o.placeActionLinkName))})})]})]})}function za({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 Et({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 Mn(t,s,n){return t===s?"positive":t===0?n:"caution"}function zh(t){switch(t){case"positive":return"text-positive";case"caution":return"text-caution";case"negative":return"text-negative";case"neutral":return"text-neutral"}}function Qh(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function ln(t){return typeof t=="string"&&t.trim().length>0}function Xo(t){return t?Sa(t):"Not returned"}function Sa(t){return t?t.toLowerCase().split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"Unknown"}function Hh(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function ki(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Wh(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&Yh(n)).map(([s])=>Sa(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function Yh(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function Jh({performance:t,freshness:s,timeseries:n}){const a=t.totals,r=fc.filter(f=>(a[f]??0)>0),o=yc.filter(f=>(a[f]??0)>0),i=Object.keys(a).filter(f=>(a[f]??0)>0&&bc(f)==="other").sort((f,y)=>(a[y]??0)-(a[f]??0)),c=Object.keys(a).filter(f=>(a[f]??0)===0).sort(),u=n.map(f=>{const y={date:f.date};for(const[j,N]of Object.entries(f.metrics))y[j]=N;return y}),h=n.find(f=>f.pending)?.date,m=n.length>0?n[n.length-1].date:void 0,x=u.length>0,g=s.dataThroughDate?`Data through ${Ot(s.dataThroughDate)}${s.pendingDays>0?` · ${s.pendingDays}d pending`:""}`:null,d=[...r,...i];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"}),g&&e.jsx("span",{className:"text-[11px] text-muted",children:g})]}),!x||r.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No profile action activity yet — run a sync."}):e.jsxs(e.Fragment,{children:[e.jsx(Ai,{data:u,metrics:r,kind:"line",firstPending:h,lastDate:m}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-x-5 gap-y-1",children:d.map(f=>e.jsxs("span",{className:"text-sm text-secondary",children:[va(f)," ",e.jsx("span",{className:"font-mono text-heading",children:(a[f]??0).toLocaleString()})]},f))})]})]}),x&&o.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(Ai,{data:u,metrics:o,kind:"area",firstPending:h,lastDate:m})]}),c.length>0&&e.jsxs("p",{className:"text-xs text-faint",children:["Not active: ",c.map(f=>va(f)).join(", ")]})]})}function Ai({data:t,metrics:s,kind:n,firstPending:a,lastDate:r}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(Ws,{width:"100%",height:"100%",children:e.jsxs(Ys,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Vn,{stroke:Bn,vertical:!1}),e.jsx(Js,{dataKey:"date",tick:Rt,tickLine:!1,axisLine:{stroke:is},tickFormatter:pn,minTickGap:24}),e.jsx(Xs,{tick:Rt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Zs,{...as,labelFormatter:Ot,formatter:(o,i)=>[typeof o=="number"?o.toLocaleString():String(o??0),va(String(i??""))]}),e.jsx(wa,{wrapperStyle:{fontSize:11,color:os.text},formatter:o=>va(o)}),a&&r&&e.jsx(xr,{x1:a,x2:r,fill:os.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:os.textDim,fontSize:10}}),s.map((o,i)=>n==="line"?e.jsx(As,{type:"monotone",dataKey:o,stroke:nt[i%nt.length],strokeWidth:2,dot:!1,isAnimationActive:!1},o):e.jsx(Fs,{type:"monotone",dataKey:o,stackId:"reach",stroke:nt[i%nt.length],fill:nt[i%nt.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},o))]})})})}function Xh(t){return qo($s(String(t)))}function Zh(t){return Bs($s(String(t)))}function Qa({children:t,label:s="More info",placement:n="top",className:a}){const r=l.useId(),[o,i]=l.useState(!1);return e.jsxs("span",{className:`relative inline-flex ${a??""}`,children:[e.jsx("button",{type:"button","aria-label":s,"aria-describedby":o?r:void 0,className:"inline-flex h-4 w-4 items-center justify-center rounded-full text-muted hover:text-strong focus:text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),onFocus:()=>i(!0),onBlur:()=>i(!1),children:e.jsx(nm,{className:"h-3.5 w-3.5","aria-hidden":!0})}),o&&e.jsx("span",{id:r,role:"tooltip",className:`absolute z-50 w-64 rounded border border-strong bg-bg-elevated px-3 py-2 text-xs font-normal leading-relaxed text-strong shadow-lg ${n==="top"?"bottom-full mb-2":"top-full mt-2"} left-1/2 -translate-x-1/2 whitespace-normal`,children:t})]})}const na=Ss;function yn(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function Ha(t){return t.toLocaleString()}function ex(t){const s=Number(t);return Number.isFinite(s)?`${(s*100).toFixed(1)}%`:"—"}function tx(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 sx(t){const s=t.filter(n=>n.kind===zs["backlink-extract"]&&!ko(n.status));return s.length===0?null:s.reduce((n,a)=>n.createdAt>a.createdAt?n:a)}function nx(t,s){const n=new Date(t??s).getTime(),a=Math.max(0,Math.floor((Date.now()-n)/1e3));if(a<60)return`${a}s`;const r=Math.floor(a/60),o=a%60;return o===0?`${r}m`:`${r}m ${o}s`}function ax({projectName:t}){const[s,n]=l.useState(null),[a,r]=l.useState(null),[o,i]=l.useState([]),[c,u]=l.useState(null),[h,m]=l.useState(null),[x,g]=l.useState(null),[d,f]=l.useState(Date.now()),[y,j]=l.useState(0),[N,P]=l.useState(!0),[M,k]=l.useState(!1),[p,v]=l.useState(null),S=l.useCallback(async()=>{P(!0),v(null);try{const[D,Z,oe,ne,U]=await Promise.all([vc().catch(()=>null),jc(t,{excludeCrawlers:!0}).catch(()=>null),Nc(t,{limit:na,offset:y,excludeCrawlers:!0}).catch(G=>{if(G instanceof hn&&G.code==="NOT_FOUND")return null;throw G}),wc(t).catch(()=>[]),Sc(t).catch(()=>[])]);u(D),n(Z),r(oe),i(ne);const T=sx(U);m(T)}catch(D){v(D instanceof Error?D.message:"Failed to load backlinks")}finally{P(!1)}},[t,y]);l.useEffect(()=>{S()},[S]),l.useEffect(()=>{if(!h)return;const D=h.id;let Z=!1;const oe=async()=>{try{const U=await hr(D);if(Z)return;ko(U.status)?(m(null),g(U),await S()):m(T=>T?.id===U.id?{...T,...U}:T)}catch{}},ne=window.setInterval(()=>{oe()},3e3);return()=>{Z=!0,window.clearInterval(ne)}},[h,S]),l.useEffect(()=>{if(!h)return;const D=window.setInterval(()=>f(Date.now()),1e3);return()=>window.clearInterval(D)},[h]),l.useEffect(()=>{if(!x||x.status==="failed")return;const D=window.setTimeout(()=>g(null),1e4);return()=>window.clearTimeout(D)},[x]);async function $(){k(!0),v(null);try{const D=await kc(t);m(D)}catch(D){D instanceof hn&&D.code==="MISSING_DEPENDENCY"?v("DuckDB is not installed. Visit the Backlinks admin page to install it."):v(D instanceof Error?D.message:"Failed to trigger extract")}finally{k(!1)}}const q=l.useMemo(()=>o.slice().sort((D,Z)=>D.queriedAt.localeCompare(Z.queriedAt)).map(D=>({date:D.queriedAt,linkingDomains:D.totalLinkingDomains})),[o]),L=a?.rows??[],Q=a?.total??0,w=s?.excludedLinkingDomains??0,X=Math.floor(y/na)+1;return l.useEffect(()=>{y>0&&y>=Q&&j(0)},[y,Q]),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(xe,{className:"surface-card p-4 mb-4 border-negative-800/60",children:e.jsx("p",{className:"text-sm text-negative",children:p})}),h&&e.jsx(xe,{className:"surface-card p-4 mb-4 border-info-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(em,{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(ce,{tone:"neutral",children:h.status}),e.jsxs("span",{className:"text-sm text-secondary tabular-nums",children:[nx(h.startedAt??null,h.createdAt)," elapsed · refreshing every 3s"]}),e.jsxs("span",{className:"sr-only",children:["now=",d]})]}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Refreshing this project from the current Common Crawl release."})]})]})}),x&&!h&&e.jsx(xe,{className:`surface-card p-4 mb-4 ${x.status==="failed"?"border-negative-800/60":"border-positive-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[x.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(tm,{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 ${x.status==="failed"?"text-negative":"text-positive"}`,children:x.status==="failed"?"Extract failed":"Extract complete"}),x.error?e.jsx("p",{className:"text-sm text-secondary mt-1",children:Cc(x.error)}):x.status!=="failed"?e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),C()]});function C(){return N?e.jsx(xe,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading backlinks…"})}):F()}function F(){const D=s!==null&&s.totalLinkingDomains>0,Z=x?.status==="failed",oe=s!==null&&s.totalLinkingDomains===0&&!Z,ne=c?.status==="ready",U=c?.status==="failed",T=c&&(c.status==="downloading"||c.status==="querying"||c.status==="queued");return D?_(e.jsxs(e.Fragment,{children:[!te()&&e.jsxs(e.Fragment,{children:[e.jsxs(A,{type:"button",variant:"outline",size:"sm",disabled:M||h!==null,onClick:qe($),children:[e.jsx(To,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":M?"Queuing…":"Re-run extract"]}),e.jsx(Qa,{label:"About re-running",children:"Re-queries the current release for this project without downloading it again."})]}),!te()&&e.jsx(A,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:yn("/backlinks"),children:"Open admin"})})]})):e.jsx(xe,{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(sm,{className:"h-5 w-5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1",children:[!c&&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."}),!te()&&e.jsx("div",{className:"mt-4",children:e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:yn("/backlinks"),children:"Set up backlinks"})})})]}),T&&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 (",c.status,c.phaseDetail?` — ${c.phaseDetail}`:"","). Backlinks will appear here once it finishes."]}),!te()&&e.jsx("div",{className:"mt-4",children:e.jsx(A,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:yn("/backlinks"),children:"View sync status"})})})]}),U&&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:c.error??"The workspace release sync failed. Retry from the Backlinks admin page."}),!te()&&e.jsx("div",{className:"mt-4",children:e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:yn("/backlinks"),children:"Go to Backlinks admin"})})})]}),ne&&!T&&!oe&&!Z&&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:c.release})," is ready. Run an extract for this project."]}),!te()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(A,{type:"button",size:"sm",disabled:M||h!==null,onClick:qe($),children:[e.jsx(Un,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":M?"Queuing…":"Run extract"]}),e.jsx(Qa,{label:"About extraction",children:"Queries the current release for this project without downloading it again."})]})]}),Z&&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."}),!te()&&e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:yn("/backlinks"),children:"Go to Backlinks admin"})})})]}),oe&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No referring domains found"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["The latest release found no referring domains for ",s.targetDomain,". Try a newer release or re-run this extract."]}),!te()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:yn("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(A,{type:"button",variant:"outline",size:"sm",disabled:M||h!==null,onClick:qe($),children:[e.jsx(Un,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":M?"Queuing…":"Re-run extract"]}),e.jsxs(Qa,{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 _(D){if(!s)return null;const Z="Linking hosts",oe="linking hosts",ne="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:Ha(s.totalLinkingDomains)})}),e.jsxs("p",{className:"metric-card-sub",children:["unique domains linking to ",s.targetDomain]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("p",{className:"metric-card-eyebrow",children:["Total ",oe]}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:Ha(s.totalHosts)})}),e.jsxs("p",{className:"metric-card-sub",children:["aggregate ",oe," across referring domains"]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsx("p",{className:"metric-card-eyebrow",children:"Top-10 concentration"}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:ex(s.top10HostsShare)})}),e.jsxs("p",{className:"metric-card-sub",children:["share of ",oe," from the 10 largest linking domains"]})]})]}),e.jsxs("p",{className:"text-xs text-muted mt-2",children:[e.jsx("span",{className:"text-secondary",children:"Common Crawl"})," · ",ne," ",e.jsx("code",{className:"text-secondary",children:s.release})," · queried ",tx(s.queriedAt),w>0&&e.jsxs(e.Fragment,{children:[" · ",w," excluded domain",w===1?"":"s"]})]}),q.length>=2&&e.jsxs(xe,{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(Ws,{width:"100%",height:"100%",children:e.jsxs(Ys,{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:nt[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:nt[0],stopOpacity:0})]})}),e.jsx(Js,{dataKey:"date",tick:Rt,stroke:is,tickFormatter:Xh}),e.jsx(Xs,{tick:Rt,stroke:is,allowDecimals:!1}),e.jsx(Zs,{contentStyle:as.contentStyle,labelStyle:as.labelStyle,itemStyle:as.itemStyle,labelFormatter:Zh}),e.jsx(Fs,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:nt[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(xe,{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:Z})]})}),e.jsxs("tbody",{children:[L.map(U=>e.jsxs("tr",{className:"border-b border-mono-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-strong",children:U.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-secondary tabular-nums",children:Ha(U.numHosts)})]},U.linkingDomain)),L.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-muted",colSpan:2,children:w>0&&Q===0?`Every referring domain in this ${ne} was a crawler/proxy host (${w} hidden).`:`No referring domains in this ${ne}.`})})]})]})}),e.jsx(Rs,{page:X,pageSize:na,visibleRows:L.length,totalRows:Q,onPageChange:U=>j((U-1)*na)})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:D})]})}}function rx({projectName:t}){const s=we({...Ac({client:H,path:{name:t}}),staleTime:Ao}),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:_n(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:Vt()?"text-sm text-secondary":"text-sm text-muted",children:n.reason==="no-queries"?"Add queries to start tracking AI citations.":Vt()?Qs:"Run a sweep to see which engines cite this project."})]});const{providersCiting:r,providersMentioning:o,providersConfigured:i}=n.summary;return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsxs("h2",{className:"flex items-center gap-2",children:["Cited by ",r," of ",i," engines",e.jsx(Me,{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 ",o," of ",i," engine answers",e.jsx(Me,{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(ix,{data:n}),e.jsx(ox,{data:n}),n.competitorGaps.length>0&&e.jsx(ux,{data:n})]})}function ix({data:t}){const{totalQueries:s,queriesCitedAndMentioned:n,queriesCitedOnly:a,queriesMentionedOnly:r,queriesInvisible:o}=t.summary;return e.jsxs("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4 mb-4",children:[e.jsx(aa,{label:"Cited + mentioned",value:`${n} / ${s}`,helper:"In sources AND named in answer",tone:n>0?"positive":"neutral"}),e.jsx(aa,{label:"Cited only",value:`${a} / ${s}`,helper:"In sources, not named in answer",tone:a>0?"positive-dim":"neutral"}),e.jsx(aa,{label:"Mentioned only",value:`${r} / ${s}`,helper:"Named in answer, no source link",tone:r>0?"caution":"neutral"}),e.jsx(aa,{label:"Invisible",value:`${o} / ${s}`,helper:"No engine cites or mentions",tone:o>0?"negative":"neutral"})]})}function aa({label:t,value:s,helper:n,tone:a}){const r=a==="positive"?"text-positive":a==="positive-dim"?"text-positive-400/70":a==="caution"?"text-caution":a==="negative"?"text-negative":"text-heading";return e.jsxs("div",{className:"rounded-md border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:t}),e.jsx("p",{className:`mt-1 text-2xl font-semibold tabular-nums ${r}`,children:s}),e.jsx("p",{className:"text-[11px] text-muted",children:n})]})}function ox({data:t}){const s=l.useMemo(()=>{const n=new Set;for(const a of t.byQuery)for(const r of a.providers)n.add(r.provider);return Array.from(n).sort()},[t.byQuery]);return t.byQuery.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No query coverage rows."}):e.jsxs("div",{children:[e.jsx(lx,{}),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(Cn,{provider:n})},n)),e.jsx("th",{className:"text-right",children:"Cite"}),e.jsx("th",{className:"text-right",children:"Ment"})]})}),e.jsx("tbody",{children:t.byQuery.map(n=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:n.query}),s.map(a=>{const r=n.providers.find(o=>o.provider===a);return e.jsx("td",{className:"text-center",children:r==null?e.jsx(am,{className:"inline h-3.5 w-3.5 text-mono-700","aria-label":"no data"}):e.jsx(cx,{provider:r})},a)}),e.jsx("td",{className:"text-right tabular-nums",children:e.jsxs("span",{className:n.totalProviders>0&&n.citedCount===n.totalProviders?"text-positive":n.citedCount>0?"text-positive-400/70":"text-muted",children:[n.citedCount,"/",n.totalProviders]})}),e.jsx("td",{className:"text-right tabular-nums",children:e.jsxs("span",{className:n.totalProviders>0&&n.mentionedCount===n.totalProviders?"text-info-300":n.mentionedCount>0?"text-info-400/70":"text-muted",children:[n.mentionedCount,"/",n.totalProviders]})})]},n.queryId))})]})})]})}function lx(){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(Nn,{active:!0,tone:"cited"}),e.jsx("span",{children:"cited (in sources)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Nn,{active:!0,tone:"mentioned"}),e.jsx("span",{children:"mentioned (in answer)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Nn,{active:!1,tone:"cited"}),e.jsx(Nn,{active:!1,tone:"mentioned"}),e.jsx("span",{children:"neither"})]})]})}function cx({provider:t}){const s=dx(t);return e.jsxs("span",{className:"inline-flex items-center justify-center gap-1",title:s,children:[e.jsx(Nn,{active:t.cited,tone:"cited"}),e.jsx(Nn,{active:t.mentioned,tone:"mentioned"})]})}function dx(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 Nn({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 ux({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(Me,{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(Cn,{provider:s.provider})}),e.jsx("td",{className:"text-neutral",children:s.citingCompetitors.join(", ")})]},`${s.queryId}::${s.provider}`))})]})})]})}const Wn="__cited__",Yn="__mentioned__",rs="__mentionShare__";function Zo(t){const s=t,{dataStartDate:n,dataEndDate:a}=s;return typeof n!="string"||typeof a!="string"?null:{start:$s(n),end:$s(a),sweepCount:s.sweepCount??1}}function Ca(t){const s=Zo(t);if(!s)return"Sweep date unavailable";const n=Bs(s.start),a=Bs(s.end);return n===a?n:`${n} – ${a} · ${s.sweepCount} sweeps combined`}function mx(t){const s=Zo(t);return s?qo(s.start):""}function An(t){return t.trim().toLowerCase()}function vr(t){return Math.round(t*1e3)/10}function jr(t){return t.byProvider??{}}function hx(t,s,n){const a=t.buckets.length>0,r=t.buckets.length===1;if(n==="overall"){const u=s==="cited"?Wn:Yn,h=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(x=>({date:x.startDate,[u]:vr(x[h])})),series:[u],hasData:a,singleBucket:r}}const o=s==="mentioned"?"mentionRate":"citationRate",i=[...new Set(t.buckets.flatMap(u=>Object.keys(jr(u))))].sort();return{rows:t.buckets.map(u=>{const h={date:u.startDate},m=jr(u);for(const x of i){const g=m[x];h[x]=g?vr(g[o]):null}return h}),series:i,hasData:a,singleBucket:r}}function el(t){const s=t;return Object.hasOwn(s,"modelEvidenceByProvider")?s.modelEvidenceByProvider??{}:null}function xx(t){const s=t;return Object.hasOwn(s,"modelAttribution")?s.modelAttribution??{}:null}function px(t){return t.servedModelAttribution??{}}function gx(t){return t.modelServiceMismatch??{}}function fx(t){return t.modelPointerChanges??{}}function yx(t){return t.length>0?t.join(", "):null}function Pi(t,s){const n=An(s);return Object.entries(t).find(([a])=>An(a)===n)?.[1]}function Cs(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 bx(t,s){for(let n=t.length-1;n>=0;n-=1){const a=t[n];if(!Pi(jr(a),s))continue;const r=el(a);return r?Pi(r,s)??null:null}return null}function vx(t){const s=new Map;for(const[n,a]of Object.entries(t))for(const r of a.events){const o=s.get(r.bucketStartDate)??[];o.push({provider:n,event:r}),s.set(r.bucketStartDate,o)}return[...s.entries()].sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>({bucketStartDate:n,events:[...a].sort((r,o)=>r.provider.localeCompare(o.provider)||r.event.observedAt.localeCompare(o.event.observedAt))}))}function jx(t){const s={},n=[];for(const[a,r]of Object.entries(t)){const o=r.events.filter(i=>!i.fromPreWindowAnchor);for(const i of r.events)i.fromPreWindowAnchor&&n.push({provider:a,event:i});o.length>0&&(s[a]={...r,events:o})}return{buckets:vx(s),beforeWindow:n.sort((a,r)=>a.event.observedAt.localeCompare(r.event.observedAt)||a.provider.localeCompare(r.provider))}}function Nx(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 wx(t){const s=[];for(const[n,a]of Object.entries(t)){const r=a.eventTotal??a.events.length;r>a.events.length&&s.push({provider:n,shown:a.events.length,total:r})}return s.sort((n,a)=>n.provider.localeCompare(a.provider))}function Sx(t){const s=t.buckets.map(a=>{const r=a.mentionShare;return{date:a.startDate,[rs]:r?.rate==null?null:vr(r.rate)}}),n=s.map(a=>a[rs]).filter(a=>typeof a=="number"&&Number.isFinite(a));return{rows:s,series:[rs],hasData:n.length>0,singleBucket:n.length===1}}function Cx(t,s,n){return s==="mentionShare"?Sx(t):hx(t,s,n)}function Ri(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 Ii(t){const[,s,n]=t.slice(0,10).split("-");return!s||!n?t:`${s}/${n}`}function $i(t){return t>0?`+${t}`:`${t}`}function kx(t){if(t.length===0)return null;if(t.length<=2)return`Query set changed: ${t.map(n=>`${$i(n.delta)} on ${Ii(n.date)}`).join(", ")}`;const s=[...t].sort((n,a)=>a.date.localeCompare(n.date))[0];return`Query set changed ${t.length} times (latest ${$i(s.delta)} on ${Ii(s.date)})`}const Ax=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],cn={"non-brand":"Non-brand queries",branded:"Branded queries",unknown:"Unclassified queries"},Gs="min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",Nr=new Intl.NumberFormat("en",{style:"percent",maximumFractionDigits:1});function tl(t){return t.kind==="project"?"Whole site":t.kind==="group"?`${t.label} · Group`:t.kind==="market"?`${t.label} · Market`:t.label}function ms({value:t,unit:s}){return t.rate===null?e.jsx("span",{className:"text-sm text-secondary",children:t.reason==="not-applicable"?"Not applicable":"Not measured"}):e.jsxs("span",{className:"inline-flex flex-col gap-1",children:[e.jsx("strong",{className:"tabular-nums text-heading",children:Nr.format(t.rate)}),e.jsxs("span",{className:"text-sm tabular-nums text-secondary",children:[t.numerator," of ",t.denominator,s?` ${s}`:""]})]})}function Px(t){const s=new Map;for(const n of t){const a=s.get(n.queryKey);a?a.rows.push(n):s.set(n.queryKey,{queryKey:n.queryKey,query:n.query,rows:[n]})}return[...s.values()]}function Rx({population:t}){const s=t.trend.flatMap(n=>{const a={createdAt:n.createdAt,mentioned:n.mentionCoverage.rate,cited:n.citationCoverage.rate};return n.continuity.state==="comparable"||n.continuity.state==="first"?[a]:[{createdAt:n.createdAt,mentioned:null,cited:null},a]});return s.length===0?e.jsx("p",{className:"py-6 text-sm text-secondary",children:"No measured trend for this selection."}):e.jsxs(e.Fragment,{children:[e.jsxs("ul",{"aria-label":"Trend legend",className:"flex gap-5 py-3 text-sm text-secondary",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{"aria-hidden":"true",className:"h-0.5 w-5",style:{backgroundColor:nt[1]}}),"Mentioned"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{"aria-hidden":"true",className:"h-0.5 w-5",style:{backgroundColor:Is.positive}}),"Cited"]})]}),e.jsx("div",{className:"visibility-trend-chart",role:"img","aria-label":`${cn[t.queryClass]} mention and citation trend`,children:e.jsx(Ws,{width:"100%",height:"100%",children:e.jsxs(Ys,{data:s,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Vn,{stroke:Bn,vertical:!1}),e.jsx(Js,{dataKey:"createdAt",tick:Rt,tickLine:!1,axisLine:{stroke:is},tickFormatter:n=>new Date(String(n)).toLocaleDateString(void 0,{month:"short",day:"numeric"}),minTickGap:24}),e.jsx(Xs,{domain:[0,1],tick:Rt,tickLine:!1,axisLine:!1,width:48,tickFormatter:n=>Nr.format(Number(n))}),e.jsx(Zs,{formatter:n=>typeof n=="number"?Nr.format(n):"Not measured",labelFormatter:n=>new Date(String(n)).toLocaleDateString()}),e.jsx(As,{type:"linear",dataKey:"mentioned",name:"Mentioned",stroke:nt[1],strokeWidth:2,connectNulls:!1,isAnimationActive:!1,dot:{r:3}}),e.jsx(As,{type:"linear",dataKey:"cited",name:"Cited",stroke:Is.positive,strokeWidth:2,connectNulls:!1,isAnimationActive:!1,dot:{r:3}})]})})}),e.jsxs("details",{className:"py-3 text-sm text-secondary",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3",children:"Trend data and comparability"}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"}),e.jsx("th",{children:"Comparison"})]})}),e.jsx("tbody",{children:t.trend.map(n=>e.jsxs("tr",{children:[e.jsx("td",{children:new Date(n.createdAt).toLocaleDateString()}),e.jsx("td",{children:e.jsx(ms,{value:n.mentionCoverage})}),e.jsx("td",{children:e.jsx(ms,{value:n.citationCoverage})}),e.jsx("td",{children:n.continuity.state.replaceAll("-"," ")})]},n.runId))})]})})]})]})}function Ix({report:t,onSelectionChange:s}){const[n,a]=l.useState(""),r=l.useRef(null),o=l.useRef(null),i=l.useId(),{selection:c,scopeOptions:u,filterOptions:h}=t,m=tl(c.scope),x=u.filter(d=>`${d.kind==="project"?"Whole site":d.label} ${d.kind}`.toLocaleLowerCase().includes(n.trim().toLocaleLowerCase()));l.useEffect(()=>{const d=f=>{r.current?.open&&f.target instanceof Node&&!r.current.contains(f.target)&&(r.current.open=!1)};return document.addEventListener("pointerdown",d),()=>document.removeEventListener("pointerdown",d)},[]);const g=(d,f,y,j)=>e.jsxs("label",{className:"min-w-0",children:[e.jsx("span",{className:"mb-1 block text-sm font-medium text-heading",children:d}),e.jsx("select",{"aria-label":d,className:Gs,value:y,onChange:N=>s({[f]:N.target.value||void 0,measurementQueryKey:void 0}),children:j.map(N=>e.jsx("option",{value:N.value,children:N.label},N.value))})]});return e.jsx("div",{className:"visibility-filter-container",children:e.jsxs("div",{className:"visibility-report-filters","data-has-scope":u.length>1,role:"group","aria-label":"Visibility filters",children:[u.length>1?e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{id:`${i}-label`,className:"mb-1 block text-sm font-medium text-heading",children:"Measurement scope"}),e.jsxs("details",{ref:r,className:"relative",onToggle:d=>{d.currentTarget.open&&(a(""),o.current?.focus())},onKeyDown:d=>{d.key==="Escape"&&(d.preventDefault(),d.currentTarget.open=!1,d.currentTarget.querySelector("summary")?.focus())},children:[e.jsxs("summary",{id:`${i}-value`,"aria-labelledby":`${i}-label ${i}-value`,className:`${Gs} visibility-scope-trigger`,children:[m,e.jsx(Hs,{size:16,"aria-hidden":"true",className:"shrink-0 text-secondary"})]}),e.jsxs("div",{className:"visibility-scope-menu",children:[e.jsx("input",{ref:o,type:"search","aria-label":"Search scopes",className:Gs,placeholder:"Search groups, markets, properties",value:n,onChange:d=>a(d.target.value)}),e.jsxs("div",{className:"mt-2 max-h-72 overflow-y-auto",children:[x.map(d=>e.jsxs("button",{className:"flex min-h-11 w-full items-center justify-between gap-3 rounded px-2 text-left text-sm text-primary hover:bg-surface-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400","aria-current":c.scope.kind===d.kind&&c.scope.id===d.id?"true":void 0,onClick:()=>{r.current&&(r.current.open=!1,r.current.querySelector("summary")?.focus()),s({measurementScope:d.kind,measurementScopeKey:d.kind==="project"?void 0:d.id})},children:[e.jsx("span",{className:"min-w-0 break-words",children:d.kind==="project"?"Whole site":d.label}),e.jsx("span",{className:"shrink-0 text-right text-xs text-secondary",children:d.kind==="group"?e.jsxs(e.Fragment,{children:["Group",e.jsxs("span",{className:"block",children:[d.targetCount," properties"]})]}):d.kind==="market"?e.jsxs(e.Fragment,{children:["Market",e.jsx("span",{className:"block",children:"query context"})]}):d.kind==="property"?"Property":`${d.targetCount} properties`})]},`${d.kind}:${d.id}`)),x.length===0?e.jsx("p",{className:"py-3 text-sm text-secondary",children:"No matching scopes."}):null]})]})]})]}):null,g("Query type","queryClass",c.queryClass,[{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"},{value:"all",label:"All classes, separate"},{value:"unknown",label:"Unclassified"}]),g("Answer engine","measurementProvider",c.provider??"",[{value:"",label:"All engines"},...h.providers.map(d=>({value:d,label:d}))]),g("Search location","measurementLocation",c.location.kind==="exact"?c.location.value:c.location.kind==="none"?"none":"",[{value:"",label:"All locations"},...h.locations.filter(d=>d.kind!=="all").map(d=>({value:d.kind==="exact"?d.value:"none",label:d.kind==="exact"?d.value:"No location"}))])]})})}function $x({report:t,isRefreshing:s=!1,onSelectionChange:n,onManageQueries:a,onPage:r,onSearch:o,search:i="",queryKey:c,answerSelection:u,evidenceReport:h,isEvidenceLoading:m=!1,evidenceError:x,onRetryEvidence:g,onEvidencePage:d}){const f=l.useRef(null),y=l.useRef(void 0),j=h??t,N=j.populations.filter(w=>[...w.queries.items,...w.evidence.items].some(X=>X.queryKey===c)),P=u?[u.queryClass]:(N.length?N:m?[]:t.populations.slice(0,1)).map(w=>w.queryClass),M=c?JSON.stringify([u??c,P]):void 0,k=l.useId();l.useEffect(()=>{if(!M){s||(y.current=void 0);return}if(y.current===M)return;const w=f.current?.querySelectorAll('[aria-label="Measured answers"]');if(w?.length){for(const X of w){const C=X.closest("details[data-query-results]");C&&(C.open=!0)}w[0].focus({preventScroll:!0}),w[0].scrollIntoView?.({block:"start"}),y.current=M}},[M,s]);const{selection:p,filterOptions:v}=t,S=p.measurement,$=tl(p.scope),q=new Map(t.scopeOptions.filter(w=>w.kind==="property").map(w=>[w.id,w.label])),L=w=>{const X=j.populations.find(C=>C.queryClass===w.queryClass)?.evidence;return{items:X?.items.filter(C=>C.queryKey===c&&(!u||C.provider===u.provider&&C.model===u.model&&C.location===u.location&&(u.runId===null||C.runId===u.runId)))??[],nextCursor:X?.nextCursor}},Q=(w,X,C,F,_)=>e.jsxs("div",{className:"min-w-40 flex-1",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-1",children:[e.jsx("label",{htmlFor:`${k}-${X}`,className:"text-sm font-medium text-heading",children:w}),e.jsx(Me,{text:_})]}),e.jsx("select",{id:`${k}-${X}`,className:Gs,value:C,onChange:D=>n({[X]:D.target.value||void 0,measurementQueryKey:void 0}),children:F.map(D=>e.jsx("option",{value:D.value,children:D.label},D.value))})]});return e.jsxs("section",{ref:f,className:"visibility-report","aria-label":"AI visibility results",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 border-b border-default pb-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(ce,{tone:S.state==="measured"?"positive":"neutral",children:S.state==="measured"?"Complete":S.state==="partial"?"Partial":"Not measured"}),S.completedAt?e.jsx("span",{className:"text-sm text-secondary",children:new Date(S.completedAt).toLocaleString()}):null,S.awaitingSweep?e.jsxs("span",{role:"status",className:"inline-flex items-center gap-1 text-sm text-secondary",children:[e.jsxs("span",{children:[S.pendingAssignmentCount," query assignments pending across project"]}),e.jsx(Me,{text:`Measured under revision ${S.measuredRevision??"unavailable"}. Project has ${S.pendingAssignmentCount} assignments awaiting sweep. Existing results stay visible until those assignments are measured.`})]}):null]}),a?e.jsx(A,{variant:"outline",onClick:a,children:"Manage queries"}):null]}),p.provenance.kind==="legacy-simple"?e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 border-b border-default py-3 text-sm text-secondary",children:[e.jsx("p",{children:"Legacy results have no frozen query classification."}),p.queryClass!=="unknown"&&p.queryClass!=="all"?e.jsx(A,{variant:"outline",onClick:()=>n({queryClass:"unknown",measurementQueryKey:void 0}),children:"View unclassified results"}):null]}):null,e.jsx(Ix,{report:t,onSelectionChange:n}),e.jsxs("details",{className:"border-b border-default text-sm text-secondary",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3",children:"More filters"}),e.jsxs("div",{className:"flex flex-wrap gap-4 pb-3",children:[e.jsxs("label",{className:"min-w-40 flex-1",children:[e.jsx("span",{className:"mb-1 block text-sm font-medium text-heading",children:"Start date (UTC)"}),e.jsx("input",{type:"date",className:Gs,value:p.time.from?.slice(0,10)??"",onChange:w=>n({measurementFrom:w.target.value?`${w.target.value}T00:00:00.000Z`:void 0})})]}),e.jsxs("label",{className:"min-w-40 flex-1",children:[e.jsx("span",{className:"mb-1 block text-sm font-medium text-heading",children:"End date (UTC)"}),e.jsx("input",{type:"date",className:Gs,value:p.time.to?.slice(0,10)??"",onChange:w=>n({measurementTo:w.target.value?`${w.target.value}T23:59:59.999Z`:void 0})})]}),Q("AI model","measurementModel",p.model??"",[{value:"",label:"All models"},...Array.from(new Set(v.models.filter(w=>!p.provider||w.provider===p.provider).map(w=>w.model))).map(w=>({value:w,label:w}))],"Filter by the AI model recorded with each answer. This does not change the model used by future sweeps."),Q("Results from","measurementRunId",p.run.explicit?p.run.id??"":"",[{value:"",label:"Latest saved sweep"},...[...t.populations[0].trend].reverse().map(w=>({value:w.runId,label:new Date(w.createdAt).toLocaleString()}))],"Choose a saved AI sweep to view its results. No new sweep starts.")]})]}),t.populations.map(w=>{const X=Px(w.queries.items),C=p.mode==="advanced"?7:6;return e.jsxs("section",{"aria-label":cn[w.queryClass],className:"py-4",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("h2",{children:cn[w.queryClass]}),e.jsx(Me,{text:w.queryClass==="non-brand"?"Queries that do not name the measured identity. Geography alone is not a brand.":w.queryClass==="branded"?"Queries that name the measured identity.":"The measured definition could not establish a query class. These answers are not included in branded or non-brand rates."})]}),e.jsxs("div",{className:"flex flex-wrap gap-x-8 gap-y-4 border-y border-default py-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center gap-1 text-sm text-secondary",children:[e.jsx("span",{children:p.mode==="advanced"&&p.scope.kind!=="property"?"Answers mentioning a property":"Mentioned answers"}),p.mode==="advanced"?e.jsx(Me,{text:"An answer counts when it mentions any assigned property. This does not mean every property was mentioned."}):null]}),e.jsx(ms,{value:w.summary.mentionCoverage,unit:"answers"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center gap-1 text-sm text-secondary",children:[e.jsx("span",{children:p.mode==="advanced"&&p.scope.kind!=="property"?"Answers citing a property":"Cited answers"}),p.mode==="advanced"?e.jsx(Me,{text:"An answer counts when it cites a matching URL for any assigned property. This does not mean every property was cited."}):null]}),e.jsx(ms,{value:w.summary.citationCoverage,unit:"answers"})]}),p.mode==="advanced"&&p.scope.kind!=="property"?e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-sm text-secondary",children:"Properties mentioned"}),e.jsx(ms,{value:w.summary.propertyReach,unit:"properties"})]}):null,e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-sm text-secondary",children:"Queries measured"}),e.jsx("strong",{className:"tabular-nums text-heading",children:w.summary.queryCount})]})]}),e.jsx(Rx,{population:w}),p.mode==="advanced"?e.jsxs("details",{className:"border-t border-default text-sm text-secondary","aria-label":`${cn[w.queryClass]} property outcomes`,children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3",children:"Property outcomes"}),e.jsx("div",{className:"flex flex-wrap gap-x-8 gap-y-3 pb-4",children:[["bothSignals","mentioned and cited"],["mentionedOnly","mentioned only"],["citedOnly","cited only"],["neither","neither signal"],["notMeasured","not measured"]].map(([F,_])=>e.jsxs("div",{children:[e.jsx("strong",{className:"block tabular-nums text-heading",children:w.summary.outcomes[F]}),e.jsx("span",{className:"text-sm text-secondary",children:_}),F==="notMeasured"?e.jsx(Me,{text:"No eligible completed measurement for this selection. This is not the same as a measured answer with neither signal."}):null]},F))})]}):null,p.mode==="advanced"&&p.scope.kind!=="property"&&(w.breakdown.groups.length>0||w.breakdown.properties.length>0)?e.jsx(Tx,{population:w,scope:p.scope.kind,onSelectionChange:n},`${p.scope.kind}:${p.scope.id}`):null,e.jsxs("details",{className:"border-t border-default","data-query-results":w.queryClass,"aria-label":`${cn[w.queryClass]} query results`,children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-5 text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",children:[e.jsx("span",{className:"font-semibold",children:"Query results"}),e.jsxs("span",{className:"ml-3 text-sm font-normal text-secondary",children:[w.queries.total," ",w.queries.total===1?"result":"results"," · ",$]})]}),e.jsxs("div",{className:"pb-5",children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center justify-between gap-3",children:[o?e.jsx("input",{type:"search","aria-label":`Search ${cn[w.queryClass]}`,placeholder:"Search queries",className:`${Gs} max-w-sm`,value:i,onChange:F=>o(F.target.value)}):null,e.jsx(Me,{text:p.mode==="advanced"?"Each tracked query is grouped once on this page. Its engine rows retain the recorded model, location, property scope, and answer counts. Mentioned and Cited count answers matching any assigned property, not the percentage of properties found.":"Each tracked query is grouped once on this page. Its engine rows retain the recorded model, location, and answer counts. Mentioned counts answers naming your brand. Cited counts answers linking to your site."})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table measurement-responsive-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),p.mode==="advanced"?e.jsx("th",{children:"Properties"}):null,e.jsx("th",{children:"Answer engine"}),e.jsx("th",{children:"Search location"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"}),e.jsx("th",{className:"measurement-table-actions",children:e.jsx("span",{className:"sr-only",children:"Evidence"})})]})}),X.map(F=>e.jsxs("tbody",{"data-query-key":F.queryKey,children:[e.jsx("tr",{className:"bg-surface-subtle",children:e.jsx("th",{scope:"rowgroup",colSpan:C,className:"measurement-query-cell text-sm font-medium normal-case tracking-normal text-heading",children:F.query})}),F.rows.map(_=>e.jsxs("tr",{children:[e.jsx("td",{"aria-label":`Query: ${F.query}`,className:"measurement-query-cell text-secondary",children:e.jsx("span",{"aria-hidden":"true",children:"↳"})}),p.mode==="advanced"?e.jsx("td",{className:"measurement-target-cell",children:_.targetKeys.length===1?q.get(_.targetKeys[0])??_.targetKeys[0]:_.targetKeys.length>1?e.jsxs("details",{children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-2 text-secondary",children:[_.targetKeys.length," properties"]}),e.jsx("ul",{className:"max-h-48 space-y-2 overflow-y-auto py-2 text-sm text-secondary",children:_.targetKeys.map(D=>e.jsx("li",{children:q.get(D)??D},D))})]}):"No properties"}):null,e.jsxs("td",{children:[_.provider,_.model?e.jsx("span",{className:"block text-sm text-secondary",children:_.model}):null]}),e.jsx("td",{children:_.location??"No location"}),e.jsx("td",{children:e.jsx(ms,{value:_.mentionCoverage})}),e.jsx("td",{children:e.jsx(ms,{value:_.citationCoverage})}),e.jsx("td",{className:"measurement-table-actions",children:e.jsx(A,{variant:"ghost","aria-label":`View answers for ${_.query} · ${_.provider}`,onClick:()=>n({measurementQueryKey:_.queryKey,measurementAnswer:JSON.stringify({queryKey:_.queryKey,queryClass:w.queryClass,provider:_.provider,model:_.model,location:_.location,runId:p.run.id,revision:p.revision})}),children:"View answers"})})]},JSON.stringify([_.provider,_.model,_.location])))]},F.queryKey))]})}),w.queries.items.length===0?e.jsx("p",{className:"py-4 text-sm text-secondary",children:"No measured queries match this selection."}):e.jsxs("p",{className:"mt-3 text-sm text-secondary",children:[X.length," ",X.length===1?"query":"queries"," · ",w.queries.items.length," ",w.queries.items.length===1?"engine result":"engine results"," shown of ",w.queries.total," results"]}),w.queries.nextCursor&&r?e.jsx(A,{variant:"outline",onClick:()=>r(w.queries.nextCursor),children:"Next queries"}):null,c&&P.includes(w.queryClass)?e.jsxs("section",{tabIndex:-1,className:"scroll-mt-6 border-t border-default py-5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400","aria-label":"Measured answers","aria-busy":m,children:[e.jsxs("div",{className:"section-head",children:[e.jsx("h3",{children:"Answers"}),e.jsx(A,{variant:"ghost",onClick:F=>{y.current=void 0,F.currentTarget.closest("details[data-query-results]")?.querySelector("summary")?.focus(),n({measurementQueryKey:void 0,measurementAnswer:void 0})},children:"Close answers"})]}),m?e.jsx("p",{role:"status",className:"py-4 text-sm text-secondary",children:"Loading saved answers…"}):x?e.jsxs("div",{role:"alert",className:"py-4 text-sm text-secondary",children:[e.jsxs("p",{children:["Saved answers unavailable: ",x]}),g?e.jsx(A,{variant:"outline",onClick:g,children:"Retry answers"}):null]}):e.jsxs(e.Fragment,{children:[L(w).items.map(F=>e.jsxs("article",{className:"border-b border-default py-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("strong",{className:"text-sm text-heading",children:F.provider}),F.model?e.jsx("span",{className:"text-sm text-secondary",children:F.model}):null,e.jsx("span",{className:"text-sm text-secondary",children:F.location??"No location"}),e.jsx("span",{className:"text-sm text-secondary",children:new Date(F.createdAt).toLocaleString()}),e.jsx(ce,{tone:"neutral",children:F.mentioned===null?"Mention not checked":F.mentioned?"Mentioned":"Not mentioned"}),e.jsx(ce,{tone:"neutral",children:F.cited===null?"Citation not checked":F.cited?"Cited":"Not cited"})]}),e.jsx("h4",{className:"mt-3 text-sm font-medium text-heading",children:F.query}),e.jsx("p",{className:"mt-3 max-w-prose whitespace-pre-wrap text-sm leading-6 text-primary",children:F.answerText??"Answer text unavailable."}),e.jsx("ul",{className:"mt-3 space-y-2",children:F.sources.map(_=>{const D=Ds(_);return e.jsx("li",{className:"break-all text-sm",children:D?e.jsx("a",{href:D,target:"_blank",rel:"noreferrer",className:"text-link hover:underline",children:_}):e.jsx("span",{className:"text-secondary",children:_})},_)})})]},F.answerId)),L(w).items.length===0?e.jsx("p",{className:"py-4 text-sm text-secondary",children:L(w).nextCursor?"No matching answers on this page. Continue to the next answers.":"No matching saved answers on this page."}):null,L(w).nextCursor&&d?e.jsx(A,{variant:"outline",onClick:()=>d(L(w).nextCursor),children:"Next answers"}):null]})]}):null]})]}),e.jsxs("details",{className:"border-t border-default","aria-label":`${cn[w.queryClass]} competitors`,children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-5 text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",children:[e.jsx("span",{className:"font-semibold",children:"Competitors"}),e.jsx("span",{className:"ml-3 text-sm font-normal text-secondary",children:w.competitorAvailability.state==="unavailable"?"Not available":`${w.competitors.length} measured`})]}),e.jsxs("div",{className:"pb-5",children:[w.competitorAvailability.state==="unavailable"?e.jsx("p",{className:"text-sm text-secondary",children:"Competitor rates unavailable for this historical definition."}):w.competitors.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No measured competitors in this selection."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Competitor"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"})]})}),e.jsx("tbody",{children:w.competitors.map(F=>e.jsxs("tr",{children:[e.jsx("td",{children:F.domain}),e.jsx("td",{children:e.jsx(ms,{value:F.mentionCoverage})}),e.jsx("td",{children:e.jsx(ms,{value:F.citationCoverage})})]},F.domain))})]})}),w.observedCompetitors.length>0?e.jsxs("details",{className:"mt-4 text-sm",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3 text-heading",children:"Other names in answers"}),e.jsx("ul",{className:"divide-y divide-default",children:w.observedCompetitors.map(F=>e.jsxs("li",{className:"flex items-center justify-between gap-4 py-3",children:[e.jsx("span",{children:F.name}),e.jsxs("span",{className:"tabular-nums text-secondary",children:[F.answerCount," ",F.answerCount===1?"answer":"answers"]})]},F.name))}),e.jsx("p",{className:"py-2 text-secondary",children:"Observed names, not additions to your tracked competitors."})]}):null]})]})]},w.queryClass)})]})}function Tx({population:t,scope:s,onSelectionChange:n}){const[a,r]=l.useState(()=>s==="project"&&t.breakdown.groups.length>0?"groups":"properties"),o=xn({rows:t.breakdown[a],getSearchText:i=>i.label});return e.jsxs("section",{className:"border-t border-default py-5","aria-label":"Scope breakdown",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[e.jsx("div",{className:"flex gap-2",children:["groups","properties"].map(i=>e.jsx(A,{variant:a===i?"secondary":"ghost",onClick:()=>{r(i),o.setPage(1)},children:i==="groups"?"Groups":"Properties"},i))}),e.jsx("input",{type:"search","aria-label":"Search breakdown",placeholder:"Search",value:o.query,onChange:i=>o.setQuery(i.target.value),className:`${Gs} max-w-sm`})]}),e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:a==="groups"?"Group":"Property"}),e.jsx("th",{children:"Queries"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"})]})}),e.jsx("tbody",{children:o.rows.map(i=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("button",{className:"min-h-11 text-left text-link hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>n({measurementScope:a==="groups"?"group":"property",measurementScopeKey:i.id}),children:i.label})}),e.jsx("td",{children:i.queryCount}),e.jsx("td",{children:e.jsx(ms,{value:i.mentionCoverage})}),e.jsx("td",{children:e.jsx(ms,{value:i.citationCoverage})})]},i.id))})]})}),o.rows.length===0?e.jsxs("p",{className:"py-3 text-sm text-secondary",children:["No ",a," match this search."]}):null,e.jsx(Rs,{page:o.page,pageSize:o.pageSize,visibleRows:o.rows.length,totalRows:o.totalRows,itemLabel:a,onPageChange:o.setPage})]})}function Mx({projectName:t,selection:s,onSelectionChange:n,onManageQueries:a,fallback:r,showUnmeasuredFallback:o=!1}){const[i,c]=l.useState(),[u,h]=l.useState(""),[m,x]=l.useState(),g={scope:s.measurementScope,scopeKey:s.measurementScopeKey,queryClass:s.queryClass,provider:s.provider,model:s.model,location:s.location,from:s.from,to:s.to,revision:s.revision,runId:s.measurementRunId},d=we({...ei({client:H,path:{name:t},query:{...g,limit:25,cursor:i,search:u||void 0}}),retry:!1,placeholderData:Rr}),f={...g,queryKey:s.queryKey,queryClass:s.answer?.queryClass??s.queryClass,provider:s.answer?.provider??s.provider,model:s.answer?s.answer.model??void 0:s.model,location:s.answer?s.answer.location??"none":s.location,runId:s.answer?.runId??d.data?.selection.run.id??s.measurementRunId,revision:s.answer?.revision??d.data?.selection.revision??s.revision,limit:50},y=JSON.stringify(f),j=we({...ei({client:H,path:{name:t},query:{...f,cursor:m?.selection===y?m.cursor:void 0}}),enabled:!!s.queryKey&&!!d.data&&!d.isPlaceholderData,retry:!1});return d.data?.selection.availability.state==="unsupported"?e.jsx(e.Fragment,{children:r}):o&&d.data?.selection.mode==="simple"&&d.data.selection.measurement.state==="not-measured"?e.jsx(e.Fragment,{children:r}):d.error?e.jsxs("section",{className:"page-section-divider",role:"alert",children:[e.jsx("h2",{children:"AI visibility unavailable"}),e.jsx("p",{className:"my-3 text-sm text-secondary",children:_n(d.error)}),e.jsx(A,{variant:"outline",onClick:()=>{c(void 0),d.refetch()},children:"Retry"})]}):d.data?e.jsx("div",{"aria-busy":d.isFetching,children:e.jsx($x,{report:d.data,isRefreshing:d.isFetching,queryKey:s.queryKey,answerSelection:s.answer,evidenceReport:j.data,isEvidenceLoading:j.isFetching||!!s.queryKey&&j.isPending,evidenceError:j.error?_n(j.error):void 0,onRetryEvidence:()=>{j.refetch()},onEvidencePage:j.isFetching?void 0:N=>x({selection:y,cursor:N}),search:u,onSearch:N=>{h(N),c(void 0)},onPage:d.isFetching?void 0:c,onSelectionChange:N=>{(!("measurementQueryKey"in N)||Object.keys(N).some(P=>P!=="measurementQueryKey"&&P!=="measurementAnswer"))&&c(void 0),x(void 0),n(N)},onManageQueries:a})}):e.jsx("section",{className:"page-section-divider",role:"status","aria-label":"Loading AI visibility",children:e.jsx("div",{className:"h-64 animate-pulse rounded-md bg-surface"})})}const Lx=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],Ex=[{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:"On non-brand queries, the share of answer-text brand mentions for you and tracked competitors that were you. Pooled only when query classification is unavailable."}],Tr=nt[2],qx="var(--chart-tooltip-bg)",Dx={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",local:"Local"};function Ps(t){const s=An(t);return Dx[s]??t.charAt(0).toUpperCase()+t.slice(1)}function Ks(t){return Math.round(t*10)/10}function Ox(t){return t===Wn||t===Yn||t===rs}function sl(t){return t===Wn?"Cited":t===Yn?"Mentioned":t===rs?"Mention share":Ps(t)}function qn(t,s){return t===Wn?Is.positive:t===Yn?nt[1]:t===rs?Tr:dm(An(t),s)}function Fx(t,s){for(const n of t){const a=n[s];if(typeof a=="number"&&Number.isFinite(a))return a}return null}function Gx(t){return t.map(s=>s.trim().toLowerCase()).filter(Boolean).sort().join(`
|
|
2
2
|
`)}function Ia(t){return t==="non-brand"?"non-brand queries":"pooled queries · classification unavailable"}function pa(t,s){return t==="cited"?"Cited":t==="mentionShare"?s?`Mention share · ${Ia(s)}`:"Mention share":"Mentioned"}function zn(t){return t==="cited"?"citationRate":"mentionRate"}function nl(t,s){return s==="cited"?t.cited:t.mentionedCount}function al(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 rl(t,s){if(s===void 0)return null;const n=String(s);return t.find(a=>a.startDate===n)??null}function wr(t){const s=el(t);if(s===null)return"Model attribution unavailable for this bucket.";const n=Object.entries(s).sort(([a],[r])=>An(a).localeCompare(An(r))).map(([a,r])=>`${Ps(a)}: ${Cs(r)}`);return n.length>0?`Model evidence: ${n.join("; ")}`:"No model evidence in this bucket."}function Kx(t){return t.some(({event:s})=>s.to.status==="mixed")?Is.caution:t.some(({event:s})=>s.to.status==="unknown")?Is.negative:t.every(({event:s})=>s.from.status==="known"&&s.to.status==="known")?nt[4]:Is.positive}function _x(t,s,n){const a=rl(t,s);return a?Ca(a):Bs($s(n))}function Ux({partition:t,available:s,counts:n,truncated:a,incompleteHistory:r,served:o,mismatch:i,buckets:c}){const u=l.useId(),h=Object.entries(o).sort(([x],[g])=>x.localeCompare(g)),m=t.buckets.length>0||t.beforeWindow.length>0;return!s||!m?null:e.jsxs("aside",{className:"trend-model-evidence","aria-labelledby":"trend-model-evidence-title","aria-describedby":u,children:[e.jsxs("div",{className:"trend-model-evidence-head",children:[e.jsx("p",{id:"trend-model-evidence-title",className:"trend-model-evidence-title",children:"Model evidence changes"}),e.jsx("span",{className:"trend-model-evidence-key","aria-hidden":"true",children:"Dashed chart markers"})]}),e.jsxs("p",{id:u,className:"sr-only",children:["Model evidence is recorded from the exact snapshots that produced each trend bucket. It is not the project’s configured provider model.",n.total>0?` ${n.shown} of ${n.total} recorded changes are listed.`:""]}),t.buckets.length>0&&e.jsx("ul",{className:"trend-model-evidence-list",children:t.buckets.flatMap(({bucketStartDate:x,events:g})=>g.map(({provider:d,event:f})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:_x(c,x,f.observedAt)}),e.jsxs("span",{children:[Ps(d),": ",Cs(f.from)," → ",Cs(f.to)]})]},`${d}-${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:x,event:g})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsxs("span",{className:"trend-model-evidence-date",children:["on or before ",Bs($s(g.observedAt))]}),e.jsxs("span",{children:[Ps(x),": ",Cs(g.from)," → ",Cs(g.to),g.anchorObservedAt?` (last seen ${Cs(g.from)} on ${Bs($s(g.anchorObservedAt))})`:""]})]},`before-${x}-${g.observedAt}`))})]}),a.map(x=>e.jsxs("p",{className:"trend-model-evidence-note",children:[Ps(x.provider),": showing the most recent ",x.shown," of ",x.total," changes."]},`truncated-${x.provider}`)),r.map(x=>e.jsxs("p",{className:"trend-model-evidence-note",children:["We did not look far enough back to be sure this is every ",Ps(x)," change."]},`incomplete-${x}`)),h.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"trend-model-evidence-note",children:"What the engines answered with"}),e.jsx("ul",{className:"trend-model-evidence-list",children:h.map(([x,g])=>{const d=yx(g.latestServedModelIds),f=i[x];return e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:Bs($s(g.latestObservation.observedAt))}),e.jsxs("span",{children:[Ps(x),": ",d??Cs(g.latestObservation.state),f?` — not the ${Cs(f.configured)} you selected`:""]})]},`served-${x}`)})})]})]})}function Ti(t){return t===null?"no data":`${t}%`}function Wa(t){return t==null?"undefined":`${Ks(t*100)}%`}function Bx({active:t,label:s,payload:n,metric:a,mode:r,buckets:o}){if(!t)return null;const i=rl(o,s);if(!i)return null;if(a==="mentionShare"){const u=i.mentionShare.projectMentionSnapshots,h=i.mentionShare.competitorMentionSnapshots,m=u+h,x=i.mentionShare.rate==null?null:Ks(i.mentionShare.rate*100);return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:Ca(i)}),e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch trend-tooltip-swatch-ring",style:{borderColor:Tr},"aria-hidden":"true"}),e.jsxs("span",{className:"trend-tooltip-name",children:["Mention share · ",Ia(i.mentionShare.scope)]}),e.jsx("span",{className:"trend-tooltip-value",children:Ti(x)})]}),m>0?e.jsxs("p",{className:"trend-tooltip-detail",children:["You ",u," / ",m," brand mentions. Competitors ",h,"."]}):e.jsx("p",{className:"trend-tooltip-detail",children:"No project or competitor brand mentions in this bucket."}),e.jsx("p",{className:"trend-tooltip-detail",children:wr(i)})]})}const c=r==="byProvider"?(n??[]).filter(u=>u.dataKey!==void 0):[{dataKey:a==="cited"?Wn:Yn,value:Ks(i[zn(a)]*100)}];return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:Ca(i)}),c.map((u,h)=>{const m=String(u.dataKey??u.name??""),x=r==="byProvider"?al(i,m,a):null,g=x?.count??nl(i,a),d=x?.total??i.total,f=typeof u.value=="number"?u.value:Ks(x?x.rate*100:i[zn(a)]*100),y=u.color??qn(m,h);return e.jsxs("div",{className:"trend-tooltip-block",children:[e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch",style:{backgroundColor:y},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:sl(m)}),e.jsx("span",{className:"trend-tooltip-value",children:Ti(f)})]}),e.jsxs("p",{className:"trend-tooltip-detail",children:[g," / ",d," snapshots, ",a==="cited"?"source links":"answer text"]})]},`${m}-${h}`)}),e.jsx("p",{className:"trend-tooltip-detail",children:wr(i)})]})}function Vx({buckets:t,metric:s,mode:n,series:a}){const r=t[t.length-1]?.mentionShare.scope;return e.jsxs("table",{className:"sr-only",children:[e.jsxs("caption",{children:[pa(s,r)," 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(o=>{let i;if(s==="mentionShare"){const c=o.mentionShare.projectMentionSnapshots,u=o.mentionShare.competitorMentionSnapshots,h=c+u,m=Ia(o.mentionShare.scope);i=h>0?`${Wa(o.mentionShare.rate)} mention share for ${m}, ${c} of ${h} brand mentions were you`:`mention share undefined for ${m}, no project or competitor brand mentions`}else n==="byProvider"?i=a.map(c=>{const u=al(o,c,s);return u?`${Ps(c)} ${Wa(u.rate)} ${pa(s).toLowerCase()}, ${u.count} of ${u.total} snapshots`:`${Ps(c)} no data`}).join("; "):i=`${Wa(o[zn(s)])} ${pa(s).toLowerCase()}, ${nl(o,s)} of ${o.total} snapshots`;return i+=`; ${wr(o)}`,e.jsxs("tr",{children:[e.jsx("th",{scope:"row",children:Ca(o)}),e.jsx("td",{children:i})]},o.startDate)})})]})}function Ya({options:t,value:s,onChange:n,ariaLabel:a,className:r}){const o=l.useId();return e.jsx("div",{role:"group","aria-label":a,className:`segmented ${r??""}`,children:t.map(i=>{const c=s===i.value,u=i.description?`${o}-${i.value}-description`:void 0;return e.jsxs(l.Fragment,{children:[e.jsx("button",{type:"button","aria-pressed":c,"aria-describedby":u,className:`segmented-option ${c?"segmented-option-active":""}`,onClick:()=>n(i.value),children:i.label}),i.description&&e.jsx("span",{id:u,className:"sr-only",children:i.description})]},i.value)})})}function zx({projectName:t,competitorDomains:s=[],analyticsRevision:n="none"}){const[a,r]=l.useState("all"),[o,i]=l.useState("mentioned"),[c,u]=l.useState("byProvider"),h=l.useMemo(()=>Gx(s),[s]),m=we({queryKey:["analytics-metrics",t,a,h,n],queryFn:()=>Pc(t,a),staleTime:Ao}),x=m.data??null,g=m.error,d=o==="mentionShare"?"overall":c,f=l.useMemo(()=>x?Cx(x,o,d):null,[x,o,d]),y=x?xx(x):null,j=l.useMemo(()=>jx(y??{}),[y]),N=l.useMemo(()=>Nx(y??{}),[y]),P=l.useMemo(()=>wx(y??{}),[y]),M=l.useMemo(()=>Object.entries(y??{}).filter(([,U])=>U.anchorUnavailable).map(([U])=>U).sort(),[y]),k=l.useMemo(()=>x?px(x):{},[x]),p=l.useMemo(()=>x?gx(x):{},[x]),v=l.useMemo(()=>x?Rc(fx(x)):null,[x]),S=o!=="mentionShare"&&d==="byProvider",$=x?.buckets??[],q=$[$.length-1]?.mentionShare.scope??x?.mentionShareScope??"pooled",L=pa(o,q),Q=o==="cited"?Is.positive:o==="mentionShare"?Tr:nt[1],w=S?os.textDim:Q,X=l.useMemo(()=>{const U=new Map($.map(T=>[T.startDate,mx(T)]));return T=>U.get(String(T))??""},[$]),C=o==="mentionShare"?f?Ri(f.rows,rs):null:$.length>0?Ks($[$.length-1][zn(o)]*100):null,F=o==="mentionShare"?f?Fx(f.rows,rs):null:$.length>0?Ks($[0][zn(o)]*100):null,_=o==="mentionShare"?f?.rows.filter(U=>typeof U[rs]=="number").length??0:$.length,D=C!==null&&F!==null&&_>1?Ks(C-F):null,Z=s.length,oe=e.jsxs(e.Fragment,{children:[v?.kind==="change"&&e.jsx("p",{className:"mb-3 rounded-lg border border-caution-800/60 bg-caution-950/20 px-3 py-2 text-[11px] leading-snug text-secondary",children:v.text}),e.jsxs("div",{className:"visibility-trend-head",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsxs("h2",{className:"visibility-trend-title",children:["Answer-engine trend",e.jsx(Me,{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 all query-provider snapshots. Mention share uses non-brand queries when classification is available; pooled means the project has no usable brand identity for a split."})]})]}),C!==null&&e.jsxs("div",{className:"visibility-trend-current",children:[e.jsx("span",{className:"visibility-trend-current-dot",style:{backgroundColor:w},"aria-hidden":"true"}),e.jsx("span",{className:"visibility-trend-current-label",children:L}),S&&e.jsx("span",{className:"visibility-trend-current-qualifier",children:"avg"}),e.jsxs("span",{className:"visibility-trend-current-value",children:[C,"%"]}),D!==null&&e.jsxs("span",{className:`visibility-trend-current-delta ${D>0?"text-positive-400":D<0?"text-negative-400":"text-muted"}`,children:[D>0?"+":"",D.toFixed(1)," pts"]})]})]}),e.jsxs("div",{className:"visibility-trend-controls",children:[e.jsx(Ya,{options:Ex,value:o,onChange:i,ariaLabel:"Metric",className:"visibility-trend-metric-control"}),o!=="mentionShare"&&e.jsx(Ya,{options:Lx,value:c,onChange:u,ariaLabel:"Series"}),e.jsx(Ya,{options:Ax,value:a,onChange:r,ariaLabel:"Time window",className:"sm:ml-auto"})]})]});let ne;if(g)ne=e.jsx("p",{className:"text-sm text-negative-400",children:_n(g)});else if(m.isLoading&&!x)ne=e.jsx("div",{className:"visibility-trend-chart animate-pulse rounded-lg bg-bg-elevated/40","aria-hidden":"true"});else if(o==="mentionShare"&&Z===0)ne=e.jsx("p",{className:"text-sm text-secondary",children:"Add tracked competitors to measure mention share over time."});else if(!x||!f)ne=null;else{const{rows:U,series:T,hasData:G}=f,ae=kx(x.queryChanges);if(!G)ne=e.jsx("p",{className:"text-sm text-secondary",children:o==="mentionShare"?`No answer-text brand mentions for you or tracked competitors on ${Ia(q)} in this window yet.`:Vt()?Qs:"Run a sweep to start tracking citations and mentions over time."});else if(S&&T.length===0)ne=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 W=`${L} rate across ${U.length} ${U.length===1?"sweep":"sweeps"}. Latest ${C}%${D!==null?`, ${D>=0?"up":"down"} ${Math.abs(D).toFixed(1)} points over the period`:""}.`;ne=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"sr-only",children:W}),e.jsx(Vx,{buckets:$,metric:o,mode:d,series:T}),S&&T.length>0&&e.jsx("ul",{className:"trend-legend","aria-label":"Engines",children:T.map((J,ge)=>{const z=Ri(U,J),re=bx($,J),ue=y===null?"Attribution unavailable":re?Cs(re):"No observed model evidence";return e.jsxs("li",{className:"trend-legend-item",children:[e.jsx("span",{className:"trend-legend-swatch",style:{backgroundColor:qn(J,ge)},"aria-hidden":"true"}),e.jsxs("span",{className:"trend-legend-label",children:[e.jsx("span",{className:"trend-legend-name",children:sl(J)}),e.jsxs("span",{className:"trend-legend-model",children:[e.jsx("span",{"aria-hidden":"true",children:"· "}),ue]})]}),z!==null&&e.jsxs("span",{className:"trend-legend-value",children:[z,"%"]})]},J)})}),e.jsx("div",{className:"visibility-trend-chart",role:"img","aria-label":`${L} trend chart over ${U.length} ${U.length===1?"bucket":"buckets"}`,children:e.jsx(Ws,{width:"100%",height:"100%",children:e.jsxs(Ys,{data:U,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Vn,{stroke:Bn,vertical:!1}),e.jsx(Js,{dataKey:"date",tick:Rt,tickLine:!1,axisLine:{stroke:is},tickFormatter:X,minTickGap:24}),e.jsx(Xs,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:J=>`${J}%`,tick:Rt,tickLine:!1,axisLine:!1,width:40}),e.jsx(Zs,{cursor:{stroke:is,strokeWidth:1},content:e.jsx(Bx,{metric:o,mode:d,buckets:$})}),j.buckets.map(({bucketStartDate:J,events:ge})=>e.jsx(gm,{x:J,stroke:Kx(ge),strokeDasharray:"4 4",strokeWidth:1.5,ifOverflow:"extendDomain"},`model-evidence-${J}`)),T.map((J,ge)=>e.jsx(As,{type:"monotone",dataKey:J,name:J,stroke:qn(J,ge),strokeDasharray:J===rs?"5 4":void 0,strokeWidth:Ox(J)?2.5:2,dot:J===rs?{r:2.75,fill:"var(--chart-tooltip-bg)",stroke:qn(J,ge),strokeWidth:1.5}:{r:2.5,fill:qn(J,ge),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:qx},connectNulls:J!==rs,isAnimationActive:!1},J))]})})}),e.jsx(Ux,{partition:j,available:y!==null,counts:N,truncated:P,incompleteHistory:M,served:k,mismatch:p,buckets:$}),ae&&e.jsx("p",{className:"visibility-trend-note",children:ae})]})}}return e.jsxs("section",{className:"visibility-trend",children:[oe,ne]})}const Mi=new Set([Gn.queued,Gn.running]);function Li({projectName:t,onReviewForTracking:s,viewerResearchConfig:n=null}){const a=js(),{account:r,canWrite:o}=Hn(),i=r?.role==="viewer"&&n!==null,[c,u]=l.useState(""),[h,m]=l.useState(""),[x,g]=l.useState(""),[d,f]=l.useState(""),[y,j]=l.useState(null),N=l.useRef(null),P=l.useRef(!1),M=we({...Ic({client:H,path:{name:t}}),staleTime:6e4}),k=we({...$c({client:H}),enabled:!i,staleTime:6e4}),p=we({...Tc({client:H,path:{name:t},query:{limit:20}}),refetchInterval:G=>G.state.data?.runs.some(ae=>Mi.has(ae.status))?3e3:!1}),v=p.isError?[]:p.data?.runs??[];l.useEffect(()=>{!y&&v[0]&&j(v[0].id)},[v,y]);const S=v.find(G=>G.id===y)??null,$=we({...Mc({client:H,path:{name:t,runId:y??""}}),enabled:!p.isError&&!!y,refetchInterval:S&&Mi.has(S.status)?3e3:!1}),q=p.isError||$.isError?null:$.data??null,L=l.useMemo(()=>Wx(c),[c]),Q=M.data?.locations??[],w=l.useMemo(()=>{const G=new Map((k.data?.providerCatalog??[]).map(ae=>[ae.name,ae]));return(k.data?.providers??[]).filter(ae=>ae.configured&&G.get(ae.name)?.mode==="api").map(ae=>({...ae,catalog:G.get(ae.name)}))},[k.data]),X=!k.isLoading&&w.length===0,C=w.find(G=>G.name===h)??null;l.useEffect(()=>{if(!h&&M.data&&!M.isError&&!k.isError){const G=M.data.providers.find(ae=>w.some(W=>W.name===ae));m(G??w[0]?.name??"")}},[h,w,M.data,M.isError,k.isError]),l.useEffect(()=>{!d&&M.data&&!M.isError&&f(M.data.defaultLocation??"__none__")},[d,M.data,M.isError]);const F=d==="__none__"?null:Q.find(G=>G.label===d),_=C?.catalog.modelConfigurable??!1,D=(_?x.trim():"")||(C?M.data?.providerModels[C.name]:"")||C?.catalog.defaultModel,Z=F===void 0?null:i?{queries:L,location:F}:C&&D?{queries:L,provider:C.name,..._?{model:D}:{},location:F}:null,oe=Z?JSON.stringify({projectName:t,...Z}):null,ne=(o||i)&&!te()&&Z!==null&&!M.isPending&&!M.isError&&!M.isFetching&&(i||!k.isPending&&!k.isError&&!k.isFetching)&&L.length>0&&L.length<=50;l.useEffect(()=>{N.current?.fingerprint!==oe&&(N.current=null)},[oe]);const U=Pt({...Lc(),onSuccess:async G=>{N.current=null,j(G.id),u(""),g(""),await Zx(a),Se({title:"Research batch saved",detail:`${G.totalQueries} quer${G.totalQueries===1?"y is":"ies are"} in research history. Nothing was added to tracked queries.`,tone:"positive",dedupeKey:`research:start:${G.id}`,dedupeMode:"replace"})},onError:G=>{Se({title:"Could not start research",detail:G instanceof Error?G.message:"Check the provider, model, and location, then try again.",tone:"negative"})},onSettled:()=>{P.current=!1}});function T(){!ne||U.isPending||P.current||!Z||!oe||(P.current=!0,N.current?.fingerprint!==oe&&(N.current={fingerprint:oe,key:crypto.randomUUID()}),U.mutate({client:H,path:{name:t},body:{...Z,idempotencyKey:N.current.key}}))}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(xe,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsx("div",{children:e.jsx("h3",{children:"Test queries"})})}),e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("label",{className:"block",htmlFor:"research-queries",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Queries"}),e.jsx("textarea",{id:"research-queries",className:"mt-1 min-h-36 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:`one query per line
|
|
3
3
|
e.g. What is the best way to choose an AEO platform?`,value:c,"aria-label":"Queries",onChange:G=>u(G.target.value),"aria-describedby":"research-query-count"}),e.jsxs("span",{id:"research-query-count",className:`mt-1 block text-[11px] ${L.length>50?"text-negative":"text-faint"}`,children:[L.length," ",L.length===1?"query":"queries",", duplicates and blank lines are removed. Maximum 50."]})]}),e.jsxs("div",{className:`grid gap-3 ${i?"":"sm:grid-cols-2"}`,children:[i?null: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:h,onChange:G=>{m(G.target.value),g("")},children:[e.jsx("option",{value:"",disabled:!0,children:"Choose a provider"}),w.map(G=>e.jsx("option",{value:G.name,children:G.displayName??G.name},G.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:d,onChange:G=>f(G.target.value),children:[e.jsx("option",{value:"",disabled:!0,children:"Choose a location"}),e.jsx("option",{value:"__none__",children:"No location"}),Q.map(G=>e.jsx("option",{value:G.label,children:G.label},G.label))]})]})]}),i?null: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:D?`Current: ${D}`:"Choose a provider to select an exact model",value:x,disabled:!C||!_,onChange:G=>g(G.target.value)}),e.jsx("datalist",{id:"research-known-models",children:(C?.catalog.knownModels??[]).map(G=>e.jsx("option",{value:G.id,children:G.displayName},G.id))})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 border-t border-default pt-4",children:[!te()&&(i?e.jsxs(A,{type:"button",size:"sm",disabled:!ne||U.isPending,onClick:T,children:[e.jsx(Un,{size:14}),U.isPending?"Starting research…":`Run ${L.length||""} research ${L.length===1?"query":"queries"}`]}):e.jsxs(De,{type:"button",size:"sm",disabled:!ne||U.isPending,onClick:T,children:[e.jsx(Un,{size:14}),U.isPending?"Starting research…":`Run ${L.length||""} research ${L.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."})]}),i?e.jsxs("p",{className:"text-xs text-secondary",children:[n.viewerDailyRunLimit," research runs per project each day."]}):Z&&"provider"in Z?e.jsxs("p",{className:"text-xs text-secondary",children:[C?.displayName??Z.provider," · ",D," · ",F?.label??"No location"]}):null,!i&&k.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load API providers."}),e.jsx(A,{variant:"outline",onClick:()=>{k.refetch()},children:"Retry providers"})]}):null,M.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load project locations."}),e.jsx(A,{variant:"outline",onClick:()=>{M.refetch()},children:"Retry locations"})]}):null,!i&&!k.isError&&X&&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(xe,{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"})]}),p.isFetching&&e.jsx(ce,{tone:"neutral",children:"Loading"})]}),p.isError?e.jsxs("div",{role:"alert",className:"mt-4 text-sm text-negative",children:[e.jsx("p",{children:"Could not load research history."}),e.jsx(A,{variant:"outline",onClick:()=>{p.refetch()},children:"Retry history"})]}):p.isPending?e.jsx("p",{role:"status",children:"Loading research history…"}):v.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:v.map(G=>e.jsxs("tr",{className:y===G.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:()=>j(G.id),children:Yx(G.createdAt)})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:G.provider}),e.jsx("span",{className:"font-mono text-[11px] text-muted",children:G.requestedModel??G.resolvedModel})]}),e.jsx("td",{className:"text-secondary",children:G.location?.label??"No location"}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[G.completedQueries+G.failedQueries,"/",G.totalQueries]}),e.jsx("td",{children:e.jsx(ce,{tone:il(G.status),children:G.status})})]},G.id))})]})})]})]}),!p.isError&&$.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load saved research results."}),e.jsx(A,{variant:"outline",onClick:()=>{$.refetch()},children:"Retry results"})]}):p.isError?null:e.jsx(Qx,{detail:q,isLoading:$.isFetching,onReviewForTracking:s})]})}function Qx({detail:t,isLoading:s,onReviewForTracking:n}){const[a,r]=l.useState(null);l.useEffect(()=>{r(t?.queries[0]?.id??null)},[t?.id]);const o=t?.queries.find(i=>i.id===a)??t?.queries[0]??null;return e.jsxs(xe,{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 ${Jx(t.id)}`:"Choose a research batch"})]}),t&&e.jsx(ce,{tone:il(t.status),children:t.status})]}),t?e.jsxs("div",{className:"mt-4 grid gap-4 xl:grid-cols-[minmax(0,1.15fr)_minmax(320px,0.85fr)]",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[680px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"})]})}),e.jsx("tbody",{children:t.queries.map(i=>e.jsxs("tr",{className:o?.id===i.id?"bg-bg-elevated/40":void 0,children:[e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-left font-medium text-heading hover:text-link focus:outline-none focus:underline",onClick:()=>r(i.id),children:i.query})}),e.jsx("td",{children:e.jsx(ce,{tone:Xx(i.status),children:i.status})}),e.jsx("td",{children:e.jsx(ce,{tone:i.answerMentioned===!0?"positive":i.answerMentioned===!1?"neutral":i.status===mn.failed?"negative":"caution",children:i.answerMentioned===null?i.status===mn.failed?"Unavailable":"Pending":i.answerMentioned?"Mentioned":"Not mentioned"})}),e.jsx("td",{children:e.jsx(ce,{tone:i.citationState==="cited"?"positive":i.citationState==="not-cited"?"neutral":i.status===mn.failed?"negative":"caution",children:i.citationState===null?i.status===mn.failed?"Unavailable":"Pending":i.citationState==="cited"?"Cited":"Not cited"})})]},i.id))})]})}),e.jsx(Hx,{query:o,isLoading:s,onReviewForTracking:n})]}):e.jsx("p",{className:"mt-4 text-sm text-muted",children:"Select a saved batch to inspect each answer and its source links."})]})}function Hx({query:t,isLoading:s,onReviewForTracking:n}){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})]}),!te()&&n&&e.jsxs("div",{className:"rounded-md border border-default bg-surface-subtle px-3 py-3",children:[e.jsx(De,{type:"button",size:"sm",onClick:()=>n({researchRunQueryId:t.id}),children:"Review for tracking"}),e.jsx("p",{className:"mt-2 text-xs leading-5 text-muted",children:"Only this saved query text enters tracking review. Its answer remains research evidence."})]}),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===mn.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(a=>e.jsx("span",{className:"mention-chip mention-chip--competitor",children:a},a))})]}),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(a=>e.jsx("span",{className:"mention-chip mention-chip--competitor",children:a.replace(/^www\./,"")},a))})]}),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((a,r)=>{const o=Ds(a.uri),i=a.title||a.uri;return e.jsxs("li",{className:"flex min-w-0 items-start gap-1.5 text-sm",children:[o?e.jsx("a",{href:o,target:"_blank",rel:"noopener noreferrer",className:"truncate text-secondary hover:text-link focus:outline-none focus:underline",children:i}):e.jsx("span",{className:"truncate text-secondary",children:i}),o&&e.jsx(rm,{className:"mt-0.5 size-3 shrink-0 text-muted","aria-hidden":"true"})]},`${a.uri}-${r}`)})})]})]}):e.jsx("p",{className:"text-sm text-muted",children:s?"Loading saved answers…":"Select a query to inspect its answer."})}function Wx(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 Yx(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 Jx(t){return t.length>8?t.slice(0,8):t}function il(t){return t===Gn.completed?"positive":t===Gn.partial?"caution":t===Gn.failed?"negative":"neutral"}function Xx(t){return t===mn.completed?"positive":t===mn.failed?"negative":"neutral"}async function Zx(t){await Nt(t,"researchRuns")}const Sr=new Set(["queued","seeding","probing"]);function ep({projectName:t,queryWorkspace:s,onQueryWorkspaceChange:n,researchMode:a,onResearchModeChange:r,selection:o={measurementScope:"project",queryClass:"all"},onSelectionChange:i,trackingQueryId:c,onTrackingQueryIdChange:u}){const{account:h}=Hn(),[m,x]=l.useState("tracked"),[g,d]=l.useState("find"),[f,y]=l.useState(null),j=h?.role==="viewer"?Ec():null,N=h?.role!=="viewer"||j!==null,P=s??m,M=P==="research"&&!N?"tracked":P,k=a??g,p=$=>{s===void 0&&x($),n?.($)},v=$=>{a===void 0&&d($),r?.($)},S=$=>{y({...$,trackingSelection:{...o}}),p("tracked")};return e.jsxs("section",{className:"page-section-divider","aria-labelledby":"queries-heading",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"queries-heading",children:"Queries"})}),e.jsxs("div",{className:"mt-3 flex border-b border-default",role:"tablist","aria-label":"Query workspace",children:[e.jsx(ka,{active:M==="tracked",label:"Tracked",onClick:()=>p("tracked")}),N?e.jsx(ka,{active:M==="research",label:"Research",onClick:()=>p("research")}):null]}),e.jsx("div",{className:"mt-4",children:M==="tracked"?e.jsx(bp,{projectName:t,selection:o,onSelectionChange:i,trackingQueryId:c,onTrackingQueryIdChange:u,pendingTrackingSource:f,onPendingTrackingSourceHandled:()=>y(null)}):e.jsx(tp,{projectName:t,selection:o,mode:k,onModeChange:v,onReviewSavedSource:S,viewerResearchConfig:j})})]})}function ka({active:t,label:s,onClick:n}){return e.jsx("button",{type:"button",role:"tab","aria-selected":t,className:`-mb-px border-b-2 px-3 py-2 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500 focus-visible:ring-inset ${t?"border-mono-400 text-heading":"border-transparent text-muted hover:border-strong hover:text-strong"}`,onClick:n,children:s})}function tp({projectName:t,selection:s,mode:n,onModeChange:a,onReviewSavedSource:r,viewerResearchConfig:o}){const i=we({...Po({client:H,path:{name:t}}),enabled:o===null&&s.measurementScope!=="project"}),c=i.data?fa(s,i.data):s.measurementScope==="project"?"Whole site":`${s.measurementScopeKey??"Selected scope"} · ${s.measurementScope==="group"?"Group":s.measurementScope==="market"?"Market":"Property"}`,u=i.data&&s.measurementScope==="property"?`${c} · Property`:c;return o?e.jsx(Li,{projectName:t,viewerResearchConfig:o}):e.jsxs("div",{children:[e.jsxs("p",{className:"mb-3 text-sm text-secondary",children:["Tracking destination: ",u]}),e.jsxs("div",{className:"flex border-b border-default",role:"tablist","aria-label":"Research workspace",children:[e.jsx(ka,{active:n==="find",label:"Find queries",onClick:()=>a("find")}),e.jsx(ka,{active:n==="test",label:"Test queries",onClick:()=>a("test")})]}),e.jsx("div",{className:"mt-4",children:n==="find"?e.jsx(vp,{projectName:t,onReviewDiscoveryProbe:h=>r({source:"discovery",discoveryProbeId:h})}):e.jsx(Li,{projectName:t,onReviewForTracking:({researchRunQueryId:h})=>r({source:"research",researchRunQueryId:h})})})]})}function sp({workspace:t,selection:s,onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:o,onPendingTrackingSourceHandled:i,templates:c,preview:u,isPreviewing:h,isCommitting:m,onPreview:x,onCommit:g}){const[d,f]=l.useState(null),[y,j]=l.useState(()=>ga(s)),[N,P]=l.useState(null),M=l.useRef(null),k=l.useRef(null),p=l.useMemo(()=>ip(t.tracked,s),[s,t.tracked]),v=xn({rows:p,getSearchText:C=>`${C.queryText} ${C.provenance?.source??"legacy"} ${C.assignments.map(F=>F.queryClass??"unknown").join(" ")}`});l.useEffect(()=>{if(!a){k.current=null;return}const C=`${a}:${ya(s)}`;if(k.current===C)return;const F=t.tracked.find(_=>_.queryId===a);F&&(k.current=C,f({kind:"edit",row:F,audience:t.mode==="advanced"?Ja(s):void 0,scopeLabel:fa(s,t)}),j(Ei(F,s)),P(null))},[s,a,t]),l.useEffect(()=>{if(!o)return;const C=ga(o.trackingSelection??s);f({kind:"add"}),j(o.source==="research"?{...C,source:"research",researchRunQueryId:o.researchRunQueryId}:{...C,source:"discovery",discoveryProbeId:o.discoveryProbeId}),P(null),i()},[i,o,s]),l.useEffect(()=>{if(!d||d.kind==="remove")return;const C=M.current;C&&(C.scrollIntoView?.({block:"start"}),C.focus({preventScroll:!0}))},[d]);function S(C="manual"){f({kind:"add"}),j({...ga(s),source:C}),P(null),r?.(void 0)}function $(C){k.current=`${C.queryId}:${ya(s)}`,f({kind:"edit",row:C,audience:t.mode==="advanced"?Ja(s):void 0,scopeLabel:fa(s,t)}),j(Ei(C,s)),P(null),r?.(C.queryId)}function q(C){k.current=`${C.queryId}:${ya(s)}`,f({kind:"remove",row:C,audience:t.mode==="advanced"?Ja(s):void 0,scopeLabel:fa(s,t)}),P(null),r?.(C.queryId)}function L(){f(null),P(null),r?.(void 0)}const Q=d?np(d,y,t.mode):null,w=d!==null&&d.kind==="add"&&t.mode==="advanced"&&!Mr(y),X=Q!==null&&(!w||y.contexts.length>0)&&!h;return e.jsxs("div",{className:"query-tracking-workspace space-y-4",children:[e.jsxs("section",{"aria-label":"Tracked queries",children:[e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsx(lp,{workspace:t,selection:s,onSelectionChange:n}),e.jsx(Us,{value:v.query,onChange:v.setQuery,label:"Filter tracked queries",placeholder:"Search tracked queries",className:"min-w-64 flex-[2]"}),!te()&&e.jsxs(De,{type:"button",size:"sm",onClick:()=>S(),children:[e.jsx(im,{"aria-hidden":"true",size:14}),"Add query"]})]}),t.active?null:e.jsx("p",{className:"mt-3 text-sm text-caution",children:"No published measurement yet."}),v.rows.length===0?e.jsx("p",{className:"mt-5 text-sm text-muted",children:v.hasQuery?"No tracked queries match that search.":"No tracked queries in this scope yet."}):e.jsx("div",{className:"mt-5 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table measurement-responsive-table min-w-[760px] table-auto",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Scope"}),e.jsx("th",{children:"Class"}),e.jsx("th",{children:"Source"}),e.jsx("th",{children:"Measurement"}),e.jsx("th",{className:"measurement-table-actions",children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{children:v.rows.map(C=>e.jsxs("tr",{children:[e.jsx("td",{className:"tracking-query-cell break-words font-medium text-heading",children:C.queryText}),e.jsx("td",{className:"tracking-scope-cell text-secondary",children:ol(C,t,s)}),e.jsx("td",{className:"whitespace-nowrap",children:e.jsx(dp,{row:C})}),e.jsx("td",{className:"whitespace-nowrap text-secondary",children:cp(C)}),e.jsx("td",{className:"whitespace-nowrap",children:e.jsx(up,{row:C})}),e.jsx("td",{className:"measurement-table-actions whitespace-nowrap text-right",children:!te()&&e.jsxs("div",{className:"tracking-row-actions flex min-w-max justify-end gap-2",children:[e.jsxs(De,{type:"button",variant:"ghost",size:"sm","aria-label":`Edit ${C.queryText}`,onClick:()=>$(C),children:[e.jsx(om,{"aria-hidden":"true",size:13})," Edit"]}),e.jsxs(De,{type:"button",variant:"ghost",size:"sm","aria-label":`Remove ${C.queryText}`,onClick:()=>q(C),children:[e.jsx(Mo,{"aria-hidden":"true",size:13})," Remove"]})]})})]},C.queryId))})]})}),e.jsx(Rs,{page:v.page,pageSize:v.pageSize,visibleRows:v.rows.length,totalRows:v.totalRows,itemLabel:"queries",onPageChange:v.setPage})]}),d&&!te()&&e.jsx(mp,{workspace:t,templates:c,action:d,draft:y,onDraftChange:C=>{j(C),P(null)},onClose:L,canReview:X,isPreviewing:h,editorHeadingRef:M,onReview:()=>{Q&&(P(Q),x(Q))}}),u&&N&&d&&e.jsx(gp,{preview:u,workspace:t,isCommitting:m,onConfirm:()=>{g({...N,expectedWorkspaceVersion:u.workspaceVersion,previewToken:u.previewToken,reviewedAt:u.reviewedAt})}})]})}function ga(t){return{source:"manual",text:"",templateId:"",templateVersion:"",template:"",researchRunQueryId:"",discoveryProbeId:"",wholeSite:t.measurementScope==="project"||!t.measurementScopeKey,targetKeys:t.measurementScope==="property"&&t.measurementScopeKey?[t.measurementScopeKey]:[],groupKeys:t.measurementScope==="group"&&t.measurementScopeKey?[t.measurementScopeKey]:[],marketKeys:t.measurementScope==="market"&&t.measurementScopeKey?[t.measurementScopeKey]:[],contexts:[],queryClass:"auto"}}function Ei(t,s){return{...ga(s),text:t.queryText,queryClass:"keep"}}function np(t,s,n){if(t.kind==="remove")return{additions:[],removals:[{queryId:t.row.queryId,...t.audience?{audience:t.audience}:{}}]};if(t.kind==="edit")return s.text.trim()?{additions:[],removals:[],edits:[{queryId:t.row.queryId,text:s.text.trim(),...t.audience?{audience:t.audience}:{},...n==="advanced"&&s.queryClass!=="keep"?{queryClass:s.queryClass==="auto"?null:s.queryClass}:{}}]}:null;const a=ap(s);if(!a||Cr(s)||!s.wholeSite&&s.targetKeys.length+s.groupKeys.length+s.marketKeys.length===0)return null;const r=rp(s);return{additions:[{input:a,...r?{audience:r}:{},...n==="advanced"&&!Mr(s)&&s.contexts.length>0?{contexts:s.contexts}:{},...n==="advanced"&&s.queryClass!=="auto"&&s.queryClass!=="keep"?{queryClass:s.queryClass}:{}}],removals:[]}}function ap(t){return t.source==="manual"?t.text.trim()?{source:"manual",text:t.text.trim()}:null:t.source==="template"?t.templateId&&t.templateVersion&&t.template?{source:"template",templateId:t.templateId,templateVersion:t.templateVersion,template:t.template}:null:t.source==="research"?t.researchRunQueryId?{source:"research",researchRunQueryId:t.researchRunQueryId}:null:t.discoveryProbeId?{source:"discovery",discoveryProbeId:t.discoveryProbeId}:null}function rp(t){if(t.wholeSite)return;const s={...t.targetKeys.length>0?{targetKeys:t.targetKeys}:{},...t.groupKeys.length>0?{groupKeys:t.groupKeys}:{},...t.marketKeys.length>0?{marketKeys:t.marketKeys}:{}};return Object.keys(s).length>0?s:void 0}function Mr(t){return t.marketKeys.length>0&&t.targetKeys.length===0&&t.groupKeys.length===0}function Cr(t){return t.source==="template"&&t.template.includes("{market}")&&(t.wholeSite||t.marketKeys.length===0)}function Ja(t){if(t.measurementScopeKey){if(t.measurementScope==="property")return{targetKeys:[t.measurementScopeKey]};if(t.measurementScope==="group")return{groupKeys:[t.measurementScopeKey]};if(t.measurementScope==="market")return{marketKeys:[t.measurementScopeKey]}}}function fa(t,s){const a=(t.measurementScope==="property"?s.targets:t.measurementScope==="group"?s.groups:t.measurementScope==="market"?s.markets:[]).find(r=>r.stableKey===t.measurementScopeKey)?.label;return a?t.measurementScope==="group"?`${a} · Group`:t.measurementScope==="market"?`${a} · Market`:a:"Whole site"}function ip(t,s){return s.measurementScope==="project"||!s.measurementScopeKey?[...t]:t.filter(n=>n.assignments.some(a=>s.measurementScope==="property"?a.targetKey===s.measurementScopeKey:s.measurementScope==="group"?a.groupKeys.includes(s.measurementScopeKey):a.marketKeys.includes(s.measurementScopeKey)))}function ya(t){return t.measurementScopeKey&&t.measurementScope!=="project"?`${t.measurementScope}:${t.measurementScopeKey}`:"project"}function op(t){if(t==="project")return{measurementScope:"project",measurementScopeKey:void 0};const[s,n]=t.split(":",2);return{measurementScope:s,measurementScopeKey:n}}function lp({workspace:t,selection:s,onSelectionChange:n}){const[a,r]=l.useState(""),o=l.useRef(null),i=l.useRef(null);l.useEffect(()=>{const g=d=>{o.current?.open&&d.target instanceof Node&&!o.current.contains(d.target)&&(o.current.open=!1)};return document.addEventListener("pointerdown",g),()=>document.removeEventListener("pointerdown",g)},[]);const c=l.useMemo(()=>[{value:"project",label:"Whole site",detail:"Project"},...t.groups.map(g=>({value:`group:${g.stableKey}`,label:g.label,detail:"Group"})),...t.markets.map(g=>({value:`market:${g.stableKey}`,label:g.label,detail:"Market"})),...t.targets.map(g=>({value:`property:${g.stableKey}`,label:g.label,detail:"Property"}))],[t.groups,t.markets,t.targets]),u=ya(s),h=c.find(g=>g.value===u)??c[0],m=a.trim().toLocaleLowerCase(),x=m?c.filter(g=>`${g.label} ${g.detail}`.toLocaleLowerCase().includes(m)):c;return e.jsxs("div",{className:"min-w-64 flex-1",children:[e.jsx("span",{id:"tracking-scope-label",className:"mb-1 block text-xs font-medium text-secondary",children:"Measurement scope"}),e.jsxs("details",{ref:o,className:"relative",onToggle:g=>{g.currentTarget.open&&i.current?.focus()},onKeyDown:g=>{g.key==="Escape"&&(g.preventDefault(),g.currentTarget.open=!1,g.currentTarget.querySelector("summary")?.focus())},children:[e.jsxs("summary",{"aria-labelledby":"tracking-scope-label",className:"visibility-scope-trigger min-h-11 rounded-md border border-default bg-surface px-3 text-sm text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500",children:[h.detail==="Group"||h.detail==="Market"?`${h.label} · ${h.detail}`:h.label,e.jsx(Hs,{size:16,"aria-hidden":"true",className:"shrink-0 text-secondary"})]}),e.jsxs("div",{className:"visibility-scope-menu",children:[e.jsx("p",{className:"mb-2 text-sm leading-5 text-secondary",children:"Group: properties grouped together. Market: search context."}),e.jsxs("label",{children:[e.jsx("span",{className:"sr-only",children:"Search scopes"}),e.jsx("input",{ref:i,type:"search","aria-label":"Search scopes",className:"h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",placeholder:"Search groups, markets, properties",value:a,onChange:g=>r(g.target.value)})]}),e.jsx("div",{className:"mt-2 max-h-72 overflow-y-auto",children:x.length===0?e.jsx("p",{className:"py-3 text-sm text-secondary",children:"No matching scopes."}):x.map(g=>e.jsxs("button",{type:"button",className:"flex min-h-11 w-full items-center justify-between gap-3 rounded px-2 text-left text-sm text-primary hover:bg-surface-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500","aria-label":`${g.label}, ${g.detail}`,"aria-current":g.value===u?"true":void 0,onClick:d=>{const f=d.currentTarget.closest("details");f&&(f.open=!1,f.querySelector("summary")?.focus()),n?.(op(g.value))},children:[e.jsx("span",{children:g.label}),e.jsx("span",{className:"text-secondary",children:g.detail})]},g.value))})]})]})]})}function cp(t){switch(t.provenance?.source){case"manual":return"Manual";case"template":return"Template";case"research":return"Saved research";case"discovery":return"Discovery";default:return"Legacy"}}function ol(t,s,n){const a=new Map(s.targets.map(d=>[d.stableKey,d.label])),r=new Map(s.groups.map(d=>[d.stableKey,d.label])),o=new Map(s.markets.map(d=>[d.stableKey,d.label])),i=new Set,c=new Set,u=new Set;for(const d of t.assignments)i.add(d.targetKey),(n?.measurementScope!=="property"||d.targetKey===n.measurementScopeKey)&&(d.groupKeys.forEach(f=>c.add(f)),d.marketKeys.forEach(f=>u.add(f)));if(i.size===0)return"Whole site";const m=n?.measurementScope==="property"&&i.has(n.measurementScopeKey??"")?i.size===1?["This property only"]:["This property",`Shared with ${i.size-1} other ${i.size===2?"property":"properties"}`]:[i.size===1?a.get([...i][0])??[...i][0]:`${i.size} properties`],x=c.size===1?r.get([...c][0])??[...c][0]:null,g=u.size===1?o.get([...u][0])??[...u][0]:null;return x&&g&&x===g?m.push(`${x} (group and market)`):(x?m.push(`Group: ${x}`):c.size>1&&m.push(`${c.size} groups`),g?m.push(`Market: ${g}`):u.size>1&&m.push(`${u.size} markets`)),m.join(" · ")}function dp({row:t}){const s=[...new Set(t.assignments.map(a=>a.queryClass??"unknown"))],n=s.join(", ");return e.jsx(ce,{tone:s.includes("unknown")?"caution":"neutral",children:n||"Unknown"})}function up({row:t}){return t.state==="tracked"?e.jsx(ce,{tone:"positive",children:"Measured"}):e.jsx(ce,{tone:"caution",children:"Awaiting sweep"})}function mp({workspace:t,templates:s,action:n,draft:a,onDraftChange:r,onClose:o,canReview:i,isPreviewing:c,editorHeadingRef:u,onReview:h}){return n.kind==="remove"?e.jsxs(xe,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{children:"Remove query"}),e.jsxs("p",{className:"mt-1 text-sm leading-6 text-secondary",children:["Remove “",n.row.queryText,"” from future tracking?"]}),e.jsxs("p",{className:"mt-1 text-sm leading-5 text-secondary",children:[n.audience?`Only assignments in ${n.scopeLabel} will be removed.`:"All assignments will be removed."," Earlier results stay unchanged."]})]})}),e.jsx(Xa,{canReview:i,isPreviewing:c,onCancel:o,onReview:h})]}):n.kind==="edit"?e.jsxs(xe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline gap-4",children:[e.jsx("h3",{ref:u,tabIndex:-1,children:"Edit query"}),e.jsx(A,{type:"button",variant:"ghost",size:"sm",onClick:o,children:"Cancel"})]}),e.jsxs("p",{className:"mt-3 text-sm leading-6 text-secondary",children:[n.audience?`Changes apply only to assignments in ${n.scopeLabel}.`:"Changes apply to every assignment of this query."," Earlier results stay unchanged."]}),e.jsxs("div",{className:"mt-4 max-w-2xl space-y-4",children:[e.jsxs("label",{className:"block",htmlFor:"tracking-query-text",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Query text"}),e.jsx("textarea",{id:"tracking-query-text",className:"mt-1 min-h-28 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:a.text,onChange:m=>r({...a,text:m.target.value})})]}),t.mode==="advanced"&&e.jsxs("label",{className:"block",htmlFor:"tracking-query-class",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Classification"}),e.jsxs("select",{id:"tracking-query-class",className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:a.queryClass,onChange:m=>r({...a,queryClass:m.target.value}),children:[e.jsx("option",{value:"keep",children:"Keep existing classifications"}),e.jsx("option",{value:"auto",children:"Automatic"}),e.jsx("option",{value:"branded",children:"Branded"}),e.jsx("option",{value:"non-brand",children:"Non-brand"})]})]}),e.jsx("p",{className:"text-sm leading-6 text-secondary",children:"Existing locations and engines are preserved. Use Add query to create assignments in another scope."})]}),e.jsx(Xa,{canReview:i,isPreviewing:c,onCancel:o,onReview:h})]}):e.jsxs(xe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline gap-4",children:[e.jsx("h3",{ref:u,tabIndex:-1,children:"Add query"}),e.jsx(A,{type:"button",variant:"ghost",size:"sm",onClick:o,children:"Cancel"})]}),e.jsxs("div",{className:"mt-4 grid gap-4 lg:grid-cols-[minmax(250px,0.8fr)_minmax(0,1.2fr)]",children:[e.jsxs("div",{className:"space-y-4",children:[a.source==="manual"?e.jsxs("label",{className:"block",htmlFor:"tracking-query-text",children:[e.jsx("span",{className:"text-sm font-medium text-secondary",children:"Question"}),e.jsx("textarea",{id:"tracking-query-text",className:"mt-1 min-h-28 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",placeholder:"e.g. How do teams compare AEO platforms?",value:a.text,onChange:m=>r({...a,text:m.target.value})})]}):null,a.source==="template"?e.jsx(hp,{templates:s,draft:a,onDraftChange:r}):null,a.source==="research"?e.jsx(qi,{id:"tracking-research-source",label:"Saved research query",value:a.researchRunQueryId,options:t.savedSources.research.map(m=>({id:m.researchRunQueryId,label:m.queryText,detail:m.researchRunId})),onChange:m=>r({...a,researchRunQueryId:m})}):null,a.source==="discovery"?e.jsx(qi,{id:"tracking-discovery-source",label:"Discovery query",value:a.discoveryProbeId,options:t.savedSources.discovery.map(m=>({id:m.discoveryProbeId,label:m.queryText,detail:m.discoverySessionId})),onChange:m=>r({...a,discoveryProbeId:m})}):null,e.jsxs("label",{className:"block",htmlFor:"tracking-query-source",children:[e.jsx("span",{className:"text-sm font-medium text-secondary",children:"Query source"}),e.jsxs("select",{id:"tracking-query-source",className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:a.source,onChange:m=>r({...a,source:m.target.value}),children:[e.jsx("option",{value:"manual",children:"Write a question"}),e.jsxs("option",{value:"template",disabled:s.length===0,children:["Saved template",s.length===0?" (none available)":""]}),e.jsxs("option",{value:"research",disabled:t.savedSources.research.length===0,children:["Saved research",t.savedSources.research.length===0?" (none available)":""]}),e.jsxs("option",{value:"discovery",disabled:t.savedSources.discovery.length===0,children:["Discovery result",t.savedSources.discovery.length===0?" (none available)":""]})]})]})]}),e.jsx(pp,{workspace:t,draft:a,onDraftChange:r})]}),t.mode==="advanced"&&!Mr(a)?e.jsx("div",{className:"mt-4",children:e.jsx(xp,{workspace:t,draft:a,onDraftChange:r})}):null,e.jsxs("details",{className:"mt-4 border-t border-default text-sm text-secondary",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3",children:"Measurement options"}),e.jsx("div",{className:"grid gap-4 pb-3 sm:grid-cols-2",children:t.mode==="advanced"?e.jsxs("div",{className:"block",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",htmlFor:"tracking-query-class",children:"Classification"}),e.jsxs("select",{id:"tracking-query-class",className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:a.queryClass,onChange:m=>r({...a,queryClass:m.target.value}),children:[e.jsx("option",{value:"auto",children:"Automatic"}),e.jsx("option",{value:"branded",children:"Branded"}),e.jsx("option",{value:"non-brand",children:"Non-brand"})]})]}):e.jsxs("div",{className:"rounded-md border border-default bg-surface-subtle px-3 py-2",children:[e.jsx("p",{className:"text-xs font-medium text-secondary",children:"Classification"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:"Automatic"})]})})]}),a.source==="research"&&e.jsx("p",{className:"mt-4 rounded-md border border-default bg-surface-subtle px-3 py-2 text-sm text-secondary",children:"Only the saved query is added."}),e.jsx(Xa,{canReview:i,isPreviewing:c,onCancel:o,onReview:h})]})}function hp({templates:t,draft:s,onDraftChange:n}){return e.jsxs("div",{children:[e.jsxs("label",{className:"block",htmlFor:"tracking-template-source",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Saved template"}),e.jsxs("select",{id:"tracking-template-source","aria-describedby":Cr(s)?"tracking-template-market-required":void 0,className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:s.templateId,onChange:a=>{const r=t.find(o=>o.id===a.target.value);n({...s,templateId:r?.id??"",templateVersion:r?.updatedAt??"",template:r?.pattern??""})},children:[e.jsx("option",{value:"",children:"Choose a template"}),t.map(a=>e.jsx("option",{value:a.id,children:a.name},a.id))]}),s.template?e.jsx("span",{className:"mt-1 block text-xs leading-5 text-muted",children:s.template}):null]}),Cr(s)?e.jsx("p",{id:"tracking-template-market-required",role:"status",className:"mt-2 text-sm leading-5 text-caution",children:"Choose a Market under Apply to for this template. A location alone does not select a market."}):null]})}function qi({id:t,label:s,value:n,options:a,onChange:r}){return e.jsxs("label",{className:"block",htmlFor:t,children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:s}),e.jsxs("select",{id:t,className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:n,onChange:o=>r(o.target.value),children:[e.jsx("option",{value:"",children:"Choose a saved query"}),a.map(o=>e.jsxs("option",{value:o.id,children:[o.label," · ",o.detail]},o.id))]})]})}function Lr(t){return{providers:[...t.providers],models:{...t.models},location:t.location?.label??null}}function Dn(t){return JSON.stringify({providers:[...t.providers].sort(),models:Object.fromEntries(Object.entries(t.models).sort(([s],[n])=>s.localeCompare(n))),location:t.location})}function ll(t){return[...new Map(t.map(s=>[Dn(s),s])).values()]}function Er(t){const s=t.providers.map(n=>{const a=t.models[n];return a?`${n} (${a})`:n}).join(", ");return`${t.location??"No location"} · ${s}`}function xp({workspace:t,draft:s,onDraftChange:n}){const a=l.useMemo(()=>ll([...t.defaultContexts.map(Lr),...s.contexts]),[s.contexts,t.defaultContexts]),r=s.contexts.length===1?Dn(s.contexts[0]):s.contexts.length>1?"__existing__":"";return e.jsxs("label",{className:"block",htmlFor:"tracking-query-context",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Location and engines"}),e.jsxs("select",{id:"tracking-query-context","aria-label":"Location and engines",className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:r,onChange:o=>{const i=a.find(u=>Dn(u)===o.target.value),c=o.target.value==="__existing__"?s.contexts:i?[i]:[];n({...s,contexts:c})},children:[e.jsx("option",{value:"",children:"Choose a location and engines"}),s.contexts.length>1?e.jsxs("option",{value:"__existing__",children:["Keep ",s.contexts.length," existing contexts"]}):null,a.map(o=>e.jsx("option",{value:Dn(o),children:Er(o)},Dn(o)))]}),e.jsx("span",{className:"mt-1 block text-xs leading-5 text-secondary",children:a.length===0?"No configured measurement context is available.":"Choose where this query will be measured."})]})}function pp({workspace:t,draft:s,onDraftChange:n}){const[a,r]=l.useState(""),[o,i]=l.useState(()=>s.wholeSite||s.targetKeys.length!==1||s.groupKeys.length>0||s.marketKeys.length>0),c=l.useMemo(()=>[...t.targets.map(d=>({kind:"target",key:d.stableKey,label:d.label,detail:"Property"})),...t.groups.map(d=>({kind:"group",key:d.stableKey,label:d.label,detail:"Group"})),...t.markets.map(d=>({kind:"market",key:d.stableKey,label:d.label,detail:"Market"}))],[t.groups,t.markets,t.targets]),u=a.trim().toLocaleLowerCase(),h=u?c.filter(d=>`${d.label} ${d.detail}`.toLocaleLowerCase().includes(u)):c,m=s.targetKeys.length+s.groupKeys.length+s.marketKeys.length>0;function x(d,f,y){const j=d==="target"?"targetKeys":d==="group"?"groupKeys":"marketKeys",N=s[j];n({...s,wholeSite:!1,[j]:y?[...N,f]:N.filter(P=>P!==f)})}function g(d,f){return(d==="target"?s.targetKeys:d==="group"?s.groupKeys:s.marketKeys).includes(f)}if(!o){const d=t.targets.find(f=>f.stableKey===s.targetKeys[0]);return e.jsxs("fieldset",{className:"self-start rounded-md border border-default bg-surface-subtle p-3",children:[e.jsx("legend",{className:"px-1 text-xs font-medium text-secondary",children:"Apply to"}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("p",{className:"text-sm text-strong",children:["Property: ",d?.label??s.targetKeys[0]]}),e.jsx(A,{type:"button",variant:"ghost",size:"sm","aria-label":"Change tracking destination",onClick:()=>i(!0),children:"Change"})]})]})}return e.jsxs("fieldset",{className:"rounded-md border border-default bg-surface-subtle p-3",children:[e.jsx("legend",{className:"px-1 text-xs font-medium text-secondary",children:"Apply to"}),e.jsx("p",{className:"text-sm leading-6 text-secondary",children:"Choose where this question should be tracked."}),e.jsxs("label",{className:"mt-3 flex min-h-9 items-center gap-2 rounded px-1 text-sm text-strong",children:[e.jsx("input",{type:"checkbox",checked:s.wholeSite,onChange:d=>{n({...s,wholeSite:d.target.checked,targetKeys:[],groupKeys:[],marketKeys:[]})}}),"Whole site"]}),!s.wholeSite&&!m?e.jsx("p",{role:"status",className:"mt-2 text-sm text-caution",children:"Choose Whole site or at least one property, group, or market."}):null,e.jsx("p",{className:"mt-2 text-sm leading-5 text-secondary",children:"Group: properties grouped together. Market: search context."}),e.jsx(Us,{value:a,onChange:r,label:"Filter assignments",placeholder:"Search Properties, Groups, Markets",className:"mt-3"}),e.jsx("div",{className:"mt-3 max-h-64 space-y-1 overflow-y-auto pr-1",children:h.length===0?e.jsx("p",{className:"px-1 py-2 text-sm text-muted",children:"No assignment matches that search."}):h.map(d=>e.jsxs("label",{className:"flex min-h-9 items-center gap-2 rounded px-1 py-1 text-sm text-strong hover:bg-surface-hover",children:[e.jsx("input",{type:"checkbox","aria-label":`${d.label}, ${d.detail}`,checked:g(d.kind,d.key),onChange:f=>x(d.kind,d.key,f.target.checked)}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:d.label}),e.jsx("span",{className:"text-xs text-muted",children:d.detail})]},`${d.kind}:${d.key}`))})]})}function Xa({canReview:t,isPreviewing:s,onCancel:n,onReview:a}){return e.jsxs("div",{className:"mt-5 flex flex-wrap items-center gap-3 border-t border-default pt-4",children:[e.jsx(De,{type:"button",size:"sm",disabled:!t,onClick:a,children:s?"Reviewing…":"Review changes"}),e.jsx(A,{type:"button",variant:"ghost",size:"sm",onClick:n,children:"Cancel"}),e.jsx("p",{className:"text-sm leading-5 text-secondary",children:"Publishing does not run a sweep."})]})}function gp({preview:t,workspace:s,isCommitting:n,onConfirm:a}){const r=l.useRef(null);l.useEffect(()=>{const c=r.current;c&&(typeof c.scrollIntoView=="function"&&c.scrollIntoView({block:"start"}),c.focus({preventScroll:!0}))},[t]);const o=!t.diff.noOp,i=[{label:"Added",rows:t.diff.added},{label:"Removed",rows:t.diff.removed},{label:"Reused",rows:t.diff.reused}].filter(c=>c.rows.length>0);return e.jsxs(xe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{ref:r,tabIndex:-1,children:o?"Confirm tracked query changes":"No tracking changes"}),e.jsx("p",{className:"mt-1 text-sm leading-6 text-secondary",children:o?"Changes apply to future sweeps. Earlier results stay unchanged.":"This request leaves tracking unchanged."})]}),e.jsx(ce,{tone:o?"caution":"neutral",children:o?"Ready to confirm":"No-op"})]}),i.length>0?e.jsx("div",{className:"mt-4 space-y-4",children:i.map(c=>e.jsx(Di,{label:c.label,rows:c.rows,workspace:s,tracked:t.tracked},c.label))}):null,t.diff.unchanged.length>0?e.jsxs("details",{className:"mt-4 border-t border-default pt-2 text-sm text-secondary",children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-3",children:[t.diff.unchanged.length," unchanged ",t.diff.unchanged.length===1?"query":"queries"]}),e.jsx(Di,{label:"Unchanged",rows:t.diff.unchanged,workspace:s,tracked:t.tracked})]}):null,e.jsxs("details",{className:"mt-4 border-t border-default text-sm text-secondary",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3",children:"Next sweep workload"}),e.jsxs("p",{className:"leading-6",children:["Next sweep: ",t.workload.nextSweepProviderCalls," provider requests (+",t.workload.addedProviderCalls,", −",t.workload.removedProviderCalls,")."]})]}),e.jsx("div",{className:"mt-5 flex flex-wrap items-center gap-3 border-t border-default pt-4",children:e.jsx(De,{type:"button",size:"sm",disabled:!o||n,onClick:a,children:n?"Confirming…":"Confirm changes"})})]})}function Di({label:t,rows:s,workspace:n,tracked:a}){return e.jsxs("section",{"aria-label":`${t} queries`,children:[e.jsxs("p",{className:"text-xs font-medium text-secondary",children:[s.length," ",t.toLocaleLowerCase(),s.length===1?"":"s"]}),e.jsx("ul",{className:"mt-2 divide-y divide-default",children:s.map(r=>e.jsxs("li",{className:"py-2 text-sm",children:[e.jsx("p",{className:"font-medium text-strong",children:r.queryText}),e.jsx("p",{className:"mt-1 text-secondary",children:t==="Removed"?`${r.assignmentCount} ${r.assignmentCount===1?"assignment":"assignments"} removed`:yp(r,a,n)}),t==="Added"||t==="Reused"?e.jsx(fp,{row:a.find(o=>o.queryId===r.queryId),workspace:n}):null]},`${t}:${r.queryId}`))})]})}function fp({row:t,workspace:s}){if(!t?.assignments.length)return null;const n=new Set(t.assignments.map(a=>a.targetKey)).size;return e.jsxs("details",{className:"mt-2 text-secondary",children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-3 font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500",children:["Classifications · ",n," ",n===1?"property":"properties"]}),e.jsx("ul",{className:"mt-1 max-h-40 space-y-1 overflow-y-auto",children:t.assignments.map((a,r)=>{const o=s.targets.find(u=>u.stableKey===a.targetKey)?.label??a.targetKey,i=a.queryClass==="branded"?"Branded":a.queryClass==="non-brand"?"Non-brand":"Unknown",c=a.contexts.map(u=>Er(Lr(u))).join("; ");return e.jsx("li",{children:[o,i,c].filter(Boolean).join(" · ")},`${a.targetKey}:${r}`)})})]})}function yp(t,s,n){const a=s.find(i=>i.queryId===t.queryId);if(!a)return`${t.assignmentCount} ${t.assignmentCount===1?"assignment":"assignments"}`;const r=ll(a.assignments.flatMap(i=>i.contexts).map(Lr)),o=r.length===1?Er(r[0]):r.length>1?`${r.length} contexts`:null;return[ol(a,n),o].filter(i=>i!==null).join(" · ")}function bp({projectName:t,selection:s={measurementScope:"project",queryClass:"all"},onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:o,onPendingTrackingSourceHandled:i}){const c=js(),[u,h]=l.useState(null),m=we({...Po({client:H,path:{name:t}})}),x=we({...qc({client:H,path:{name:t}}),staleTime:6e4}),g=Pt({...Oc(),onSuccess:f=>h(f),onError:async f=>{h(null),await c.invalidateQueries({queryKey:Dc({client:H,path:{name:t}})}),Se({title:"Could not review tracking changes",detail:f instanceof Error?f.message:"Update the draft and review it again.",tone:"negative"})}}),d=Pt({...Fc(),onSuccess:async f=>{h(null),r?.(void 0),await ti(c,t),Se({title:f.committed?"Tracked queries updated":"No tracked-query change",detail:f.active?`Measurement revision ${f.active.revision}.`:"No measurement revision is published yet.",tone:f.committed?"positive":"neutral",dedupeKey:`query-tracking:commit:${t}`,dedupeMode:"replace"})},onError:async f=>{h(null),await ti(c,t),Se({title:"Could not confirm tracking changes",detail:f instanceof Error?f.message:"The review may be stale. Review the changes again.",tone:"negative"})}});return m.isLoading?e.jsx(xe,{className:"surface-card",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading tracked queries…"})}):m.isError||!m.data?e.jsxs(xe,{className:"surface-card",children:[e.jsx("p",{className:"text-sm text-negative",children:"Could not load tracked queries."}),e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:()=>{m.refetch()},children:"Try again"})]}):e.jsx(sp,{workspace:m.data,selection:s,onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:o,onPendingTrackingSourceHandled:i,templates:x.data?.templates??[],preview:u,isPreviewing:g.isPending,isCommitting:d.isPending,onPreview:f=>{h(null),g.mutate({client:H,path:{name:t},body:{...f,expectedWorkspaceVersion:m.data.workspaceVersion}})},onCommit:f=>d.mutate({client:H,path:{name:t},body:f})})}function vp({projectName:t,onReviewDiscoveryProbe:s}){const n=js(),[a,r]=l.useState(null),[o,i]=l.useState(""),[c,u]=l.useState("100"),h=we({...Gc({client:H,path:{name:t},query:{limit:"10"}}),refetchInterval:P=>P.state.data?.some(k=>Sr.has(k.status))?3e3:!1}),m=h.data??[];l.useEffect(()=>{!a&&m[0]&&r(m[0].id)},[a,m]);const x=m.find(P=>P.id===a)??null,g=we({...Kc({client:H,path:{name:t,id:a??""}}),enabled:!!a,refetchInterval:x&&Sr.has(x.status)?3e3:!1}),d=g.data??null,f=Pt({mutationFn:()=>{const P={},M=o.trim();M&&(P.icpDescription=M);const k=Number.parseInt(c,10);return Number.isFinite(k)&&k>0&&(P.maxProbes=k),_c(t,P)},onSuccess:async P=>{r(P.sessionId),i(""),await Sp(n,t,P.sessionId),Se({title:"Discovery started",detail:`Run ${Za(P.sessionId)} is testing questions your customers might ask.`,tone:"neutral",dedupeKey:`discovery:start:${P.sessionId}`,dedupeMode:"replace"})},onError:P=>{Se({title:"Discovery failed to start",detail:P instanceof Error?P.message:"Could not start discovery.",tone:"negative"})}}),y=d??x,j=l.useMemo(()=>(d?.probes??[]).slice(0,30),[d?.probes]);async function N(){try{const P=await h.refetch();if(P.error)throw P.error;const M=P.data?.length??0;Se({title:"Discovery sessions refreshed",detail:`${M} recent session${M===1?"":"s"} loaded.`,tone:"positive",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}catch(P){Se({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:te()?"Generate customer questions and check whether your site is already visible.":"Generate customer questions, check current visibility, then choose what to track."})]}),e.jsxs(A,{type:"button",variant:"outline",size:"sm",disabled:h.isFetching,onClick:()=>{N()},children:[e.jsx(Na,{className:`size-3.5 ${h.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(xe,{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(ce,{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:o,onChange:P=>i(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:c,onChange:P=>u(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."})]}),!te()&&e.jsxs(De,{type:"button",size:"sm",disabled:f.isPending,onClick:()=>f.mutate(),children:[e.jsx(Un,{size:14}),f.isPending?"Starting…":"Find queries"]})]})]}),e.jsxs(xe,{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"})]}),h.isFetching&&e.jsx(ce,{tone:"neutral",children:"Loading"})]}),m.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:m.map(P=>e.jsxs("button",{type:"button",className:`w-full rounded-md border px-3 py-2 text-left transition-colors ${a===P.id?"border-mono-600 bg-bg-elevated/70":"border-default bg-bg/40 hover:border-strong hover:bg-bg-elevated/40"}`,onClick:()=>r(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:Za(P.id)}),e.jsx(ce,{tone:Oi(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(xe,{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:y?Za(y.id):"No run selected"})]}),y&&e.jsx(ce,{tone:Oi(y.status),children:y.status})]}),y?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(ra,{label:"Questions tested",value:y.probeCount??0}),e.jsx(ra,{label:"Cited queries",value:y.citedCount??0,tone:"positive"}),e.jsx(ra,{label:"Worth tracking",value:y.aspirationalCount??0,tone:"caution"}),e.jsx(ra,{label:"Skip",value:y.wastedCount??0,tone:"negative"})]}),y.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:y.error}),y.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:y.warning}),y.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:y.icpDescription})]}),y.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:y.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."})]}),y?.status==="completed"&&e.jsxs(xe,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 2"}),e.jsx("h3",{children:"Review a discovery question for tracking"}),e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-secondary",children:"Choose a Cited query or Worth tracking result below. Tracking opens with the saved discovery source, where you choose its scope and review the exact next-sweep change."})]})}),e.jsx("p",{className:"mt-3 text-xs leading-5 text-muted",children:"Discovery remains research. This review does not add competitors or start a sweep."})]}),e.jsxs(xe,{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"})]}),g.isFetching&&e.jsx(ce,{tone:"neutral",children:"Loading"})]}),j.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("th",{children:e.jsx("span",{className:"sr-only",children:"Tracking review"})})]})}),e.jsx("tbody",{children:j.map(P=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:P.query}),e.jsx("td",{children:e.jsx(ce,{tone:jp(P.bucket),children:wp(P.bucket)})}),e.jsx("td",{className:"text-secondary",children:P.citedDomains.length>0?P.citedDomains.slice(0,3).join(", "):"-"}),e.jsx("td",{className:"whitespace-nowrap text-right",children:!te()&&s&&(P.bucket==="cited"||P.bucket==="aspirational")&&e.jsx(De,{type:"button",variant:"ghost",size:"sm",onClick:()=>s(P.id),children:"Review for tracking"})})]},P.id))})]})})]})]})]})]})}function ra({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 Oi(t){return t==="completed"?"positive":t==="failed"?"negative":Sr.has(t)?"caution":"neutral"}function jp(t){return t==="cited"?"positive":t==="aspirational"?"caution":t==="wasted-surface"?"negative":"neutral"}const Np={cited:"Cited queries",aspirational:"Worth tracking","wasted-surface":"Skip"};function wp(t){return t?Np[t]:"Not classified"}function Za(t){return t.length>8?t.slice(0,8):t}async function Sp(t,s,n){await Promise.all([Nt(t,"discovery"),t.invalidateQueries({queryKey:Uc({client:H})})])}function Fi(t){return`${(t*100).toFixed(1)}%`}function Cp({projectName:t}){const[s,n]=l.useState("changes"),[a,r]=l.useState(null),[o,i]=l.useState(null),c=we({...Bc({client:H,path:{name:t},query:{limit:30}}),enabled:s==="health"}),u=we({...Vc({client:H,path:{name:t},query:{kind:"answer-visibility",limit:100}}),enabled:s==="compare"}),h=(u.data??[]).filter(j=>(j.status==="completed"||j.status==="partial")&&j.trigger!=="probe").reverse(),m=o??h[0]?.id??"",x=a??h.find(j=>j.id!==m)?.id??"",g=!!(x&&m&&x!==m),d=we({...zc({client:H,path:{name:t},query:{run1:x,run2:m}}),enabled:s==="compare"&&g}),f=c.data??[],y=d.data?.diff.filter(j=>j.changed||j.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(([j,N])=>e.jsx("button",{type:"button",role:"tab","aria-selected":s===j,className:`filter-chip ${s===j?"filter-chip-active":""}`,onClick:()=>n(j),children:N},j))}),s==="changes"?e.jsx(fm,{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."})]}),c.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Loading coverage history…"}):null,!c.isLoading&&f.length===0?e.jsxs(xe,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No coverage history yet"}),e.jsx("p",{children:Vt()?Qs:"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(j=>e.jsxs("tr",{children:[e.jsx("td",{className:"whitespace-nowrap tabular-nums text-secondary",children:new Date(j.createdAt).toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[j.mentionedPairs,"/",j.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:Fi(j.overallMentionRate)}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[j.citedPairs,"/",j.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:Fi(j.overallCitedRate)})]},j.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:x,onChange:j=>r(j.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:h.map(j=>e.jsx("option",{value:j.id,children:new Date(j.createdAt).toLocaleString()},j.id))})]}),e.jsxs("label",{className:"text-xs text-muted",children:["Later run",e.jsx("select",{value:m,onChange:j=>i(j.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:h.map(j=>e.jsx("option",{value:j.id,children:new Date(j.createdAt).toLocaleString()},j.id))})]})]}),u.isLoading||d.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Comparing runs…"}):null,!u.isLoading&&h.length<2?e.jsxs(xe,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"Two completed sweeps are required"}),e.jsx("p",{children:Vt()?Qs:"Run another answer visibility sweep before comparing historical evidence."})]}):null,d.data&&y.length===0?e.jsxs(xe,{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,y.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:y.map(j=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:j.query??"Archived query"}),e.jsx("td",{children:e.jsxs(ce,{tone:j.changed?"caution":"neutral",children:[j.run1State??"none"," → ",j.run2State??"none"]})}),e.jsx("td",{children:e.jsxs(ce,{tone:j.visibilityChanged?"caution":"neutral",children:[j.run1MentionState??"none"," → ",j.run2MentionState??"none"]})})]},j.queryId??j.query??"unknown"))})]})}):null]}):null]})}const Gi={state:"not-connected",selection:null,snapshotCount:0,evidence:"No stored evidence yet.",lastSnapshotAt:null},kp={contract:null,assessment:null,googleAds:Gi,gtm:Gi,snapshots:[]};function Ap(t){return t.contractSelectionRequired?"contract-selection-required":t.assessmentState==="loading"?"assessment-loading":t.assessmentState==="unavailable"?"assessment-unavailable":$p(t)?"static-mismatch":t.assessment?.status??(t.contract?"configured":"not-configured")}function Pp(t){switch(t){case"configured":return{label:"Configured",detail:"The conversion is declared, but the static configuration is not yet proven consistent.",tone:"caution"};case"static-mismatch":return{label:"Static mismatch",detail:"Stored configuration does not match the declared conversion. Review the failing checks before relying on it.",tone:"negative"};case"statically-consistent":return{label:"Statically consistent",detail:"Stored Google Ads and Tag Manager configuration aligns with the declared conversion.",tone:"positive"};case"runtime-unverified":return{label:"Runtime verification needed",detail:"The stored configuration aligns, but a real browser event has not been observed.",tone:"caution"};case"observed":return{label:"Observed",detail:"Stored static evidence and a runtime observation support this conversion path.",tone:"positive"};case"not-configured":return{label:"Setup needed",detail:"Connect both providers, select their resources, then declare the conversion Canonry should inspect.",tone:"neutral"};case"contract-selection-required":return{label:"Choose conversion",detail:"Choose one of the declared conversions before Canonry evaluates its evidence.",tone:"neutral"};case"assessment-loading":return{label:"Checking configuration",detail:"Canonry is loading the selected conversion assessment.",tone:"neutral"};case"assessment-unavailable":return{label:"Assessment unavailable",detail:"The selected conversion could not be assessed. Retry before treating static evidence as current.",tone:"negative"}}}function Rp(t){switch(t.googleAds.state){case"not-connected":return{id:"connect-google-ads",label:"Connect Google Ads",detail:"Canonry only queries data; connect a Google Ads user with the Read-only role."};case"selection-required":return{id:"select-google-ads",label:"Select Google Ads account",detail:"Choose the customer account Canonry should inspect."};case"stale":return{id:"sync-google-ads",label:"Refresh Google Ads evidence",detail:"Read the selected account again and save a new sanitized observation."};default:return null}}function Ip(t){switch(t.gtm.state){case"not-connected":return{id:"connect-gtm",label:"Connect Google Tag Manager",detail:"Authorize read-only Tag Manager access for this project."};case"selection-required":return{id:"select-gtm",label:"Select Tag Manager container",detail:"Choose the account and container Canonry should inspect."};case"stale":return{id:"sync-gtm",label:"Refresh Tag Manager evidence",detail:"Read the selected container again and save a new sanitized observation."};default:return null}}function cl(t){return t.googleAds.state==="not-connected"?{id:"connect-google-ads",label:"Connect Google Ads",detail:"Canonry only queries data; connect a Google Ads user with the Read-only role."}:t.googleAds.state==="unavailable"||t.gtm.state==="unavailable"?{id:"retry-connection-status",label:"Retry connection status",detail:"Retry the stored connection reads before starting another provider action."}:t.googleAds.state==="selection-required"?{id:"select-google-ads",label:"Select Google Ads account",detail:"Choose the customer account Canonry should inspect."}:t.googleAds.state==="stale"?{id:"sync-google-ads",label:"Refresh Google Ads evidence",detail:"Read the selected account again and save a new sanitized observation."}:t.gtm.state==="not-connected"?{id:"connect-gtm",label:"Connect Google Tag Manager",detail:"Authorize read-only Tag Manager access for this project."}:t.gtm.state==="selection-required"?{id:"select-gtm",label:"Select Tag Manager container",detail:"Choose the account and container Canonry should inspect."}:t.gtm.state==="stale"?{id:"sync-gtm",label:"Refresh Tag Manager evidence",detail:"Read the selected container again and save a new sanitized observation."}:t.contractSelectionRequired?{id:"select-contract",label:"Select conversion",detail:"Choose the declared conversion Canonry should assess."}:t.contract?t.assessmentState==="loading"?{id:"waiting-for-integrity",label:"Checking configuration…",detail:"Canonry is loading the selected conversion assessment."}:t.assessmentState==="unavailable"?{id:"retry-integrity",label:"Retry assessment",detail:"Retry the selected conversion assessment before acting on its evidence."}:t.assessment?.status==="runtime-unverified"?{id:"review-runtime-verification",label:"Review runtime verification",detail:"Static configuration is aligned. Verify a real browser event separately."}:t.assessment?.status==="configured"&&Tp(t)?{id:"review-findings",label:"Review findings",detail:"Resolve the mismatched or unknown checks before treating this conversion as ready."}:{id:"sync-static-evidence",label:"Refresh static evidence",detail:"Queue fresh read-only Google Ads and Tag Manager observations."}:{id:"declare-contract",label:"Declare conversion",detail:"Name the website event, Google Ads action, and Tag Manager tag that must agree."}}function $p(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome==="fail")}function Tp(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome!=="pass")}function dl(t){switch(t){case"connected":return{label:"Connected",tone:"positive"};case"stale":return{label:"Needs refresh",tone:"caution"};case"selection-required":return{label:"Selection needed",tone:"caution"};case"not-connected":return{label:"Not connected",tone:"neutral"};case"unavailable":return{label:"Unavailable",tone:"negative"}}}function Mp(t,s){return t==="configured"?s==="not-configured"||s==="contract-selection-required"?"neutral":"positive":t==="static"?s==="assessment-unavailable"?"negative":s==="assessment-loading"?"neutral":s==="static-mismatch"?"negative":s==="statically-consistent"||s==="runtime-unverified"||s==="observed"?"positive":s==="configured"?"caution":"neutral":s==="observed"?"positive":s==="runtime-unverified"?"caution":"neutral"}function Lp(t,s){return t==="configured"?s==="not-configured"?"Not declared":s==="contract-selection-required"?"Choose conversion":"Declared":t==="static"?s==="assessment-unavailable"?"Unavailable":s==="assessment-loading"?"Checking":s==="static-mismatch"?"Mismatch":s==="statically-consistent"||s==="runtime-unverified"||s==="observed"?"Consistent":s==="configured"?"Needs review":"Not checked":s==="observed"?"Observed":s==="runtime-unverified"?"Not observed":"Not checked"}function nn(t){return t.length<=12?t:`…${t.slice(-10)}`}function Ep(t){const s=[];return t.googleAds.requirePrimaryAction&&s.push("primary action"),t.googleAds.requireBiddableGoal&&s.push("biddable goal"),s.length>0?s.join(" and "):"No bidding-goal assertion"}function qp(t){const s=[];return t.runtime.requireTransactionId&&s.push("transaction ID"),t.runtime.requireValue&&s.push("value"),t.runtime.requireCurrency&&s.push("currency"),s.length>0?s.join(", "):"No additional event fields required"}const er={"ads-connection-missing":"Google Ads connection is available","ads-conversion-action-missing":"Google Ads conversion action exists and is enabled","ads-goal-missing":"Google Ads goal includes the conversion action","ads-goal-not-biddable":"Google Ads goal is available for bidding","ads-action-not-primary":"Google Ads action is primary","gtm-connection-missing":"Tag Manager connection is available","gtm-live-graph-missing":"Tag Manager configuration is available","gtm-tag-missing":"Required Tag Manager tag exists","gtm-tag-unrecognized":"Tag Manager tag type is supported","gtm-tag-paused":"Tag Manager tag is active","gtm-trigger-missing":"Required Tag Manager trigger is linked","gtm-variable-missing":"Required Tag Manager variable is linked","gtm-event-mismatch":"Tag Manager event matches the declaration","gtm-hostname-mismatch":"Tag Manager host matches the production site","gtm-value-mapping-missing":"Conversion value mapping is present","gtm-transaction-id-mapping-missing":"Transaction ID mapping is present","gtm-currency-mapping-missing":"Currency mapping is present","gtm-conversion-id-mismatch":"Google conversion ID matches","gtm-conversion-label-mismatch":"Google conversion label matches","runtime-event-not-observed":"Website event was observed","runtime-gtm-not-observed":"Tag Manager firing was observed","runtime-ads-not-observed":"Google Ads conversion was observed"};function Ki(t){return t.outcome==="pass"?{label:er[t.code],tone:"positive",outcome:"Pass"}:t.outcome==="fail"?{label:er[t.code],tone:"negative",outcome:"Fail"}:{label:er[t.code],tone:"caution",outcome:"Unknown"}}function Dp(t){return t.runtime.productionHosts.length>0?t.runtime.productionHosts.join(", "):"the declared production site"}function Op(t){const s=[];return t.runtime.requireTransactionId&&s.push("transaction ID"),t.runtime.requireValue&&s.push("conversion value"),t.runtime.requireCurrency&&s.push("currency"),s.length>0?s.join(", "):"no additional event fields"}function Fp(t){return t.provider==="google-ads"?"Google Ads":"Tag Manager"}function _i({label:t,connection:s,changeSelectionLabel:n,onChangeSelection:a,actionPending:r}){const o=dl(s.state),i=s.snapshotState==="loading"?"Loading stored snapshots":s.snapshotState==="unavailable"?"Stored snapshots unavailable":s.snapshotCount===0?"No stored snapshots":null;return e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:t}),e.jsx("td",{children:e.jsx(ce,{tone:o.tone,children:o.label})}),e.jsx("td",{className:"text-secondary",children:s.selection??"No selection"}),e.jsxs("td",{children:[e.jsx("p",{className:"text-secondary",children:s.evidence}),i?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:i}):e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:[s.snapshotCount," stored ",s.snapshotCount===1?"snapshot":"snapshots",s.lastSnapshotAt?`, latest ${Bt(s.lastSnapshotAt)}`:""]}),s.snapshotError?e.jsx("p",{role:"alert",className:"mt-1 text-sm text-negative",children:s.snapshotError}):null]}),e.jsx("td",{children:n&&a?e.jsx(De,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:a,children:n}):e.jsx("span",{className:"text-sm text-secondary",children:"Use the next step above"})})]})}const Gp="A conversion names the website event, the Google Ads conversion action, and the Tag Manager tag that must agree. It needs both connections selected because it references resources from each.",Kp="Available once Google Ads and Tag Manager are connected.",_p="Check that a conversion is wired the same way in Google Ads and Tag Manager, so the numbers you optimise against are the ones your site actually sends. Canonry only reads the configuration; it never changes or publishes it.";function Up({workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:n,onChangeGtmSelection:a,actionPending:r,actionError:o}){const i=t.googleAds.state==="connected",c=t.gtm.state==="connected",u=t.googleAds.state==="unavailable",h=t.gtm.state==="unavailable",m=u||h||t.gtm.state==="unavailable",x={id:"retry-connection-status",label:"Retry connection status",detail:"Retry the stored connection reads before starting another provider action."},g=!i&&!c,d=[{title:"Google Ads",state:t.googleAds.state,ready:i,summary:t.googleAds.selection,changeLabel:"Change Google Ads account",onChange:n,action:u?x:Rp(t)},{title:"Tag Manager",state:t.gtm.state,ready:c,summary:t.gtm.selection,changeLabel:"Change Tag Manager container",onChange:a,action:h?x:Ip(t)}],f=i&&c&&!m?cl(t):null;return e.jsxs("section",{className:"page-section","aria-labelledby":"conversion-integrity-title",children:[e.jsx("div",{className:"section-head mb-4",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx("h2",{id:"conversion-integrity-title",className:"text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsx(Me,{text:"Canonry reads your Google configuration and never changes or publishes it. Connect Google Ads and Tag Manager, then choose one website conversion to check across both."})]}),g?e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-secondary",children:_p}):null]})}),e.jsxs("div",{className:"max-w-3xl",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 border-y border-default py-4",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Conversion to check"}),e.jsx(Me,{text:Gp})]}),f&&s?e.jsx(De,{type:"button",disabled:r,onClick:()=>s(f.id),children:r?"Working…":f.label}):e.jsx("p",{className:"text-sm text-secondary",children:Kp})]}),e.jsx("ul",{className:"flex flex-wrap items-center gap-x-6 gap-y-2 border-b border-default py-3",children:d.map(y=>{const j=y.ready?{label:"Ready",tone:"positive"}:dl(y.state),N=y.action;return e.jsxs("li",{className:"flex min-w-0 flex-wrap items-center gap-2 text-sm",children:[e.jsx("span",{className:"font-medium text-heading",children:y.title}),e.jsx(ce,{tone:j.tone,children:j.label}),y.summary?e.jsx("span",{className:"min-w-0 truncate text-secondary",children:y.summary}):null,N&&s?N.id==="retry-connection-status"?e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(N.id),children:r?"Working…":N.label}):e.jsx(De,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(N.id),children:r?"Working…":N.label}):null,y.summary&&y.onChange?e.jsx(De,{type:"button",variant:"ghost",size:"sm","aria-label":y.changeLabel,disabled:r,onClick:y.onChange,children:"Change"}):null]},y.title)})}),o?e.jsx("p",{role:"alert",className:"mt-3 text-sm text-negative",children:o}):null]})]})}function Bp({workspace:t=kp,onPrimaryAction:s,actionPending:n=!1,actionError:a=null,contracts:r=[],selectedContractId:o=null,onSelectContract:i,contractError:c=null,onRetryContracts:u,onRetryEvidence:h,onChangeGoogleAdsSelection:m,onChangeGtmSelection:x,onAddContract:g}){const d=Ap(t),f=Pp(d),y=cl(t),j=t.assessment?.findings??[],N=j.filter(p=>p.outcome!=="pass"),P=j.filter(p=>p.outcome==="pass"),M=N.some(p=>p.outcome==="fail")?"negative":"caution";return r.length===0&&t.contract===null&&!t.contractSelectionRequired&&c===null?e.jsx(Up,{workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:m,onChangeGtmSelection:x,actionPending:n,actionError:a}):e.jsxs("section",{className:"page-section","aria-labelledby":"conversion-integrity-title",children:[e.jsx("div",{className:"section-head mb-5",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsx("h2",{id:"conversion-integrity-title",className:"mt-1 text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsx("p",{className:"lede mt-2",children:"Follow one declared website event through Tag Manager, Google Ads, and the evidence Canonry can verify."})]})}),e.jsxs("div",{className:"flex flex-col gap-4 border-y border-default py-5 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(ce,{tone:f.tone,children:f.label}),t.assessment?.evaluatedAt?e.jsxs("span",{className:"text-[11px] text-muted",children:["Assessed ",Bt(t.assessment.evaluatedAt)]}):null]}),e.jsx("p",{className:"supporting-copy mt-2 max-w-2xl",children:f.detail}),t.assessmentEvidenceSnapshots?.length?e.jsxs("details",{className:"inline-disclosure mt-3 max-w-2xl",children:[e.jsx("summary",{children:"Evidence used for this assessment"}),e.jsx("ul",{className:"mt-3 space-y-2 text-sm leading-6 text-secondary",children:t.assessmentEvidenceSnapshots.map(p=>e.jsxs("li",{className:"break-words",children:[Fp(p)," ",p.kind,", captured ",Bt(p.capturedAt),e.jsxs("span",{className:"ml-1 font-mono text-[11px] text-muted",children:["(",p.id,")"]})]},p.id))})]}):null]}),e.jsxs("div",{className:"shrink-0 lg:max-w-xs",children:[s?y.id==="review-findings"||y.id==="review-runtime-verification"||y.id==="retry-connection-status"||y.id==="select-contract"||y.id==="retry-integrity"||y.id==="waiting-for-integrity"?e.jsx(A,{type:"button",disabled:n||y.id==="waiting-for-integrity",onClick:()=>s(y.id),children:n?"Working…":y.label}):e.jsx(De,{type:"button",disabled:n,onClick:()=>s(y.id),children:n?"Working…":y.label}):y.id==="review-findings"?e.jsx(A,{asChild:!0,type:"button",children:e.jsx("a",{href:"#conversion-integrity-findings",children:"Review findings"})}):d==="runtime-unverified"?e.jsx(A,{asChild:!0,type:"button",children:e.jsx("a",{href:"#conversion-integrity-runtime-guidance",children:"Review runtime verification"})}):null,e.jsx("p",{className:"mt-2 text-sm leading-5 text-secondary",children:y.detail}),a?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:a}):null]})]}),e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-contract-title",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Declared conversion"}),e.jsx("h3",{id:"conversion-integrity-contract-title",className:"min-w-0 break-words text-base font-semibold text-heading",children:t.contract?.name??(t.contractSelectionRequired?"Choose a conversion":"No conversion declared")})]}),r.length>0&&g?e.jsx(De,{type:"button",variant:"outline",size:"sm",disabled:n,onClick:g,children:"Add conversion"}):null]}),r.length>1?e.jsxs("label",{htmlFor:"conversion-integrity-contract-select",className:"mb-5 block max-w-xl text-sm font-medium text-secondary",children:["Conversion to inspect",e.jsxs("select",{id:"conversion-integrity-contract-select",className:"mt-1 w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-heading outline-none transition-colors focus:border-mono-500 focus:ring-2 focus:ring-mono-500/30",value:o??"",onChange:p=>i?.(p.target.value),children:[e.jsx("option",{value:"",children:"Choose a declared conversion"}),r.map(p=>e.jsx("option",{value:p.id,children:p.name},p.id))]})]}):null,t.contract?e.jsxs(e.Fragment,{children:[e.jsxs("dl",{className:"grid gap-x-8 gap-y-4 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-[11px] font-medium uppercase tracking-[0.14em] text-muted",children:"Website event"}),e.jsx("dd",{className:"mt-1 text-sm font-medium text-heading",children:t.contract.eventName})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[11px] font-medium uppercase tracking-[0.14em] text-muted",children:"Google Ads goal"}),e.jsx("dd",{className:"mt-1 text-sm text-secondary",children:Ep(t.contract)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[11px] font-medium uppercase tracking-[0.14em] text-muted",children:"Tag Manager"}),e.jsxs("dd",{className:"mt-1 text-sm text-secondary",children:[t.contract.gtm.triggerIds.length," ",t.contract.gtm.triggerIds.length===1?"trigger":"triggers"," and ",t.contract.gtm.variableIds.length," ",t.contract.gtm.variableIds.length===1?"variable":"variables"," required"]})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[11px] font-medium uppercase tracking-[0.14em] text-muted",children:"Runtime event fields"}),e.jsx("dd",{className:"mt-1 text-sm text-secondary",children:qp(t.contract)})]})]}),e.jsxs("details",{className:"inline-disclosure mt-5",children:[e.jsx("summary",{children:"Show declared identifiers"}),e.jsxs("dl",{className:"mt-3 grid gap-x-6 gap-y-3 text-sm sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-muted",children:"Google Ads customer"}),e.jsx("dd",{className:"mt-0.5 font-mono text-secondary",children:nn(t.contract.googleAds.customerId)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-muted",children:"Google Ads conversion action"}),e.jsx("dd",{className:"mt-0.5 font-mono text-secondary",children:nn(t.contract.googleAds.conversionActionId)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-muted",children:"Tag Manager container"}),e.jsx("dd",{className:"mt-0.5 font-mono text-secondary",children:nn(t.contract.gtm.containerId)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-muted",children:"Tag Manager tag"}),e.jsx("dd",{className:"mt-0.5 font-mono text-secondary",children:nn(t.contract.gtm.tagId)})]})]})]})]}):e.jsx("p",{className:"supporting-copy max-w-2xl",children:t.contractSelectionRequired?"Choose a declared conversion before Canonry evaluates the configuration.":"A contract makes the expected event and provider identifiers explicit before Canonry evaluates the configuration."}),c?e.jsxs("div",{role:"alert",className:"mt-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:c}),u?e.jsx(A,{type:"button",variant:"outline",onClick:u,children:"Retry contracts"}):null]}):null,t.assessmentError?e.jsx("p",{role:"alert",className:"mt-4 text-sm text-negative",children:t.assessmentError}):null]}),N.length>0?e.jsxs("section",{id:"conversion-integrity-findings",tabIndex:-1,className:"page-section-divider","aria-labelledby":"conversion-integrity-findings-title",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Assessment findings"}),e.jsx("h3",{id:"conversion-integrity-findings-title",className:"text-base font-semibold text-heading",children:"Checks to review"})]}),e.jsxs(ce,{tone:M,children:[N.length," ",N.length===1?"check":"checks"]})]}),e.jsx("ul",{className:"divide-y divide-default border-y border-default",children:N.map(p=>{const v=Ki(p);return e.jsxs("li",{className:"py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"min-w-0 break-words text-sm font-medium text-heading",children:v.label}),e.jsx(ce,{tone:v.tone,children:v.outcome})]}),e.jsxs("p",{className:"mt-1 break-words text-sm text-secondary",children:["Related item: ",p.subject]}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",p.code]}),p.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",p.evidenceIds.join(", ")]}):null]},`${p.code}:${p.subject}`)})})]}):null,e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-progression-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{id:"conversion-integrity-progression-title",className:"text-base font-semibold text-heading",children:"Evidence progression"}),e.jsx(Me,{text:"Configured means a contract exists. Static configuration is checked only against saved Google Ads and Tag Manager evidence. Observed requires separate runtime evidence."})]})}),e.jsx("ol",{className:"divide-y divide-default border-y border-default",children:[{key:"configured",title:"Declared",detail:"The event and provider identifiers are recorded in one project contract."},{key:"static",title:"Static configuration",detail:"Sanitized Google Ads and Tag Manager snapshots are compared with that contract."},{key:"runtime",title:"Runtime observation",detail:"A real browser event, tag firing, and recorded conversion are verified separately."}].map(p=>{const v=Mp(p.key,d);return e.jsxs("li",{className:"grid gap-3 py-3 sm:grid-cols-[minmax(10rem,0.7fr)_minmax(0,1fr)_auto] sm:items-center",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{"aria-hidden":"true",className:`size-2 rounded-full ${v==="positive"?"bg-positive-fill":v==="caution"?"bg-caution-fill":v==="negative"?"bg-negative-fill":"bg-neutral-fill"}`}),e.jsx("span",{className:"text-sm font-medium text-heading",children:p.title})]}),e.jsx("p",{className:"text-sm text-secondary",children:p.detail}),e.jsx(ce,{tone:v,children:Lp(p.key,d)})]},p.key)})})]}),e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-connections-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection evidence"}),e.jsx("h3",{id:"conversion-integrity-connections-title",className:"text-base font-semibold text-heading",children:"Google Ads and Tag Manager"})]})}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("caption",{className:"sr-only",children:"Google Ads and Tag Manager connection and stored evidence state"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Source"}),e.jsx("th",{scope:"col",children:"Connection"}),e.jsx("th",{scope:"col",children:"Selection"}),e.jsx("th",{scope:"col",children:"Stored evidence"}),e.jsx("th",{scope:"col",children:"Actions"})]})}),e.jsxs("tbody",{children:[_i({label:"Google Ads",connection:t.googleAds,...t.googleAds.state==="connected"||t.googleAds.state==="stale"?{changeSelectionLabel:"Change Google Ads account",onChangeSelection:m}:{},actionPending:n}),_i({label:"Google Tag Manager",connection:t.gtm,...t.gtm.state==="connected"||t.gtm.state==="stale"?{changeSelectionLabel:"Change Tag Manager container",onChangeSelection:x}:{},actionPending:n})]})]})}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-caution",children:"Static API evidence does not prove that a browser tag fired or that Google Ads recorded a conversion."}),(t.googleAds.snapshotError||t.gtm.snapshotError)&&h?e.jsx(A,{type:"button",variant:"outline",className:"mt-3",onClick:h,children:"Retry evidence"}):null]}),t.snapshots.length>0?e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-snapshots-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Recent observations"}),e.jsx("h3",{id:"conversion-integrity-snapshots-title",className:"text-base font-semibold text-heading",children:"Latest sanitized snapshots"})]})}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("caption",{className:"sr-only",children:"Latest stored Google marketing snapshots"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Source"}),e.jsx("th",{scope:"col",children:"Observation"}),e.jsx("th",{scope:"col",children:"Captured"}),e.jsx("th",{scope:"col",children:"Identifier"})]})}),e.jsx("tbody",{children:t.snapshots.slice(0,5).map(p=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:p.provider==="google-ads"?"Google Ads":"Google Tag Manager"}),e.jsx("td",{className:"text-secondary",children:p.kind}),e.jsx("td",{className:"text-secondary",children:Bt(p.capturedAt)}),e.jsx("td",{className:"font-mono text-[11px] text-muted",children:nn(p.id)})]},p.id))})]})})]}):null,P.length>0?e.jsxs("details",{className:"inline-disclosure mt-8",children:[e.jsxs("summary",{children:[P.length," ",P.length===1?"passing check":"passing checks"," from the latest assessment"]}),e.jsx("div",{className:"findings-table-wrap mt-3",children:e.jsxs("table",{className:"findings-table",children:[e.jsx("caption",{className:"sr-only",children:"Conversion integrity findings"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Check"}),e.jsx("th",{scope:"col",children:"Result"}),e.jsx("th",{scope:"col",children:"Subject"})]})}),e.jsx("tbody",{children:P.map(p=>{const v=Ki(p);return e.jsxs("tr",{children:[e.jsxs("td",{className:"text-secondary",children:[e.jsx("p",{children:v.label}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",p.code]}),p.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",p.evidenceIds.join(", ")]}):null]}),e.jsx("td",{children:e.jsx(ce,{tone:v.tone,children:v.outcome})}),e.jsx("td",{className:"break-words text-secondary",children:p.subject})]},`${p.code}:${p.subject}`)})})]})})]}):null,d==="runtime-unverified"?e.jsxs("section",{id:"conversion-integrity-runtime-guidance",className:"page-section-divider","aria-labelledby":"conversion-integrity-runtime-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Runtime verification"}),e.jsx("h3",{id:"conversion-integrity-runtime-title",className:"text-base font-semibold text-heading",children:"Runtime verification checklist"})]})}),e.jsxs("ol",{className:"max-w-2xl list-decimal space-y-2 pl-5 text-sm leading-6 text-secondary marker:text-muted",children:[e.jsxs("li",{children:["Use a controlled browser session on ",Dp(t.contract)," and complete the conversion that emits ",e.jsx("span",{className:"font-mono text-heading",children:t.contract.eventName}),"."]}),e.jsxs("li",{children:["In Tag Manager preview or debugging, confirm tag ",e.jsx("span",{className:"font-mono text-heading",children:nn(t.contract.gtm.tagId)})," fires with ",Op(t.contract),"."]}),e.jsxs("li",{children:["Confirm Google Ads records the matching conversion action ",e.jsx("span",{className:"font-mono text-heading",children:nn(t.contract.googleAds.conversionActionId)}),". Do not change the account or publish a Tag Manager version just to verify it."]})]})]}):null]})}const an=3e4,Ui={name:"",eventName:"",conversionActionId:"",conversionId:"",conversionLabel:"",campaignIds:"",tagId:"",triggerIds:"",variableIds:"",productionHosts:"",requireBiddableGoal:!0,requirePrimaryAction:!0,verificationRequired:!0,requireTransactionId:!0,requireValue:!0,requireCurrency:!0},At="mt-1 w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-heading outline-none transition-colors placeholder-mono-600 focus:border-mono-500 focus:ring-2 focus:ring-mono-500/30",ns="text-sm font-medium text-secondary";function Bi(t,s,n,a){return n?{snapshotCount:t,snapshotState:"unavailable",snapshotError:mt(a)}:s?{snapshotCount:t,snapshotState:"loading"}:{snapshotCount:t}}function ia(t){return[...new Set(t.split(/[\n,]/).map(s=>s.trim()).filter(Boolean))]}function Vp(t,s,n){if(n)return{state:"unavailable",selection:null,...s,evidence:"Stored Google Ads connection status could not be loaded.",lastSnapshotAt:null};if(!t||t.status==="not-connected")return{state:"not-connected",selection:null,...s,evidence:"No Google Ads OAuth connection is stored for this project.",lastSnapshotAt:null};if(t.status==="selection-required"){const r=t.connection.selection.customerId;return r?{state:"stale",selection:`Selected customer ${r}`,...s,evidence:"A customer is selected, but Canonry needs a fresh conversion-goal observation.",lastSnapshotAt:t.connection.lastInventorySnapshotAt}:{state:"selection-required",selection:null,...s,evidence:"OAuth access is connected, but Canonry needs a customer account selection.",lastSnapshotAt:t.connection.lastInventorySnapshotAt}}const a=t.selectedCustomer;return{state:t.status,selection:a.descriptiveName??`Selected customer ${a.customerId}`,...s,evidence:t.status==="stale"?"The selected customer needs a fresh conversion-goal observation.":"Selected customer and conversion-goal evidence are stored.",lastSnapshotAt:t.connection.lastInventorySnapshotAt}}function zp(t,s,n){const a=[`Container ${t}`,`account ${s}`];return n&&a.push(`workspace ${n}`),a.join(" · ")}function Qp(t,s,n){if(n)return{state:"unavailable",selection:null,...s,evidence:"Stored Tag Manager connection status could not be loaded.",lastSnapshotAt:null};if(!t||t.status==="not-connected")return{state:"not-connected",selection:null,...s,evidence:"No Tag Manager OAuth connection is stored for this project.",lastSnapshotAt:null};const a=t.selection;return t.status==="selection-required"||!a.accountId||!a.containerId?{state:"selection-required",selection:null,...s,evidence:"OAuth access is connected, but Canonry needs an account and container selection.",lastSnapshotAt:t.connection.lastSnapshotAt}:{state:t.status,selection:zp(a.containerId,a.accountId,a.workspaceId),...s,evidence:t.status==="stale"?"The selected container needs a fresh static configuration observation.":"Selected container configuration evidence is stored.",lastSnapshotAt:t.connection.lastSnapshotAt}}function Hp(t,s,n){return{name:t.name.trim(),eventName:t.eventName.trim(),googleAds:{customerId:s,conversionActionId:t.conversionActionId.trim(),...t.conversionId.trim()?{conversionId:t.conversionId.trim()}:{},...t.conversionLabel.trim()?{conversionLabel:t.conversionLabel.trim()}:{},campaignIds:ia(t.campaignIds),requireBiddableGoal:t.requireBiddableGoal,requirePrimaryAction:t.requirePrimaryAction},gtm:{accountId:n.accountId,containerId:n.containerId,tagId:t.tagId.trim(),triggerIds:ia(t.triggerIds),variableIds:ia(t.variableIds)},runtime:{verificationRequired:t.verificationRequired,requireTransactionId:t.requireTransactionId,requireValue:t.requireValue,requireCurrency:t.requireCurrency,productionHosts:ia(t.productionHosts)}}}function Vi(t,s){const n=window.open(t,"_blank","width=600,height=700");if(!n){window.location.assign(t);return}const a=window.setInterval(()=>{n.closed&&(window.clearInterval(a),s())},1e3)}function oa(t,s,n){if(!s)return null;const a=s.totalAccessible===1?t:`${t}s`;return s.truncated?`Incomplete result: showing ${n} of ${s.totalAccessible} accessible ${a}. Use the CLI or API if the resource is not shown.`:`${s.totalAccessible} accessible ${a} found.`}function la(t,s,n){return t?"no longer accessible":n?"access not verified":s?"not in the current result":"checking access"}function ca({id:t,label:s,value:n,onChange:a,children:r,disabled:o=!1}){return e.jsxs("label",{htmlFor:t,className:ns,children:[s,e.jsx("select",{id:t,className:At,value:n,onChange:i=>a(i.target.value),disabled:o,children:r})]})}function bn({id:t,checked:s,onChange:n,children:a}){return e.jsxs("label",{htmlFor:t,className:"flex items-start gap-2 text-sm text-secondary",children:[e.jsx("input",{id:t,type:"checkbox",checked:s,onChange:r=>n(r.target.checked),className:"mt-0.5 size-4 rounded border-base bg-bg accent-mono-100"}),e.jsx("span",{children:a})]})}function zi({providerLabel:t,disabled:s,onDisconnect:n}){const[a,r]=l.useState(!1),[o,i]=l.useState(!1),[c,u]=l.useState(null),h=l.useRef(null),m=l.useRef(null),x=l.useRef(!1);l.useEffect(()=>{const y=x.current;x.current=a,a?m.current?.focus():y&&h.current?.querySelector("button")?.focus()},[a]);function g(){u(null),r(!0)}function d(){u(null),r(!1)}async function f(){i(!0),u(null);try{await n()}catch(y){u(mt(y)),i(!1)}}return e.jsx("div",{ref:h,className:"mt-5 border-t border-subtle pt-4",children:a?e.jsxs("div",{role:"group","aria-label":`Confirm disconnect ${t}`,className:"max-w-2xl",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"Remove Canonry's stored access and selection?"}),e.jsx("p",{className:"mt-1 text-sm leading-6 text-secondary",children:"Saved evidence and conversion contracts remain. New checks stop until you reconnect."}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(A,{ref:m,type:"button",variant:"outline",size:"sm",className:"min-h-11",disabled:o,onClick:d,children:"Keep connected"}),e.jsx(De,{type:"button",variant:"destructive",size:"sm",className:"min-h-11",disabled:s||o,onClick:()=>{f()},children:o?"Disconnecting…":`Disconnect ${t}`})]}),c?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:c}):null]}):e.jsxs(De,{type:"button",variant:"ghost",size:"sm",className:"min-h-11 text-negative hover:text-negative",disabled:s,onClick:g,children:["Disconnect ",t]})})}function Qi({id:t,label:s,options:n,synced:a,loading:r,failed:o,onRetry:i,emptyHint:c,value:u,onChange:h}){const m=n.some(y=>y.id===u),[x,g]=l.useState(!1),d=x||u!==""&&!m&&n.length>0,f=e.jsx("label",{htmlFor:t,className:ns,children:s});return r?e.jsxs("div",{children:[f,e.jsx("select",{id:t,className:At,disabled:!0,children:e.jsx("option",{children:"Loading…"})})]}):o?e.jsxs("div",{children:[f,e.jsx("input",{id:t,required:!0,className:At,value:u,onChange:y=>h(y.target.value)}),e.jsxs("p",{className:"mt-1 text-xs text-negative",children:["Could not load the list."," ",e.jsx("button",{type:"button",className:"text-link underline",onClick:i,children:"Retry"})]})]}):!a||n.length===0?e.jsxs("div",{children:[f,e.jsx("input",{id:t,required:!0,className:At,value:u,onChange:y=>h(y.target.value)}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:a?"Synced, but nothing to choose from yet.":c})]}):e.jsxs("div",{children:[f,d?e.jsx("input",{id:t,required:!0,className:At,value:u,onChange:y=>h(y.target.value)}):e.jsxs("select",{id:t,required:!0,className:At,value:u,onChange:y=>h(y.target.value),children:[e.jsxs("option",{value:"",children:["Select ",s.toLowerCase()]}),n.map(y=>e.jsxs("option",{value:y.id,children:[y.name,y.detail?` (${y.detail})`:"",y.active?"":" — inactive"]},y.id))]}),e.jsx("button",{type:"button",className:"mt-1 text-xs text-link",onClick:()=>{g(!d),h("")},children:d?"Choose from synced list":"Enter an ID manually"})]})}function Wp({projectId:t,projectName:s}){const n=Hn(),[a,r]=l.useState(null),[o,i]=l.useState(null),[c,u]=l.useState(!1),[h,m]=l.useState(""),[x,g]=l.useState(null),[d,f]=l.useState(!1),[y,j]=l.useState(!1),[N,P]=l.useState(""),[M,k]=l.useState(""),[p,v]=l.useState(""),[S,$]=l.useState(""),[q,L]=l.useState(""),[Q,w]=l.useState(!1),[X,C]=l.useState(Ui),[F,_]=l.useState(null),D=l.useRef(null),Z=we({...Qc({client:H,path:{name:s}}),staleTime:an}),oe=we({...Hc({client:H,path:{name:s}}),staleTime:an}),ne=we({...Wc({client:H,path:{name:s}}),staleTime:an}),U=we({...Yc({client:H,path:{name:s}}),staleTime:an}),T=U.data,G=we({...Jc({client:H,path:{name:s},query:{limit:5}}),staleTime:an}),ae=we({...Xc({client:H,path:{name:s},query:{limit:5}}),staleTime:an}),W=ne.data??[],ge=(F?W.find(R=>R.id===F)??null:null)??(W.length===1?W[0]??null:null),z=W.length>1&&!ge,re=we({...Zc({client:H,path:{name:s,contractId:ge?.id??""}}),enabled:!!ge,staleTime:an}),ue=we({...ed({client:H,path:{name:s}}),enabled:x==="google-ads"&&Z.data?.connected===!0,staleTime:0}),Oe=we({...td({client:H,path:{name:s}}),enabled:x==="gtm"&&oe.data?.connected===!0,staleTime:0}),Fe=we({...sd({client:H,path:{name:s,accountId:p}}),enabled:x==="gtm"&&!!p,staleTime:0}),Pe=we({...nd({client:H,path:{name:s,accountId:p,containerId:S}}),enabled:x==="gtm"&&!!p&&!!S,staleTime:0}),tt=Pt(ad({client:H})),it=Pt(rd({client:H})),ke=Pt(id({client:H})),Xe=Pt(od({client:H})),_e=Pt(ld({client:H})),Ve=Pt(cd({client:H})),He=Pt(dd({client:H})),Te=Pt(ud({client:H})),B=Pt(md({client:H}));l.useEffect(()=>{if(x!=="google-ads"||d||!Z.isSuccess)return;const R=Z.data.connection?.selection;P(R?.customerId??""),k(R?.loginCustomerId??""),f(!0)},[d,Z.data,Z.isSuccess,x]),l.useEffect(()=>{if(x!=="gtm"||y||!oe.isSuccess)return;const R=oe.data.selection;v(R?.accountId??""),$(R?.containerId??""),L(R?.workspaceId??""),j(!0)},[y,oe.data,oe.isSuccess,x]),l.useEffect(()=>{!F||!ne.data||ne.data.some(R=>R.id===F)||_(null)},[ne.data,F]);const O=l.useMemo(()=>{const R=G.data?.snapshots??[],me=ae.data?.snapshots??[],st=[...R.map(_t=>({id:_t.id,provider:"google-ads",kind:_t.kind,capturedAt:_t.capturedAt})),...me.map(_t=>({id:_t.id,provider:"gtm",kind:_t.kind,capturedAt:_t.capturedAt}))].sort((_t,Yt)=>Yt.capturedAt.localeCompare(_t.capturedAt)).slice(0,5),Ae=[],ut=re.data?.googleAdsSnapshot,ds=re.data?.gtmSnapshot;return ut&&Ae.push({id:ut.id,provider:"google-ads",kind:ut.kind,capturedAt:ut.capturedAt}),ds&&Ae.push({id:ds.id,provider:"gtm",kind:ds.kind,capturedAt:ds.capturedAt}),{contract:re.data?.assessment.contract??ge,assessment:re.data?.assessment??null,contractSelectionRequired:z,assessmentState:ge?re.isError?"unavailable":re.isLoading?"loading":void 0:void 0,assessmentError:re.isError?mt(re.error):null,googleAds:Vp(Z.data,Bi(G.data?.total??0,G.isLoading,G.isError,G.error),Z.isError),gtm:Qp(oe.data,Bi(ae.data?.total??0,ae.isLoading,ae.isError,ae.error),oe.isError),snapshots:st,assessmentEvidenceSnapshots:Ae}},[ge,z,G.data,G.error,G.isError,G.isLoading,Z.data,Z.isError,ae.data,ae.error,ae.isError,ae.isLoading,oe.data,oe.isError,re.data,re.error,re.isError,re.isLoading]),V=l.useSyncExternalStore(Co,ba,ba),Ne=Object.values(V.runs).some(R=>R.projectId===t&&(R.kind===zs["google-ads-sync"]||R.kind===zs["gtm-sync"])),Ie=tt.isPending||it.isPending||ke.isPending||Xe.isPending||_e.isPending||Ve.isPending||He.isPending||Te.isPending||B.isPending||Ne;async function ee(){await Promise.all([Z.refetch(),oe.refetch(),ne.refetch(),G.refetch(),ae.refetch(),U.refetch(),ge?re.refetch():Promise.resolve()])}async function We(R){await ee();for(let me=0;me<10&&!R();me+=1)await new Promise(st=>setTimeout(st,1500)),await ee()}function ht(){const R=document.activeElement;D.current=R instanceof HTMLElement?R:null}function Ze(R){if(typeof window<"u"&&typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame(R);return}globalThis.setTimeout(R,0)}function ye(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Ge(R){if(!R)return;!R.matches('a[href], button, input, select, textarea, [contenteditable="true"]')&&!R.hasAttribute("tabindex")&&(R.tabIndex=-1),R.focus({preventScroll:!0})}function It(R,me=R){const st=document.getElementById(R);st instanceof HTMLDetailsElement&&(st.open=!0);const Ae=st?.scrollIntoView;typeof Ae=="function"&&Ae.call(st,{behavior:ye()?"auto":"smooth",block:"start"}),Ge(document.getElementById(me)??st)}function xt(R,me){ht(),Ze(()=>It(R,me))}function Ee(){const R=D.current;D.current=null,R&&Ze(()=>{R.isConnected&&R.focus({preventScroll:!0})})}function Ye(){r(null),u(!1),Ee()}function pt(){r(null),g(null),Ee()}function St(){r(null),w(!1),Ee()}function Ke(){r(null),g(null),u(!0),xt("google-ads-connect-panel","google-ads-connect-title")}function Le(){r(null),P(""),k(""),f(!1),g("google-ads"),u(!1),xt("google-ads-selection-panel","google-ads-selection-title")}function et(){r(null),v(""),$(""),L(""),j(!1),g("gtm"),u(!1),xt("gtm-selection-panel","gtm-selection-title")}function Ue(){r(null),w(!0),xt("conversion-integrity-contract-form","conversion-integrity-contract-form-title")}function Be(R,me){So({id:R.id,projectId:R.projectId,kind:R.kind,projectLabel:s,sourceAction:me}),Se({title:me==="google-ads-sync"?"Google Ads sync queued":"Tag Manager sync queued",detail:`${s} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`google-marketing-sync:${R.id}`,dedupeMode:"replace"})}async function $t(){ys(n),r(null);try{const R=await tt.mutateAsync({path:{name:s},body:{provider:"google-ads",...h.trim()?{developerToken:h.trim()}:{}}});m(""),u(!1),i("Finish the Google Ads consent flow in the new window. Canonry will refresh stored status after it closes."),Vi(R.authorizationUrl,()=>{ee(),i(null),Ee()})}catch(R){r(mt(R))}}async function vt(){ys(n),r(null);try{const R=await it.mutateAsync({path:{name:s},body:{provider:"gtm"}});i("Finish the Tag Manager consent flow in the new window. Canonry will refresh stored status after it closes."),Vi(R.authorizationUrl,()=>{ee(),i(null),Ee()})}catch(R){r(mt(R))}}async function Ft(){if(ys(n),!N){r("Select a Google Ads customer before saving.");return}r(null);try{await ke.mutateAsync({path:{name:s},body:{customerId:N,...M.trim()?{loginCustomerId:M.trim()}:{}}}),g(null),Ee(),await We(()=>Z.data?.selectedCustomer!=null)}catch(R){r(mt(R))}}async function gt(){if(ys(n),!p||!S){r("Select a Tag Manager account and container before saving.");return}r(null);try{await Xe.mutateAsync({path:{name:s},body:{accountId:p,containerId:S,...q?{workspaceId:q}:{}}}),g(null),Ee(),await We(()=>oe.data?.status==="connected")}catch(R){r(mt(R))}}async function Y(){ys(n),r(null),await He.mutateAsync({path:{name:s}}),g(null),u(!1),P(""),k(""),f(!1),i(null),await ee(),Se({title:"Google Ads disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`google-ads-disconnected:${t}`,dedupeMode:"replace"}),D.current=null,Ze(()=>Ge(document.getElementById("conversion-integrity-title")))}async function Re(){ys(n),r(null),await Te.mutateAsync({path:{name:s}}),g(null),v(""),$(""),L(""),j(!1),i(null),await ee(),Se({title:"Tag Manager disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`gtm-disconnected:${t}`,dedupeMode:"replace"}),D.current=null,Ze(()=>Ge(document.getElementById("conversion-integrity-title")))}async function be(){ys(n),r(null);try{const R=await _e.mutateAsync({path:{name:s}});Be(R,"google-ads-sync")}catch(R){r(mt(R))}}async function je(){ys(n),r(null);try{const R=await Ve.mutateAsync({path:{name:s}});Be(R,"gtm-sync")}catch(R){r(mt(R))}}async function Gt(){ys(n),r(null);try{const R=await Promise.allSettled([_e.mutateAsync({path:{name:s}}),Ve.mutateAsync({path:{name:s}})]),[me,st]=R;me.status==="fulfilled"&&Be(me.value,"google-ads-sync"),st.status==="fulfilled"&&Be(st.value,"gtm-sync");const Ae=R.find(ut=>ut.status==="rejected");if(Ae?.status==="rejected")throw Ae.reason}catch(R){r(mt(R))}}async function ze(){ys(n);const R=Z.data?.connection?.selection.customerId,me=oe.data?.selection;if(!R||!me?.accountId||!me.containerId){r("Select Google Ads and Tag Manager resources before declaring a conversion.");return}r(null);try{const st=await B.mutateAsync({path:{name:s},body:Hp(X,R,{accountId:me.accountId,containerId:me.containerId})});C(Ui),w(!1),Ee(),(await ne.refetch()).data?.some(ut=>ut.id===st.id)&&_(st.id)}catch(st){r(mt(st))}}function ft(R){switch(R){case"connect-google-ads":Ke();return;case"connect-gtm":ht(),vt();return;case"select-google-ads":Le();return;case"select-gtm":et();return;case"sync-google-ads":be();return;case"sync-gtm":je();return;case"sync-static-evidence":Gt();return;case"declare-contract":Ue();return;case"review-findings":xt("conversion-integrity-findings","conversion-integrity-findings");return;case"review-runtime-verification":xt("conversion-integrity-runtime-guidance","conversion-integrity-runtime-title");return;case"retry-connection-status":ee();return;case"select-contract":xt("conversion-integrity-contract-select","conversion-integrity-contract-select");return;case"retry-integrity":re.refetch();return;case"waiting-for-integrity":return}}const Tt=ue.data?.customers??[],ls=Oe.data?.accounts??[],Mt=Fe.data?.containers??[],Kt=Pe.data?.workspaces??[],ot=!!N&&!Tt.some(R=>R.customerId===N),cs=!!p&&!ls.some(R=>R.id===p),Ct=!!S&&!Mt.some(R=>R.id===S),Ts=!!q&&!Kt.some(R=>R.id===q),zt=ot&&ue.isSuccess&&ue.data.truncated===!1,Xt=cs&&Oe.isSuccess&&Oe.data.truncated===!1,Qt=Ct&&Fe.isSuccess&&Fe.data.truncated===!1,dt=Ts&&Pe.isSuccess&&Pe.data.truncated===!1,Ns=Xt||Qt||dt,Ht=Xt?"The saved Tag Manager account is no longer accessible. Choose an available account before saving.":Qt?"The saved Tag Manager container is no longer accessible. Choose an available container before saving.":dt?"The saved draft workspace is no longer accessible. Choose an available workspace or No draft workspace before saving.":null,ct=la(zt,ue.data,ue.isError),hs=la(Xt,Oe.data,Oe.isError),jt=la(Qt,Fe.data,Fe.isError),Zt=la(dt,Pe.data,Pe.isError),xs=ue.isError?mt(ue.error):null,ps=Oe.isError?mt(Oe.error):Fe.isError?mt(Fe.error):Pe.isError?mt(Pe.error):null,Lt=x==="google-ads"?xs:x==="gtm"?ps:null,E=oa("customer",ue.data,Tt.length),se=oa("account",Oe.data,ls.length),fe=oa("container",Fe.data,Mt.length),ie=oa("draft workspace",Pe.data,Kt.length),le=Oe.isError||Fe.isError||Pe.isError&&!!q,$e=c||x!==null||Q;function Wt(){ue.refetch()}function yt(){if(Oe.isError){Oe.refetch();return}if(Fe.isError){Fe.refetch();return}Pe.isError&&Pe.refetch()}return Z.isLoading||oe.isLoading||ne.isLoading?e.jsxs("section",{className:"page-section","aria-busy":"true","aria-labelledby":"conversion-integrity-title",children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsx("h2",{id:"conversion-integrity-title",className:"mt-1 text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsx("div",{"aria-hidden":"true",className:"mt-5 grid gap-4 sm:grid-cols-2",children:[0,1].map(R=>e.jsxs("div",{className:"page-skeleton-card",children:[e.jsx("div",{className:"skeleton-text w-28"}),e.jsx("div",{className:"skeleton-text-sm w-full"}),e.jsx("div",{className:"skeleton-text-sm w-3/4"})]},R))}),e.jsx("p",{role:"status",className:"sr-only",children:"Loading conversion setup…"})]}):ne.isError&&!ne.data?e.jsxs("section",{className:"page-section","aria-labelledby":"conversion-integrity-title",children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsx("h2",{id:"conversion-integrity-title",className:"mt-1 text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsxs("p",{role:"alert",className:"mt-3 text-sm text-negative",children:["Could not load conversion contracts: ",mt(ne.error)]}),e.jsx(A,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{ne.refetch()},children:"Retry contracts"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Bp,{workspace:O,onPrimaryAction:ft,actionPending:Ie,actionError:$e?null:a,contracts:W,selectedContractId:ge?.id??null,onSelectContract:R=>_(R||null),contractError:ne.isError?mt(ne.error):null,onRetryContracts:()=>{ne.refetch()},onRetryEvidence:()=>{Promise.all([G.refetch(),ae.refetch()])},onChangeGoogleAdsSelection:Le,onChangeGtmSelection:et,onAddContract:()=>ft("declare-contract")}),o?e.jsx("p",{role:"status",className:"page-section text-sm text-secondary",children:o}):null,c?e.jsxs("section",{id:"google-ads-connect-panel",className:"page-section-divider","aria-labelledby":"google-ads-connect-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Google Ads"}),e.jsx("h3",{id:"google-ads-connect-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Connect read-only access"})]})}),a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,e.jsxs("form",{className:"max-w-xl",onSubmit:qe(async R=>{R.preventDefault(),await $t()}),children:[e.jsxs("label",{htmlFor:"google-ads-developer-token",className:ns,children:["Developer token",e.jsx("input",{id:"google-ads-developer-token",type:"password",autoComplete:"off",value:h,onChange:R=>m(R.target.value),className:At,placeholder:"Required only when this project has no saved token"})]}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-secondary",children:"Canonry stores this securely. It never appears in saved evidence."}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(De,{type:"submit",disabled:tt.isPending,children:tt.isPending?"Starting…":"Continue to Google"}),e.jsx(A,{type:"button",variant:"outline",onClick:Ye,children:"Cancel"})]})]})]}):null,x==="google-ads"?e.jsxs("section",{id:"google-ads-selection-panel",className:"page-section-divider","aria-labelledby":"google-ads-selection-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Google Ads"}),e.jsx("h3",{id:"google-ads-selection-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Select customer context"})]})}),Lt?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:Lt}),e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:Wt,children:"Retry customer list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,zt?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:"The saved customer is no longer accessible. Choose another customer before saving."}):null,e.jsxs("div",{className:"grid max-w-2xl gap-4 sm:grid-cols-2",children:[e.jsxs(ca,{id:"google-ads-customer",label:"Customer account",value:N,onChange:R=>{f(!0),P(R);const me=Tt.find(st=>st.customerId===R);k(me?.parentCustomerId??"")},disabled:ue.isLoading,children:[e.jsx("option",{value:"",children:ue.isLoading?"Loading accessible customers…":"Select a customer"}),ot?e.jsxs("option",{value:N,disabled:zt,children:["Saved customer ",N," (",ct,")"]}):null,Tt.map(R=>e.jsx("option",{value:R.customerId,children:R.descriptiveName??`Customer ${R.customerId}`},R.customerId))]}),e.jsxs("label",{htmlFor:"google-ads-login-customer",className:ns,children:["Manager account ID (optional)",e.jsx("input",{id:"google-ads-login-customer",className:At,value:M,onChange:R=>{f(!0),k(R.target.value)},placeholder:"Use only when a manager context is required"})]})]}),E?e.jsx("p",{role:"status",className:`mt-3 text-sm ${ue.data?.truncated?"text-caution":"text-secondary"}`,children:E}):null,e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(De,{type:"button",disabled:ke.isPending||ue.isLoading||ue.isError||zt||!N,onClick:qe(Ft),children:ke.isPending?"Saving…":"Save customer selection"}),e.jsx(A,{type:"button",variant:"outline",onClick:pt,children:"Cancel"})]}),Z.data?.connected?e.jsx(zi,{providerLabel:"Google Ads",disabled:Ie,onDisconnect:Y}):null]}):null,x==="gtm"?e.jsxs("section",{id:"gtm-selection-panel",className:"page-section-divider","aria-labelledby":"gtm-selection-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Google Tag Manager"}),e.jsx("h3",{id:"gtm-selection-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Select container context"})]})}),Lt?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:Lt}),e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:yt,children:Oe.isError?"Retry account list":Fe.isError?"Retry container list":"Retry workspace list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,Ht?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:Ht}):null,e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-3",children:[e.jsxs(ca,{id:"gtm-account",label:"Account",value:p,onChange:R=>{j(!0),R!==p&&($(""),L("")),v(R)},disabled:Oe.isLoading,children:[e.jsx("option",{value:"",children:Oe.isLoading?"Loading accounts…":"Select an account"}),cs?e.jsxs("option",{value:p,disabled:Xt,children:["Saved account ",p," (",hs,")"]}):null,ls.map(R=>e.jsx("option",{value:R.id,children:R.name},R.id))]}),e.jsxs(ca,{id:"gtm-container",label:"Container",value:S,onChange:R=>{j(!0),R!==S&&L(""),$(R)},disabled:!p||Fe.isLoading,children:[e.jsx("option",{value:"",children:Fe.isLoading?"Loading containers…":"Select a container"}),Ct?e.jsxs("option",{value:S,disabled:Qt,children:["Saved container ",S," (",jt,")"]}):null,Mt.map(R=>e.jsx("option",{value:R.id,children:R.name},R.id))]}),e.jsxs(ca,{id:"gtm-workspace",label:"Draft workspace (optional)",value:q,onChange:R=>{j(!0),L(R)},disabled:!S||Pe.isLoading,children:[e.jsx("option",{value:"",children:Pe.isLoading?"Loading workspaces…":"No draft workspace"}),Ts?e.jsxs("option",{value:q,disabled:dt,children:["Saved draft workspace ",q," (",Zt,")"]}):null,Kt.map(R=>e.jsx("option",{value:R.id,children:R.name},R.id))]})]}),e.jsxs("div",{className:"mt-3 grid max-w-3xl gap-2 text-sm sm:grid-cols-3",children:[se?e.jsx("p",{role:"status",className:Oe.data?.truncated?"text-caution":"text-secondary",children:se}):null,fe?e.jsx("p",{role:"status",className:Fe.data?.truncated?"text-caution":"text-secondary",children:fe}):null,ie?e.jsx("p",{role:"status",className:Pe.data?.truncated?"text-caution":"text-secondary",children:ie}):null]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(De,{type:"button",disabled:Xe.isPending||Oe.isLoading||Fe.isLoading||Pe.isLoading&&!!q||le||Ns||!p||!S,onClick:qe(gt),children:Xe.isPending?"Saving…":"Save container selection"}),e.jsx(A,{type:"button",variant:"outline",onClick:pt,children:"Cancel"})]}),oe.data?.connected?e.jsx(zi,{providerLabel:"Tag Manager",disabled:Ie,onDisconnect:Re}):null]}):null,Q?e.jsxs("section",{id:"conversion-integrity-contract-form",className:"page-section-divider","aria-labelledby":"conversion-integrity-contract-form-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Declared conversion"}),e.jsx("h3",{id:"conversion-integrity-contract-form-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Declare the expected path"})]})}),a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,e.jsxs("form",{onSubmit:qe(async R=>{R.preventDefault(),await ze()}),children:[e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-2",children:[e.jsxs("label",{htmlFor:"contract-name",className:ns,children:["Conversion name",e.jsx("input",{id:"contract-name",required:!0,maxLength:120,className:At,value:X.name,onChange:R=>C(me=>({...me,name:R.target.value})),placeholder:"Booking completed"})]}),e.jsxs("label",{htmlFor:"contract-event-name",className:ns,children:["Website event",e.jsx("input",{id:"contract-event-name",required:!0,className:At,value:X.eventName,onChange:R=>C(me=>({...me,eventName:R.target.value})),placeholder:"booking_complete"})]}),e.jsx(Qi,{id:"contract-conversion-action",label:"Google Ads conversion action",options:T?.googleAds.conversionActions??[],synced:T?.googleAds.syncedAt!=null,loading:U.isLoading,failed:U.isError,onRetry:()=>{U.refetch()},emptyHint:"Run a Google Ads sync to list conversion actions.",value:X.conversionActionId,onChange:R=>C(me=>({...me,conversionActionId:R}))}),e.jsx(Qi,{id:"contract-gtm-tag",label:"Tag Manager tag",options:T?.gtm.tags??[],synced:T?.gtm.syncedAt!=null,loading:U.isLoading,failed:U.isError,onRetry:()=>{U.refetch()},emptyHint:"Run a Tag Manager sync to list tags.",value:X.tagId,onChange:R=>C(me=>({...me,tagId:R}))})]}),e.jsxs("details",{className:"inline-disclosure mt-5 max-w-3xl",children:[e.jsx("summary",{children:"Additional matching rules"}),e.jsxs("div",{className:"mt-4 grid gap-4 sm:grid-cols-2",children:[e.jsxs("label",{htmlFor:"contract-conversion-id",className:ns,children:["Google conversion ID (optional)",e.jsx("input",{id:"contract-conversion-id",className:At,value:X.conversionId,onChange:R=>C(me=>({...me,conversionId:R.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-conversion-label",className:ns,children:["Google conversion label (optional)",e.jsx("input",{id:"contract-conversion-label",className:At,value:X.conversionLabel,onChange:R=>C(me=>({...me,conversionLabel:R.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-trigger-ids",className:ns,children:["Trigger IDs",e.jsx("input",{id:"contract-trigger-ids",className:At,value:X.triggerIds,onChange:R=>C(me=>({...me,triggerIds:R.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-variable-ids",className:ns,children:["Variable IDs",e.jsx("input",{id:"contract-variable-ids",className:At,value:X.variableIds,onChange:R=>C(me=>({...me,variableIds:R.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-campaign-ids",className:ns,children:["Campaign IDs",e.jsx("input",{id:"contract-campaign-ids",className:At,value:X.campaignIds,onChange:R=>C(me=>({...me,campaignIds:R.target.value})),placeholder:"Optional campaign-specific goal checks"})]}),e.jsxs("label",{htmlFor:"contract-production-hosts",className:ns,children:["Production hosts",e.jsx("input",{id:"contract-production-hosts",className:At,value:X.productionHosts,onChange:R=>C(me=>({...me,productionHosts:R.target.value})),placeholder:"example.com"})]})]}),e.jsxs("fieldset",{className:"mt-5 border-t border-subtle pt-4",children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:"Required evidence"}),e.jsxs("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:[e.jsx(bn,{id:"contract-primary-action",checked:X.requirePrimaryAction,onChange:R=>C(me=>({...me,requirePrimaryAction:R})),children:"Google Ads action is primary"}),e.jsx(bn,{id:"contract-biddable-goal",checked:X.requireBiddableGoal,onChange:R=>C(me=>({...me,requireBiddableGoal:R})),children:"Google Ads goal is biddable"}),e.jsx(bn,{id:"contract-runtime-verification",checked:X.verificationRequired,onChange:R=>C(me=>({...me,verificationRequired:R})),children:"Runtime proof is required"}),e.jsx(bn,{id:"contract-transaction-id",checked:X.requireTransactionId,onChange:R=>C(me=>({...me,requireTransactionId:R})),children:"Transaction ID is required"}),e.jsx(bn,{id:"contract-value",checked:X.requireValue,onChange:R=>C(me=>({...me,requireValue:R})),children:"Conversion value is required"}),e.jsx(bn,{id:"contract-currency",checked:X.requireCurrency,onChange:R=>C(me=>({...me,requireCurrency:R})),children:"Currency is required"})]})]})]}),e.jsx("p",{className:"mt-4 max-w-2xl text-sm leading-6 text-secondary",children:"This creates a Canonry contract only. It does not alter a Google Ads conversion action or create, edit, or publish a Tag Manager version."}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(De,{type:"submit",disabled:B.isPending,children:B.isPending?"Saving…":"Save conversion contract"}),e.jsx(A,{type:"button",variant:"outline",onClick:St,children:"Cancel"})]})]})]}):null]})}const Yp=6e4,Jp=["7d","14d","30d"],qr="not available",Xp='Figures come from the stored Google Ads snapshot; this view never calls Google. The window ends on the newest CLOSED day, because the capture day is only partly recorded and would read as a drop. A calendar day the provider returned no row for is zero delivery, so it is charted as zero. Rates with a zero denominator read "not available", never 0%.',Zp="No Google Ads snapshot stored yet",eg="Connect a Google Ads account in Conversion Integrity below, choose the customer, then run a Google Ads sync. Spend, clicks, impressions, and conversions appear here once the first snapshot is stored.",tg="No closed days yet",sg="The stored snapshot covers no completed day yet. Figures appear after a full day closes in the account time zone; the day a snapshot is captured is partial and is left out on purpose. If this persists, check the latest Google Ads sync in Activity.",ng={"insufficient-history":"Period change is hidden: the stored snapshot does not cover a prior period of equal length yet."},qs=new Intl.NumberFormat(void 0,{maximumFractionDigits:0}),tr=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}),ul=new Intl.NumberFormat(void 0,{maximumFractionDigits:1}),ag=new Intl.NumberFormat(void 0,{minimumFractionDigits:2,maximumFractionDigits:2});function vn(t,s){return t===null||!Number.isFinite(t)?qr:s===null?ag.format(t/1e6):$m(t,s)}function sr(t){if(t===null||!Number.isFinite(t))return qr;const s=t*100;return s>0&&s<.1?"<0.1%":`${ul.format(s)}%`}function rg(t,s){if(t===null||!Number.isFinite(t))return`${qr} vs prior ${s}d`;if(t===0)return`no change vs prior ${s}d`;const n=Math.abs(t*100),a=n<.1?"<0.1%":`${ul.format(n)}%`;return`${t>0?"↑":"↓"} ${a} vs prior ${s}d`}function ig(t){return t==="enabled"?"positive":t==="paused"?"caution":"neutral"}function og(t){return t==="enabled"?"Enabled":t==="paused"?"Paused":t==="removed"?"Removed":"Unknown"}function lg(t,s){return s==="none"||t===null||!Number.isFinite(t)||t===0?"text-muted":(s==="up-good"?t>0:t<0)?"text-positive":"text-negative"}function cg({projectName:t}){const[s,n]=l.useState("14d"),[a,r]=l.useState(()=>new Set(["costMicros","conversions"])),o=we({...hd({client:H,path:{name:t},query:{window:s}}),staleTime:Yp}),i=o.data,c=e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Google Ads"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h2",{id:"google-ads-performance-title",className:"text-xl font-semibold tracking-[-0.02em] text-heading",children:"Ad performance"}),e.jsx(Me,{text:Xp})]}),i?.source?e.jsxs("p",{className:"text-xs text-muted",children:[Ot(i.startDate)," to ",Ot(i.endDate)," · ",i.days," closed ",i.days===1?"day":"days"]}):null]}),e.jsx(Ra,{windows:Jp,value:s,onChange:n,label:"Google Ads time period"})]});if(o.isLoading)return e.jsxs("section",{className:"page-section","aria-busy":"true","aria-labelledby":"google-ads-performance-title",children:[c,e.jsx("div",{"aria-hidden":"true",className:"mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[0,1,2,3].map(p=>e.jsxs("div",{className:"page-skeleton-card",children:[e.jsx("div",{className:"skeleton-text w-20"}),e.jsx("div",{className:"skeleton-text-sm w-28"})]},p))}),e.jsx("p",{role:"status",className:"sr-only",children:"Loading Google Ads performance…"})]});if(o.isError||!i)return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[c,e.jsxs("p",{role:"alert",className:"mt-4 text-sm text-negative",children:["Could not load Google Ads performance: ",mt(o.error)]}),e.jsx(A,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{o.refetch()},children:"Retry performance"})]});const{totals:u,daily:h,campaigns:m,comparison:x,comparisonUnavailableReason:g,source:d}=i;if(!d){const p=g==="insufficient-history";return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[c,e.jsxs("div",{className:"mt-4 max-w-2xl rounded-md border border-default bg-surface-subtle p-5",children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:p?tg:Zp}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-secondary",children:p?sg:eg})]})]})}const f=d.currencyCode,y=d.campaignsInInventory>0&&d.campaignsQueried<d.campaignsInInventory?{queried:d.campaignsQueried,inInventory:d.campaignsInInventory}:null,j=u.costMicros>0&&u.conversions===0,N=[{key:"spend",comparable:!0,label:"Spend",value:vn(u.costMicros,f),change:x?.change.costMicros??null,direction:"none",seriesKey:"costMicros"},{key:"conversions",comparable:!0,label:"Conversions",value:tr.format(u.conversions),change:x?.change.conversions??null,direction:"up-good",seriesKey:"conversions"},{key:"cost-per-conversion",label:"Cost / conv.",value:j?"no conversions":vn(u.costPerConversionMicros,f),change:null,comparable:!1,direction:"down-good",seriesKey:null},{key:"conversion-rate",comparable:!0,label:"Conv. rate",value:sr(u.conversionRate),change:x?.change.conversionRate??null,direction:"up-good",seriesKey:null}],P=[{key:"clicks",label:"Clicks",value:qs.format(u.clicks),seriesKey:"clicks"},{key:"impressions",label:"Impressions",value:qs.format(u.impressions),seriesKey:"impressions"},{key:"ctr",label:"CTR",value:sr(u.ctr),seriesKey:null},{key:"cpc",label:"CPC",value:vn(u.cpcMicros,f),seriesKey:null}],M={costMicros:{label:"Spend",color:nt[1],axisId:"spend",formatValue:p=>vn(p,f)},conversions:{label:"Conversions",color:nt[0],axisId:"conversions",formatValue:p=>tr.format(p)},clicks:{label:"Clicks",color:nt[2],axisId:"clicks",formatValue:p=>qs.format(p)},impressions:{label:"Impressions",color:nt[3],axisId:"impressions",formatValue:p=>qs.format(p)}},k=[...a].map(p=>({dataKey:p,...M[p]}));return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[c,y!==null?e.jsxs("p",{role:"status",className:"mt-3 text-sm text-caution",children:["Totals cover ",qs.format(y.queried)," of"," ",qs.format(y.inInventory)," campaigns, so they are a subset of the account."]}):null,d.truncated?e.jsx("p",{role:"status",className:"mt-3 text-sm text-caution",children:"The provider returned a bounded result, so some rows are missing from the figures below."}):null,!x&&g==="insufficient-history"?e.jsx("p",{className:"mt-3 text-sm text-secondary",children:ng["insufficient-history"]}):null,e.jsx("div",{className:"mt-4 grid grid-cols-2 gap-2 lg:grid-cols-4",children:N.map(p=>{const v=p.seriesKey!==null&&a.has(p.seriesKey),S=v&&a.size===1,$=e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[p.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:v?M[p.seriesKey].color:"var(--color-mono-600)"}}):null,p.label]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:p.value}),x&&p.comparable?e.jsx("span",{className:`block text-[11px] tabular-nums ${lg(p.change,p.direction)}`,children:rg(p.change,x.days)}):e.jsx("span",{className:"block text-[11px] text-muted",children:p.comparable?`no prior ${s} period stored`:" "})]});return p.seriesKey===null?e.jsx("div",{className:"rounded-md border border-subtle bg-surface-subtle px-3 py-2",children:$},p.key):e.jsx("button",{type:"button","aria-pressed":v,disabled:S,onClick:()=>r(q=>{const L=new Set(q);return L.has(p.seriesKey)?L.delete(p.seriesKey):L.add(p.seriesKey),L.size===0?q:L}),className:`rounded-md border px-3 py-2 text-left transition-colors ${v?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${S?"cursor-default":""}`,children:$},p.key)})}),e.jsx("dl",{className:"mt-2 flex flex-wrap gap-x-6 gap-y-1 rounded-md border border-subtle bg-surface-subtle px-3 py-2",children:P.map(p=>{const v=p.seriesKey!==null&&a.has(p.seriesKey),S=v&&a.size===1,$=e.jsxs(e.Fragment,{children:[e.jsxs("dt",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[p.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:v?M[p.seriesKey].color:"var(--color-mono-600)"}}):null,p.label]}),e.jsx("dd",{className:"text-sm tabular-nums text-strong",children:p.value})]});return p.seriesKey===null?e.jsx("div",{className:"flex items-baseline gap-1.5",children:$},p.key):e.jsx("button",{type:"button","aria-pressed":v,disabled:S,onClick:()=>r(q=>{const L=new Set(q);return L.has(p.seriesKey)?L.delete(p.seriesKey):L.add(p.seriesKey),L.size===0?q:L}),className:`flex items-baseline gap-1.5 rounded px-1 -mx-1 ${S?"cursor-default":"hover:bg-surface-hover"}`,children:$},p.key)})}),e.jsxs("div",{className:"mt-4",children:[e.jsx(Eo,{data:h,xKey:"date",series:k,xTickFormatter:pn,labelFormatter:Ot}),e.jsx("ul",{className:"sr-only",children:h.map(p=>e.jsxs("li",{children:[Ot(p.date),":"," ",k.map(v=>`${v.label} ${M[v.dataKey].formatValue(p[v.dataKey])}`).join(", "),p.origin==="filled"?", no delivery reported":""]},p.date))})]}),e.jsxs("div",{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:"By campaign"}),e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Campaign performance"})]})}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("caption",{className:"sr-only",children:"Google Ads campaign performance for the selected window"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Campaign"}),e.jsx("th",{className:"text-left",children:"Status"}),e.jsx("th",{className:"text-right",children:"Impressions"}),e.jsx("th",{className:"text-right",children:"Clicks"}),e.jsx("th",{className:"text-right",children:"Spend"}),e.jsx("th",{className:"text-right",children:"Conversions"}),e.jsx("th",{className:"text-right",children:"CTR"}),e.jsx("th",{className:"text-right",children:"Cost / conv."})]})}),e.jsx("tbody",{children:m.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"text-secondary",children:"No campaign delivered in this window."})}):m.map(p=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs truncate text-strong",title:p.name??p.campaignId,children:p.name??e.jsx("span",{className:"font-mono text-secondary",children:p.campaignId})}),e.jsx("td",{children:e.jsx(ce,{tone:ig(p.status),children:og(p.status)})}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:qs.format(p.totals.impressions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:qs.format(p.totals.clicks)}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:vn(p.totals.costMicros,f)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:tr.format(p.totals.conversions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:sr(p.totals.ctr)}),e.jsx("td",{className:"text-right tabular-nums",children:p.totals.costMicros>0&&p.totals.conversions===0?e.jsx(ce,{tone:"caution",children:"no conversions"}):e.jsx("span",{className:"text-secondary",children:vn(p.totals.costPerConversionMicros,f)})})]},p.campaignId))})]})}),e.jsxs("p",{className:"mt-3 text-[11px] text-muted",children:["Snapshot ",Bs($s(d.capturedAt))," · ","customer ",d.customerId," · ","latest closed day ",Ot(d.asOfDate),d.openDate?e.jsxs(e.Fragment,{children:[" · ",Ot(d.openDate)," still open, excluded"]}):null,d.timeZone?e.jsxs(e.Fragment,{children:[" · ","days close in ",d.timeZone]}):null]})]})]})}const nr=20,ks=50,dg=50,ug=50;function Dr(t){return t==="viewer"}function Or(t){return t?.status==="unavailable"}function ml(t,s,n){return n?t.includes(s)?[...t]:[...t,s]:t.filter(a=>a!==s)}function hl(t,s){const n=new Map(s.map(r=>[r.id,r.label])),a=t.map(r=>n.get(r)).filter(r=>!!r);return a.length===0?"Not applied":a.length>3?`${a.length} Properties`:a.join(", ")}function da(t,s,n){if(t.kind==="all")return s.map(o=>o.id);if(t.kind==="specific")return s.filter(o=>t.propertyIds.includes(o.id)).map(o=>o.id);const a=new Set(t.groupIds),r=new Set(n.filter(o=>a.has(o.id)).flatMap(o=>o.propertyIds));return s.filter(o=>r.has(o.id)).map(o=>o.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(r=>s.find(o=>o.id===r)?.name).filter(r=>!!r);return a.length===0?"selected groups":a.join(" + ")}function ar(t,s){const n=new Set(s.map(r=>r.id)),a=t.propertyIds.filter(r=>n.has(r)).length;return`${t.name} · ${a===1?"1 Property":`${a} Properties`}`}function Hi(t){return t==="matched"?"positive":t==="duplicate"?"neutral":t==="ambiguous"||t==="proposed"||t==="excluded"?"caution":"negative"}function Wi(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 ua(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 kr(t){return t.state==="missing"||t.source==="unavailable-tracked-query"||!t.source}function rr(t){return kr(t)?"Unavailable tracked query":t.text?.trim()||"Unavailable tracked query"}function Ar({properties:t,selectedPropertyIds:s,onSelectedPropertyIdsChange:n,legend:a,showBulkActions:r=!0}){const[o,i]=l.useState(""),[c,u]=l.useState(!1),h=o.trim().toLocaleLowerCase(),m=h?t.filter(f=>f.label.toLocaleLowerCase().includes(h)):t,x=c?m:m.slice(0,dg),g=x.length<m.length;function d(){const f=new Set([...s,...x.map(y=>y.id)]);n(t.filter(y=>f.has(y.id)).map(y=>y.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:o,onChange:f=>i(f.currentTarget.value),className:"mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400"})]}),r?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:x.length===0,onClick:d,children:"Select all shown"}),e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:s.length===0,onClick:()=>n([]),children:"Clear selection"})]}):null]}),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 ",x.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:x.map(f=>{const y=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:y,type:"checkbox",onChange:j=>n(ml(s,f.id,j.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)})}),g?e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",onClick:()=>u(!0),children:"Show all Properties"}):null]})]})}function Fr(){return e.jsxs("div",{className:"flex items-center gap-2 text-sm text-secondary",children:[e.jsx(ce,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]})}function Gr({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(ce,{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 hg({value:t}){const[s,n]=l.useState(0),[a,r]=l.useState(0),[o,i]=l.useState(null),c=t.preview,u=c?.counts.needsAttention??0,h=c?.rows.filter(S=>S.status==="matched")??[],m=c?.rows??[],x=m.filter(S=>S.status!=="matched"),g=Math.max(1,Math.ceil(m.length/ks)),d=Math.min(s,g-1),f=m.slice(d*ks,(d+1)*ks),y=Math.max(1,Math.ceil(x.length/ks)),j=Math.min(a,y-1),N=x.slice(j*ks,(j+1)*ks),P=t.csv.trim().length>0&&!t.isReviewing&&!t.isApplying,M=h.length>0&&!t.isApplying,k=c!==null&&o===c.previewChecksum,p=x.length>0&&j===y-1;l.useEffect(()=>{n(0),r(0),i(null)},[c?.previewChecksum]);async function v(S){if(S)try{t.onCsvChange(await S.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:S=>{v(S.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:S=>t.onCsvChange(S.currentTarget.value),placeholder:`property,group,url
|
|
4
4
|
Harbor House,Dallas,https://example.com/harbor-house`,className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!P,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]}),c?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:[c.counts.matchedRows," matched · ",c.counts.groupsReady," group",c.counts.groupsReady===1?"":"s"," ready",u>0?` · ${u} need${u===1?"s":""} attention`:""]}),c.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:c.groupChanges.map(S=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:S.label}),e.jsx("td",{className:"text-secondary",children:S.action==="create"?"Create group":"Add to existing group"}),e.jsx("td",{className:"tabular-nums text-secondary",children:S.targetKeys.length}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[S.addedTargetKeys.length,S.unchangedTargetKeys.length>0?` · ${S.unchangedTargetKeys.length} already members`:""]})]},S.groupKey))})]})}):null,c.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 (",c.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(S=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:S.dataRow}),e.jsx("td",{className:"text-heading",children:S.property}),e.jsx("td",{className:"text-secondary",children:S.group}),e.jsxs("td",{children:[e.jsx(ce,{tone:Hi(S.status),children:Wi(S.status)}),ua(S)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:ua(S)}):null]})]},S.dataRow))})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Page ",d+1," of ",g," · ",c.rows.length," rows"]}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:d===0,onClick:()=>n(S=>Math.max(0,S-1)),children:"Previous 50 rows"}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:d===g-1,onClick:()=>n(S=>Math.min(g-1,S+1)),children:"Next 50 rows"})]})]}):null,u>0?e.jsxs("details",{className:"mt-3 border-y border-caution-800/30 py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Fix ",u," row",u===1?"":"s"," before applying"]}),e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Correct these rows, or explicitly continue with only the reviewed matches. Rows needing attention are not added."}),e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"CSV rows that need attention"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Row"}),e.jsx("th",{children:"Property"}),e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Issue"})]})}),e.jsx("tbody",{children:N.map(S=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:S.dataRow}),e.jsx("td",{className:"text-heading",children:S.property}),e.jsx("td",{className:"text-secondary",children:S.group}),e.jsxs("td",{children:[e.jsx(ce,{tone:Hi(S.status),children:Wi(S.status)}),ua(S)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:ua(S)}):null]})]},S.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 ",j+1," of ",y]}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:j===0,onClick:()=>r(S=>Math.max(0,S-1)),children:"Previous 50 exceptions"}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:j===y-1,onClick:()=>r(S=>Math.min(y-1,S+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:k,disabled:t.isApplying||!p,onChange:S=>i(S.currentTarget.checked?c.previewChecksum:null),className:"size-4 rounded border-default"}),"I reviewed the exceptions and understand that ",u," row",u===1?"":"s"," will be skipped."]}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",disabled:!M||!k,onClick:()=>{t.onApply(h.map(S=>S.dataRow))},children:t.isApplying?"Applying groups…":`Apply ${h.length} matched row${h.length===1?"":"s"}`})]}):e.jsx(A,{type:"button",className:"mt-3 min-h-11",disabled:!M,onClick:()=>{t.onApply(h.map(S=>S.dataRow))},children:t.isApplying?"Creating groups…":`Create ${c.counts.groupsReady} group${c.counts.groupsReady===1?"":"s"} with ${h.length} membership${h.length===1?"":"s"}`})]}):null]})}const xg="—";function pg({access:t,availability:s,properties:n,queries:a,selectedQueryIds:r,isApplying:o=!1,isBusy:i=!1,canContinue:c=!0,onSelectedQueryIdsChange:u,onApplySelectedQueries:h,onClearQueryAssignments:m,onRemoveQuery:x,onCreateQueries:g,onCreateAndPairQuestions:d,isCreatingQueries:f=!1,createQueriesError:y=null,onManageProjectQueries:j,groups:N,audience:P,onAudienceChange:M,assignmentImpact:k=null,isPreviewingAssignmentImpact:p=!1,assignmentImpactError:v=null,onRetryAssignmentImpact:S,assignmentNotice:$=null,onReplaceAssignments:q,isReplacingAssignments:L=!1,onBack:Q,onContinue:w}){const[X,C]=l.useState(""),[F,_]=l.useState(!1),[D,Z]=l.useState(!1),[oe,ne]=l.useState(""),[U,T]=l.useState(""),[G,ae]=l.useState(null);if(Or(s))return e.jsx("section",{"aria-label":"Queries",children:e.jsx(Gr,{message:s.message})});const W=Dr(t),J=P,ge=M,z=da(J,n,N),re=z.length,ue=re>0&&r.length>0&&!o&&!i&&!p&&k!==null&&v===null,Oe=m??x,Fe=X.trim().toLocaleLowerCase(),Pe=Fe?a.filter(V=>rr(V).toLocaleLowerCase().includes(Fe)):a,tt=Pe.filter(V=>(V.propertyIds?.length??0)===0),it=D?tt:Pe,ke=F?it:it.slice(0,ug),Xe=ke.filter(V=>!kr(V)),_e=[...new Set(oe.split(`
|