@ainyc/canonry 5.1.1 → 5.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. package/assets/assets/{AuditHistoryPanel-9F_74jKS.js → AuditHistoryPanel-Dc_pymFg.js} +1 -1
  2. package/assets/assets/{BacklinksPage-DmF2rbwy.js → BacklinksPage-BkSo48YX.js} +1 -1
  3. package/assets/assets/{HistoryPage-DKopwAjo.js → HistoryPage-BbswsdU7.js} +1 -1
  4. package/assets/assets/{MeasurementPropertyPage-Dpd_DYQv.js → MeasurementPropertyPage-BbgtalkM.js} +1 -1
  5. package/assets/assets/{ProjectPage-b1-57SzP.js → ProjectPage-CAcRQp-T.js} +1 -1
  6. package/assets/assets/{RunRow-BjrSRp6X.js → RunRow-2cNW8FHz.js} +1 -1
  7. package/assets/assets/{RunsPage-BFrymZ7D.js → RunsPage-Cz3lJ6VJ.js} +1 -1
  8. package/assets/assets/{SettingsPage-DdVa6pLK.js → SettingsPage-BQwB0r9k.js} +1 -1
  9. package/assets/assets/{SiteHealthSection-CizmiBjA.js → SiteHealthSection-C0aJ_UhN.js} +3 -3
  10. package/assets/assets/{TrafficPage-N7sZgb9x.js → TrafficPage-DTic3zhO.js} +1 -1
  11. package/assets/assets/{TrafficSourceDetailPage-BNQmMJ5D.js → TrafficSourceDetailPage-BKfabnCw.js} +1 -1
  12. package/assets/assets/{extract-error-message-Bh9mRIz9.js → extract-error-message-BzB8j3fC.js} +1 -1
  13. package/assets/assets/{index-BnR1Tu9j.js → index-DQGEzxrN.js} +3 -3
  14. package/assets/assets/{react-sigma_core.esm.min-DGaYwjLZ.js → react-sigma_core.esm.min-rYv0aKKx.js} +1 -1
  15. package/assets/assets/{v2-overview-adapter-eqN-8OK5.js → v2-overview-adapter-CWWPfsm-.js} +1 -1
  16. package/assets/index.html +1 -1
  17. package/dist/{chunk-MEQGGODM.js → chunk-5K2NUQOV.js} +34 -5
  18. package/dist/{chunk-3DL3KV6C.js → chunk-5ZIUROAQ.js} +48 -0
  19. package/dist/{chunk-ZWVXUPLP.js → chunk-BS4ZC7FG.js} +141 -25
  20. package/dist/{chunk-66KGNC4U.js → chunk-NKEKDWGX.js} +2 -2
  21. package/dist/{chunk-LHHJVGH7.js → chunk-WSYJ4IT7.js} +43 -15
  22. package/dist/cli.js +17 -15
  23. package/dist/index.js +4 -4
  24. package/dist/{intelligence-service-7XX5ZRYE.js → intelligence-service-D2HY2S5F.js} +2 -2
  25. package/dist/mcp.js +5 -4
  26. package/package.json +11 -11
@@ -1,4 +1,4 @@
1
- import{j as e,r as l,u as Te,L as As,h as ms,o as Tt,B as ni,C as Zo,D as xc,k as pc,l as gc}from"./vendor-tanstack-ZXXkndVj.js";import{T as ue,t as fc,a as yc,M as el,I as Ve,s as tl,B as P,b as bc,u as sl,C as vc,P as Ln,h as jc,c as Nc,d as mn,g as nl,e as al,f as ye,i as Y,j as ie,k as Nt,l as Ye,m as wc,n as Sc,o as Cc,p as rl,q as kc,r as Ac,v as bn,S as hn,w as Pc,x as Rc,y as _s,z as Ht,A as Ic,D as Si,E as il,G as Ut,F as ai,H as Tc,J as $c,K as Mc,L as Lc,N as Ci,O as $e,Q as qc,R as Ec,U as er,V as Dc,W as Oc,X as Fc,Y as Kc,Z as Gc,_ as _c,$ as Uc,a0 as Bc,a1 as Vc,a2 as Qc,a3 as zc,a4 as Wc,a5 as Hc,a6 as Yc,a7 as Jc,a8 as ol,a9 as Ys,aa as Xc,ab as ll,ac as Oa,ad as Zc,ae as Je,af as ed,ag as td,ah as sd,ai as Fa,aj as nd,ak as ad,al as rd,am as pn,an as id,ao as od,ap as ld,aq as cl,ar as Fr,as as cd,at as ri,au as dd,av as ea,aw as Js,ax as Bt,ay as ud,az as md,aA as hd,aB as tr,aC as Et,aD as xd,aE as pd,aF as gd,aG as fd,aH as yd,aI as Xn,aJ as ki,aK as ya,aL as sr,aM as bd,aN as vd,aO as Ai,aP as nr,aQ as xn,aR as jd,aS as dl,aT as ul,aU as Nd,aV as wd,aW as Pi,aX as Sd,aY as Cd,aZ as kd,a_ as Ad,a$ as Pd,b0 as Rd,b1 as Id,b2 as Td,b3 as $d,b4 as Md,b5 as Ld,b6 as qd,b7 as Ed,b8 as Dd,b9 as Od,ba as Fd,bb as Kd,bc as Gd,bd as _d,be as Ud,bf as Bd,bg as Vd,bh as Qd,bi as zd,bj as Wd,bk as Hd,bl as Yd,bm as Jd,bn as Ns,bo as Xd,bp as xt,bq as Zd,br as eu,bs as tu,bt as su,bu as nu,bv as au,bw as ru,bx as iu,by as ou,bz as lu,bA as cu,bB as du,bC as uu,bD as mu,bE as hu,bF as xu,bG as pu,bH as gu,bI as fu,bJ as yu,bK as bu,bL as vu,bM as ju,bN as Ri,bO as Ii,bP as Ti,bQ as Nu,bR as wu,bS as Su,bT as Cu,bU as ku,bV as Au,bW as Pu,bX as Ru,bY as Iu,bZ as Tu,b_ as $u,b$ as Mu,c0 as Lu,c1 as qu,c2 as Eu,c3 as Du,c4 as Ou,c5 as Fu,c6 as Ku,c7 as Gu,c8 as ml,c9 as ar,ca as _u,cb as $i,cc as Uu,cd as Bu,ce as Vu,cf as Qu,cg as zu,ch as Wu,ci as Hu,cj as hl,ck as Yu,cl as xl,cm as pl,cn as gl,co as fl,cp as Ju,cq as Xu,cr as Zu,cs as em,ct as tm,cu as sm,cv as Mi,cw as nm,cx as am,cy as rm,cz as im,cA as om,cB as Li,cC as lm,cD as cm,cE as dm,cF as um,cG as mm,cH as hm,cI as Ka,cJ as xm,cK as rr,cL as pm,cM as gm,cN as fm,cO as ym,cP as bm,cQ as vm,cR as jm,cS as Nm,cT as wm,cU as Sm,cV as yl,cW as Cm,cX as km,cY as Am,cZ as Pm,c_ as Rm,c$ as Im,d0 as ba,d1 as Tm,d2 as $m,d3 as Mm,d4 as qi,d5 as Lm}from"./index-BnR1Tu9j.js";import{C as gn,e as Ga,q as ta,U as qm,r as Em,L as Dm,s as Om,i as Fm,P as _a,D as bl,t as Km,u as vl,v as Gm,d as _m,E as Um,p as Bm,w as Vm,x as jl}from"./vendor-lucide-CW2qe0uH.js";import{R as Qm}from"./RunRow-BjrSRp6X.js";import{u as fn,D as zs,a as Ls,b as Nl,M as qa,c as Rs,S as zm}from"./SiteHealthSection-CizmiBjA.js";import{C as sa,f as yn,a as ds,b as Ft,c as Vt,d as ts,e as rt,g as us,h as qs,M as wl,i as Sl,o as Es,j as Ws,p as Wm}from"./ChartPrimitives-Bxa_vFmq.js";import{u as Hm,a as Ym,b as Jm,t as Xm,e as Zm,c as ft}from"./extract-error-message-Bh9mRIz9.js";import{R as Xs,C as Zs,a as na,X as en,Y as tn,T as sn,b as Kr,L as Ua,A as Bs,d as Ms,e as eh}from"./vendor-recharts-D-cUuLZo.js";import{A as Cl,a as th,b as sh,c as nh}from"./v2-overview-adapter-eqN-8OK5.js";import{A as ah}from"./AuditHistoryPanel-9F_74jKS.js";import"./vendor-radix-twS1M3FF.js";import"./vendor-markdown-B-Oq2NYq.js";import"./vendor-yaml-GWJz5H2G.js";function Hs(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 rh(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=ih(r,1));return a}function ih(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 oh(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 lh(t,s){const n=oh(t,s);return n===null?null:Math.round(n*100)}function ir(t,s,n="vs prior 7 days"){return t.deltaPct===null?t.prior===0?"First baseline week":"":t.deltaPct>0?`Up ${t.deltaPct}% ${n} (${Hs(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${Hs(t.prior)} ${s})`:`Flat ${n} (${Hs(t.prior)} ${s})`}const kl=30;function Ei(t){return Math.round(t*10)/10}function ch(t){return t.prior>=kl&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% vs prior`:`${t.deltaAbs>0?"+":""}${Ei(t.deltaAbs)} vs ${Ei(t.prior)}`}function dh(t,s,n){return t.prior>=kl&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% ${n}`:`${t.deltaAbs>0?"+":""}${Hs(Math.round(t.deltaAbs))} ${s} ${n}`}function uh(t,s="UTC"){const n=new Date(t);if(!Number.isFinite(n.getTime()))return null;const a={weekday:"short",year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"};try{return n.toLocaleString("en-US",{...a,timeZone:s})}catch{return n.toLocaleString("en-US",{...a,timeZone:"UTC"})}}const mh=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function Al(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function Pl(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 Rl(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(Al).map(Pl).filter(Boolean)):new Set}function Il(t,s){const n=Al(t).map(Pl).filter(Boolean).filter(a=>!mh.has(a)).filter(a=>!s.has(a));return[...new Set(n)].sort().join(" ")}function hh(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function xh(t,s){const n=Rl(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=Il(hh(o),n);!i||a.has(i)||(a.add(i),r.push(o))}return r}function ph(t){const s=Rl(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const a=new Set;return n.filter(r=>{const o=Il(r.query,s);return!o||a.has(o)?!1:(a.add(o),!0)})}const gh=1e6;function fh(t,s="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:s}).format(t/gh)}const ii={queryClass:"all"},yh=["all","non-brand","branded"];function Tl(t){return typeof t=="string"&&yh.includes(t)}function $l(t){const s=Tl(t.class)?t.class:ii.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 bh(t,s){return s===null||t===null?!1:t!==s}function vh(t){return{scope:t.scope==="group"&&t.groupKey?`group:${t.groupKey}`:void 0,class:t.queryClass===ii.queryClass?void 0:t.queryClass}}function jh(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 Nh(t){const s=h=>typeof t[h]=="string"&&t[h]!==""?t[h]:void 0,n=$l({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==="unknown"||Tl(o)?o:ii.queryClass};i.measurementScope!=="project"&&(i.measurementScopeKey=r);for(const[h,m]of[["measurementMarketKey","marketKey"],["measurementProvider","provider"],["measurementModel","model"],["measurementLocation","location"],["measurementFrom","from"],["measurementTo","to"],["measurementRunId","measurementRunId"],["measurementQueryKey","queryKey"]]){const u=s(h);u!==void 0&&(i[m]=u)}const c=Number(t.measurementRevision);Number.isSafeInteger(c)&&c>0&&(i.revision=c);const d=jh(t.measurementAnswer,i.queryKey);return d&&(i.answer=d),i}function wh(t,s){const n={...t,...s};return["measurementScope","measurementScopeKey","measurementMarketKey","queryClass","measurementProvider","measurementModel","measurementLocation","measurementFrom","measurementTo","measurementRevision","measurementRunId"].some(a=>a in s)?(n.measurementQueryKey=s.measurementQueryKey,n.measurementAnswer=s.measurementAnswer):"measurementQueryKey"in s&&!("measurementAnswer"in s)&&(n.measurementAnswer=void 0),"measurementScope"in s&&(n.scope=void 0,"measurementMarketKey"in s||(n.measurementMarketKey=void 0),n.measurementQueryKey=void 0,s.measurementScope==="project"&&(n.measurementScopeKey=void 0)),"queryClass"in s&&(n.class=void 0),n}function Gr({state:t,label:s}){return e.jsx(ue,{tone:yc(t),children:s??fc(t)})}const an=[{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],Di={"non-brand":"Non-brand",branded:"Branded",pooled:"All queries"},Sh={"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."},Ch="Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other.";function kh(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 Ah({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(Ve,{text:Ch})]}),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 Ph({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,d=c?a:"non-brand",h=i?"pooled":d,m=d==="branded"?t.branded:t.breakdown,u=d==="branded"?t.breakdown:t.branded,b=kh(m,{hasCompetitors:n.length>0,unavailable:t.unavailable===!0,noRun:t.breakdown.snapshotsTotal===0&&t.branded.snapshotsTotal===0,otherClassHasData:u.snapshotsTotal>0}),p=h==="non-brand"?el[t.tone]:"text-secondary";function x(g){const f=an.findIndex(j=>j.value===d);let S=null;g.key==="ArrowRight"||g.key==="ArrowDown"?S=(f+1)%an.length:g.key==="ArrowLeft"||g.key==="ArrowUp"?S=(f-1+an.length)%an.length:g.key==="Home"?S=0:g.key==="End"&&(S=an.length-1),S!==null&&(g.preventDefault(),r(an[S].value),g.currentTarget.querySelectorAll('[role="radio"]')[S]?.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(Ve,{text:Sh[h]})]}),c?e.jsx("div",{role:"radiogroup","aria-labelledby":o,className:"segmented flex-wrap",onKeyDown:x,children:an.map(g=>{const f=g.value===d;return e.jsx("button",{type:"button",role:"radio","aria-checked":f,tabIndex:f?0:-1,onClick:()=>r(g.value),className:`segmented-option min-h-11 ${f?"segmented-option-active":""}`,children:g.label},g.value)})}):e.jsx("span",{className:"mention-share-class",children:Di[h]})]}),b.numeric?e.jsxs("p",{className:`mention-share-value ${p}`,children:[b.headline,e.jsx("span",{className:"text-faint",children:"%"})]}):e.jsx("p",{className:"mention-share-value-text",children:b.headline}),e.jsxs("p",{className:"mention-share-caption",children:[e.jsx("span",{className:"mention-share-caption-scope",children:Di[h]}),` · ${b.detail}`]}),i&&e.jsx("p",{className:"mention-share-note",children:"Set a brand name to split branded from non-brand."}),b.showRows&&e.jsx(Ah,{breakdown:m,projectLabel:s,competitorDomains:n})]})}const rn=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],Oi=5;function Rh(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 Ih(t){return t?t.evidence.answeredResults>0||t.evidence.sourceResults>0?"measured":"not-measured":"unavailable"}function or(t){return t==="unavailable"?"Unavailable":"Not measured"}function Ml(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 Th({value:t,onChange:s}){function n(a){const r=rn.findIndex(c=>c.value===t);let o=null;if(a.key==="ArrowRight"||a.key==="ArrowDown"?o=(r+1)%rn.length:a.key==="ArrowLeft"||a.key==="ArrowUp"?o=(r-1+rn.length)%rn.length:a.key==="Home"?o=0:a.key==="End"&&(o=rn.length-1),o===null)return;a.preventDefault();const i=rn[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:rn.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 _r({row:t,isProject:s=!1,metricState:n="measured",shareContext:a,canManage:r,onPin:o,onUnpin:i}){const c=!s&&r&&!t.pinned&&!!o,d=!s&&r&&t.pinned&&!!i,h=n==="measured",m=h&&t.sampleUrls.length>0,[u,b]=l.useState(!1),[p,x]=l.useState(null);async function g(f,S){if(!(!S||u)){b(!0),x(null);try{await S(t.domain)===!1&&x(`Could not ${f} competitor. Try again.`)}catch{x(`Could not ${f} competitor. Try again.`)}finally{b(!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":Ml(t.surfaceClass)}),e.jsx("td",{className:"tabular-nums text-strong",children:h?bc(t.shareOfVoice,a):or(n)}),e.jsx("td",{className:"tabular-nums text-secondary",children:h?t.mentionCount:or(n)}),e.jsx("td",{className:"tabular-nums text-secondary",children:h?t.citationCount:or(n)}),e.jsx("td",{className:"text-right",children:c||d||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(f=>e.jsx("li",{className:"break-all",children:f},f))})]}):null,d&&i?e.jsxs(P,{type:"button",size:"sm",variant:"outline",disabled:u,onClick:()=>{g("unpin",i)},children:["Unpin"," ",e.jsx("span",{className:"sr-only",children:t.domain})]}):null,c&&o?e.jsxs(P,{type:"button",size:"sm",variant:"outline",disabled:u,onClick:()=>{g("pin",o)},children:["Pin"," ",e.jsx("span",{className:"sr-only",children:t.domain})]}):null,p?e.jsx("span",{role:"alert",className:"sr-only",children:p}):null]}):e.jsx("span",{className:"text-faint",children:"—"})})]})}function Ur({children:t}){return e.jsx("tr",{className:"competitor-landscape-group",children:e.jsx("th",{scope:"rowgroup",colSpan:6,children:t})})}function $h({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(Ur,{children:"Observed in this window"}),i.map(c=>e.jsx(_r,{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(P,{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 Mh({onAddCompetitor:t}){const s=l.useId(),[n,a]=l.useState(""),[r,o]=l.useState(!1),[i,c]=l.useState(null);async function d(){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(),d()},"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(P,{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 Lh({window:t,landscape:s,pinnedFallback:n=[],canWrite:a,isEmbed:r,onWindowChange:o,onPin:i,onUnpin:c,onAddCompetitor:d,error:h,onRetry:m,isLoading:u=!1,scopeLabel:b}){const p=a&&!r,x=s?.pinned??n,g=s?.observed??[],f=s?.otherSources??[],S=s?.evidence,j=Ih(s),D=s?.marketState?.draft?.pendingCompetitorDomains.length??0;return e.jsxs("section",{"aria-labelledby":"competitor-landscape-title","aria-busy":u,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"}),b?e.jsx("p",{className:"supporting-copy mt-1",children:b}):null,s?e.jsx("p",{className:"supporting-copy mt-1",children:Rh(s.filters?.queryClass)}):null,s?.reason?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:tl(s.reason)}):null]}),e.jsx(Th,{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(P,{type:"button",size:"sm",variant:"outline",onClick:m,children:"Retry competitor history"}):null]}):null,u&&!s&&x.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(Ur,{children:"You"}),e.jsx(_r,{row:s.project,shareContext:s,isProject:!0,metricState:j,canManage:!1})]}):null,e.jsx(Ur,{children:"Pinned"}),x.length>0?x.map(A=>e.jsx(_r,{row:{...A,pinned:!0},shareContext:s,metricState:j,canManage:p,onUnpin:c},A.domain)):e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"text-secondary",children:"No pinned competitors."})})]}),s&&g.length>0?e.jsx($h,{shareContext:s,rows:g,canManage:p,onPin:i},JSON.stringify([t,s.project.domain,s.scope,s.filters])):null]})}),S?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:[S.answeredResults," ",S.answeredResults===1?"answer":"answers"]}),S.missingAnswerTextResults>0?e.jsx("span",{className:"text-caution",children:"Answer data incomplete"}):null,S.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(gn,{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:[g.length===0?e.jsx("p",{children:"No additional competitors were identified in this period."}):null,e.jsxs("p",{children:[S.sourceResults," ",S.sourceResults===1?"result includes":"results include"," source URLs."]}),S.missingAnswerTextResults>0?e.jsxs("p",{children:[S.missingAnswerTextResults," ",S.missingAnswerTextResults===1?"result has":"results have"," no answer text and ",S.missingAnswerTextResults===1?"is":"are"," excluded from mention share."]}):null,S.incompleteSourceResults>0?e.jsxs("p",{children:[S.incompleteSourceResults," ",S.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,S.excludedProbeResults+S.excludedNonCompletedResults>0?e.jsxs("p",{children:[S.excludedProbeResults+S.excludedNonCompletedResults," test or unfinished ",S.excludedProbeResults+S.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,D>0?e.jsx("p",{className:"text-sm text-secondary",children:s?.scope.kind==="all-markets"?`${D} competitor${D===1?" is":"s are"} pending publication across markets.`:`${D} competitor${D===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(A=>e.jsxs("li",{children:[A.name," · ",A.answerCount," answers"]},A.name))})]}):null,f.length>0?e.jsxs("details",{className:"inline-disclosure",children:[e.jsxs("summary",{children:["Other observed sources (",f.length,")"]}),e.jsx("ul",{className:"mt-3 space-y-2 text-sm text-secondary",children:f.map(A=>e.jsxs("li",{children:[e.jsxs("span",{children:[A.label," · ",Ml(A.surfaceClass)," · ",A.citationCount," citations"]}),A.sampleUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1 font-mono text-[11px] text-muted",children:A.sampleUrls.map(y=>e.jsx("li",{className:"break-all",children:y},y))}):null]},A.domain))})]}):null]}),p&&d?e.jsx(Mh,{onAddCompetitor:d}):null]})}function Fi({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"}),d=n.map((h,m)=>{const u=new Date(h.createdAt).toLocaleDateString();return`${m===o?"Latest run, ":""}${u}: ${h.citationState}${h.model?`, model ${h.model}`:""}`}).join("; ");return e.jsxs("div",{className:"flex items-center gap-1",role:"img","aria-label":`Citation history across ${n.length} runs. ${d}`,children:[e.jsx("span",{className:"text-[9px] text-faint shrink-0","aria-hidden":"true",children:i}),e.jsx("div",{className:"flex items-center gap-[3px]",title:`${n.length} runs`,"aria-hidden":"true",children:n.map((h,m)=>{const u=!!(h.model&&m>0&&n[m-1]?.model&&n[m-1].model!==h.model),b=m===o;return e.jsx("span",{className:`h-2.5 w-2.5 ${r[h.citationState]??"rounded-sm"} ${a[h.citationState]??"bg-mono-700"} ${u?"ring-1 ring-caution-300/80 ring-offset-1 ring-offset-bg":""} ${b?"outline outline-1 outline-offset-2 outline-mono-400":""}`,title:[h.citationState,new Date(h.createdAt).toLocaleDateString(),h.model?`model ${h.model}`:null,u?"model changed":null,b?"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 Br(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 qh=320;function Eh(t){return t==="branded"?"Branded":t==="non-brand"?"Non-brand":"Unclassified"}function Dh(t){return[t.phrase,t.location??"",...t.rawItems.map(s=>s.provider)].join(" ")}function Ki(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 Gi(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 _i(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 Oh(t,s){return t.map(n=>Ll(n,s))}function Ll(t,s){return s==="citations"?t:{...t,citationState:Ki(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:Ki(n,s)}))}}function Ui(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 Fh(t){const s=Br(Oh(t,"mentions")),n=Br(t);return[Ui(s,"mentions"),Ui(n,"citations")]}function Kh({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 Bi({items:t}){return e.jsx("div",{className:"mt-1 flex flex-wrap gap-1","aria-label":"Latest run mention and citation signals",children:Fh(t).map(s=>e.jsx(Kh,{signal:s},s.key))})}function Gh({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:a}=sl(),[r,o]=l.useState(new Set),[i,c]=l.useState("mentions"),[d,h]=l.useState(n),[m,u]=l.useState("all"),b=l.useMemo(()=>{const y=new Map;for(const w of t){const N=w.query,M=w.queryClass??null,L=s?w.location??null:null,F=JSON.stringify([N,M,L]),H=y.get(F)??{key:F,phrase:N,queryClass:M,location:L,items:[],rawItems:[]};H.items.push(Ll(w,i)),H.rawItems.push(w),y.set(F,H)}return[...y.values()]},[t,i,s]),p=l.useMemo(()=>b.filter(y=>m==="all"||(m==="unclassified"?y.queryClass===null:y.queryClass===m)),[b,m]),x=fn({rows:p,getSearchText:Dh}),g=x.rows.map(y=>y.key),f=g.length>0&&g.every(y=>r.has(y)),S=y=>{o(w=>{const N=new Set(w);return N.has(y)?N.delete(y):N.add(y),N})},j=i==="mentions"?"mentioned":"cited",D=i==="mentions"?"Mention History":"Citation History",A=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(y=>{const w=new Set(y);for(const N of g)f?w.delete(N):w.add(N);return w})},children:f?"Collapse page":"Expand page"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Density"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-bg-elevated/60 border border-subtle",role:"tablist","aria-label":"Evidence row density",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":d==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${d==="compact"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>h("compact"),children:"Compact"}),e.jsx("button",{type:"button",role:"tab","aria-selected":d==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${d==="detailed"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>h("detailed"),children:"Detailed"})]})]})]})]}),b.length>0?e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-3",children:[e.jsx(zs,{value:x.query,onChange:x.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:y=>{u(y.target.value),x.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:D}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:x.rows.map(({key:y,phrase:w,queryClass:N,location:M,items:L,rawItems:F})=>{const H=r.has(y),O=L.map(q=>q.citationState),J=O.includes("cited")?"cited":O.includes("emerging")?"emerging":O.includes("lost")?"lost":O.every(q=>q==="pending")?"pending":"not-cited",G=Br(L),C=L.filter(q=>q.citationState===vc.cited||q.citationState==="emerging").length,ae=_i(G,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:()=>S(y),onKeyDown:q=>{(q.key==="Enter"||q.key===" ")&&(q.preventDefault(),S(y))},tabIndex:0,role:"button","aria-expanded":H,children:[e.jsx("td",{children:e.jsx(Ga,{size:14,className:`transition-transform duration-150 text-muted ${H?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-heading",children:w}),s&&e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-muted",children:M??"No location"}),e.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[e.jsx(ue,{tone:"neutral",className:"whitespace-nowrap",children:Eh(N)}),L.map(q=>e.jsx(Ln,{provider:q.provider},q.id))]})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gr,{state:J,label:Gi(J,i)}),e.jsxs("span",{className:"text-[11px] text-muted",title:`${C} of ${L.length} engines ${A}`,children:[C,"/",L.length]})]})}),e.jsx("td",{children:e.jsx(Fi,{history:G})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:ae}),e.jsx(Bi,{items:F})]}),e.jsx("td",{})]}),H&&L.map((q,se)=>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(Ln,{provider:q.provider})}),e.jsx("td",{children:e.jsx(Gr,{state:q.citationState,label:Gi(q.citationState,i)})}),e.jsx("td",{children:e.jsx(Fi,{history:q.runHistory})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:_i(q.runHistory,i)}),e.jsx(Bi,{items:[F[se]??q]})]}),e.jsx("td",{children:e.jsx(P,{variant:"ghost",size:"sm",type:"button",onClick:V=>{V.stopPropagation(),a(q.id)},children:"View"})})]}),d==="detailed"&&e.jsxs("tr",{className:"bg-surface-subtle",children:[e.jsx("td",{}),e.jsx("td",{colSpan:5,className:"px-5 pb-4",children:e.jsx(Bh,{item:q,onViewFull:()=>a(q.id)})})]})]},q.id))]},y)})})]})}),x.totalRows===0&&(x.hasQuery||m!=="all")?e.jsx("p",{className:"supporting-copy mt-3",children:"No tracked queries match this filter."}):null,e.jsx(Ls,{page:x.page,pageSize:x.pageSize,visibleRows:x.rows.length,totalRows:x.totalRows,onPageChange:x.setPage,itemLabel:x.hasQuery||m!=="all"?"matches":"queries"}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",j==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function _h(t){const s=(t.matchedTerms??[]).filter(r=>r.trim().length>2),n=[...(t.mentionedCompetitorDomains??[]).flatMap(r=>{const o=Nc(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 Vi(t,s){const n=s.toLowerCase().replace(/^www\./,"");return(t.citedCompetitorDomains??[]).some(a=>a.toLowerCase().replace(/^www\./,"")===n)}function Uh(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 Bh({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}=Uh(t.answerSnippet,qh),o=_h(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:jc(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] ${Vi(t,i)?"border-negative-900/40 bg-negative-950/30 text-negative":"border-mono-700/60 bg-bg-elevated/60 text-neutral"}`,children:[i,Vi(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 va({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 Ha({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 lr=rt[0],cr=rt[1],Qi=rt[2],zi=rt[3],Vh=["both","server","ga4"],Wi={fontSize:11,paddingTop:6},Hi=new Set(["Pages crawled trend","Page fetches trend","Visits trend"]),Yi=t=>typeof t=="number"?Hs(Math.round(t)):String(t),rs=t=>typeof t=="number"&&Number.isFinite(t)?t:0;function dr(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 ur({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(Ve,{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 Qh(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 zh({projectName:t,sinceMinutes:s}){const[n,a]=l.useState(!0),[r,o]=l.useState(!0),[i,c]=l.useState("both"),d=Hm(t,{sinceMinutes:s,granularity:"day",limit:1}),h=Ym(t),u=Te({...nl({client:Y,path:{name:t}}),enabled:!!t,staleTime:mn}).data?.connected===!0,b=Te({...al({client:Y,path:{name:t},query:{window:s>=2160*60?"90d":s>=720*60?"30d":"7d"}}),enabled:!!t&&u,staleTime:mn}),p=l.useMemo(()=>d.data?.series?.points??[],[d.data]),x=l.useMemo(()=>{const M=b.data;return new Map((M?.days??[]).map(L=>[L.date,L.sessions]))},[b.data]),g=l.useMemo(()=>{const M=F=>F.measured!==!1;if(p.length===0||M(p[0]))return null;const L=p.findIndex(M)-1;return L<0?{from:p[0].bucket,to:p[p.length-1].bucket}:{from:p[0].bucket,to:p[L].bucket}},[p]),f=d.data?.series?.coverageStart??null,S=d.data?.series?.trends,j=l.useMemo(()=>{const M=dr(S?.crawlerContentHits,p.length),L=dr(S?.aiUserFetchHits,p.length),F=dr(S?.aiReferralLandedHits,p.length);return p.map((H,O)=>({...H,crawlerContentHits:H.measured!==!1?rs(H.crawlerContentHits):null,aiUserFetchHits:H.measured!==!1?rs(H.aiUserFetchHits):null,aiReferralLandedHits:H.measured!==!1?rs(H.aiReferralLandedHits):null,ga4Visits:x.get(H.bucket)??null,crawlTrend:M[O],fetchTrend:L[O],visitTrend:F[O]}))},[p,x,S]),D=d.data?.totals,A=D&&{crawlers:rs(D.crawlerContentHits),fetches:rs(D.aiUserFetchHits),visits:rs(D.aiReferralLandedHits)},y=l.useMemo(()=>p.reduce((M,L)=>({crawlers:M.crawlers+rs(L.crawlerContentHits),fetches:M.fetches+rs(L.aiUserFetchHits),visits:M.visits+rs(L.aiReferralLandedHits)}),{crawlers:0,fetches:0,visits:0}),[p]),w=A??y,N=w.crawlers>0||w.fetches>0||w.visits>0;if(d.isLoading)return e.jsx(ye,{className:"surface-card p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading AI traffic history…"})});if(d.isError)return e.jsxs(ye,{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(!N){const M=h.data?.sources,L=M!==void 0&&M.length===0,F=!L&&f===null;return e.jsxs(ye,{className:"surface-card p-5",children:[e.jsx("p",{className:"text-sm text-secondary",children:L?"No server-side traffic source connected yet.":F?"No AI activity recorded yet.":"No AI activity recorded in this period."}),e.jsx("p",{className:"text-xs text-muted mt-1",children:L?"Connect a traffic source to see how AI engines read this site over time.":F?"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(ye,{className:"surface-card p-5",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3 mb-5",children:[e.jsx(ur,{label:"AI crawlers",value:Hs(w.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(ur,{label:"AI page fetches",value:Hs(w.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(ur,{label:"AI visitors",value:Hs(w.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."})]}),p.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:rs(p[p.length-1].crawlerContentHits).toLocaleString()}),"pages crawled"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:rs(p[p.length-1].aiUserFetchHits).toLocaleString()}),"page fetches"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:rs(p[p.length-1].aiReferralLandedHits).toLocaleString()}),"visits, server"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:x.get(p[p.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(Ve,{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:M=>a(M.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:M=>o(M.target.checked),className:"accent-current"}),"Trend line"]})]})]}),e.jsx(Xs,{width:"100%",height:206,children:e.jsxs(Zs,{data:j,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(na,{stroke:sa,vertical:!1}),e.jsx(en,{dataKey:"bucket",tick:Ft,stroke:ds,tickFormatter:yn,minTickGap:28}),e.jsx(tn,{tick:Ft,stroke:ds,width:48,allowDecimals:!1}),e.jsx(sn,{contentStyle:ts.contentStyle,labelStyle:ts.labelStyle,itemStyle:ts.itemStyle,labelFormatter:Vt,formatter:Yi}),g&&e.jsx(Kr,{x1:g.from,x2:g.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(Ua,{wrapperStyle:Wi,iconType:"plainline",iconSize:14,formatter:M=>Hi.has(M)?"":M}),e.jsx(Bs,{type:"monotone",dataKey:"crawlerContentHits",name:"Pages crawled",stroke:lr,fill:lr,fillOpacity:.22,strokeWidth:1.8}),n&&e.jsx(Bs,{type:"monotone",dataKey:"aiUserFetchHits",name:"Page fetches",stroke:cr,fill:cr,fillOpacity:.18,strokeWidth:1.6}),r&&e.jsx(Ms,{type:"linear",dataKey:"crawlTrend",name:"Pages crawled trend",dot:!1,tooltipType:"none",stroke:lr,strokeWidth:1.4,strokeDasharray:"5 4",connectNulls:!0}),r&&n&&e.jsx(Ms,{type:"linear",dataKey:"fetchTrend",name:"Page fetches trend",dot:!1,tooltipType:"none",stroke:cr,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(Ve,{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(Ha,{windows:Vh,value:i,onChange:c,label:"Visit measurement source",formatOption:M=>M==="ga4"?"GA4":M==="both"?"Both":"Server"})]}),e.jsx(Xs,{width:"100%",height:176,children:e.jsxs(Zs,{data:j,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(na,{stroke:sa,vertical:!1}),e.jsx(en,{dataKey:"bucket",tick:Ft,stroke:ds,tickFormatter:yn,minTickGap:28}),e.jsx(tn,{tick:Ft,stroke:ds,width:48,allowDecimals:!1}),e.jsx(sn,{contentStyle:ts.contentStyle,labelStyle:ts.labelStyle,itemStyle:ts.itemStyle,labelFormatter:Vt,formatter:Yi}),g&&e.jsx(Kr,{x1:g.from,x2:g.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(Ua,{wrapperStyle:Wi,iconType:"plainline",iconSize:14,formatter:M=>Hi.has(M)?"":M}),i!=="ga4"&&e.jsx(Ms,{type:"monotone",dataKey:"aiReferralLandedHits",name:"Visits, server",stroke:Qi,strokeWidth:2,dot:!1}),i!=="server"&&e.jsx(Ms,{type:"monotone",dataKey:"ga4Visits",name:"Visits, GA4",connectNulls:!1,stroke:zi,strokeWidth:1.8,strokeDasharray:"5 3",dot:Qh(j.map(M=>M.ga4Visits),zi)}),r&&i!=="ga4"&&e.jsx(Ms,{type:"linear",dataKey:"visitTrend",name:"Visits trend",dot:!1,tooltipType:"none",stroke:Qi,strokeWidth:1.3,strokeDasharray:"5 4",connectNulls:!0})]})})]})}const Wh=6,qn="__other__",$n="_socialTotal";function Hh(t,s=Wh){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,u)=>u[1]!==m[1]?u[1]-m[1]:m[0].localeCompare(u[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 u=c.get(m.date);u||(u={date:m.date,[$n]:0},c.set(m.date,u));const b=o.has(m.source)?m.source:qn;u[b]=(u[b]??0)+m.sessions,u[$n]=(u[$n]??0)+m.sessions}const d=[...c.values()].sort((m,u)=>String(m.date).localeCompare(String(u.date))),h=r.map(([m])=>m);return i>0&&h.push(qn),{data:d,sources:h,otherCount:i}}function Mn(t){return t.replace(/\+/g," ")}function ql(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const Ji="_totalSessions",Xi="_organicSessions";function Yh(t,s){const n=new Map;for(const i of s)n.set(i.date,{[Ji]:i.sessions,[Xi]:i.organicSessions});for(const i of t.days){let c=n.get(i.date);c||(c={[Ji]:0,[Xi]:0},n.set(i.date,c));for(const d of i.bySource)c[d.source]=(c[d.source]??0)+d.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 Jh=["7d","30d","90d"],Xh={"7d":10080,"30d":720*60,"90d":2160*60,all:2160*60},Us=rt,Vr=us.textDim,El=us.textFaint,_n=25;function Zh(t){return Nl(t.landingPage)}const ex=25,tx=10,mr={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0};function ja(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function Dl(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({projectName:t}){const{data:s,isLoading:n,isError:a}=Jm(t);if(n)return e.jsx(ye,{className:"p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading server activity…"})});if(a)return e.jsx(ye,{className:"p-5",children:e.jsx("div",{className:"text-sm text-negative-400",children:"Failed to load server activity."})});const 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."," ",!ie()&&e.jsx(As,{to:"/traffic",className:"text-link hover:underline",children:"Manage sources →"})]})]})}),r.length===0?e.jsx(ye,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-secondary",children:["No server traffic source connected yet."," ",!ie()&&e.jsxs(e.Fragment,{children:[e.jsx(As,{to:"/traffic",className:"text-link hover:underline",children:"Connect a traffic source"})," ","to surface bot crawls and AI referrals straight from server logs."]})]})}):e.jsx(ye,{className:"overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-bg-elevated/50 text-[10px] uppercase tracking-wide text-muted",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Source"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Status"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Crawler hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI sessions 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Last sync"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium","aria-label":"open"})]})}),e.jsx("tbody",{children: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(ue,{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?Dl(o.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:ie()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(As,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:o.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},o.id))})]})})]})}function nx({projectName:t}){const[s,n]=l.useState("30d");return e.jsxs("div",{className:"space-y-10",children:[e.jsx(sx,{projectName:t}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(Ha,{windows:Jh,value:s,onChange:n,label:"Traffic time period"})}),e.jsx(ax,{projectName:t,window:s}),e.jsx(zh,{projectName:t,sinceMinutes:Xh[s]})]})}function ax({projectName:t,window:s}){const n=ms(),a=s??"30d",[r,o]=l.useState(null),[i,c]=l.useState(null),[d,h]=l.useState(!0),[m,u]=l.useState(!1),[b,p]=l.useState(!1),[x,g]=l.useState(null),[f,S]=l.useState(null),[j,D]=l.useState("sessions"),[A,y]=l.useState("desc"),[w,N]=l.useState("sessions"),[M,L]=l.useState("desc"),[F,H]=l.useState("sessions"),[O,J]=l.useState("desc"),[G,C]=l.useState("sessions"),[ae,q]=l.useState("desc"),[se,V]=l.useState(mr),[B,E]=l.useState([]),[R,oe]=l.useState([]),[T,ee]=l.useState(!1);async function Z(te){h(!0),g(null);try{const qe=await n.fetchQuery({...nl({client:Y,path:{name:t}}),staleTime:mn});if(te.current)return;if(o(qe),!qe.connected){c(null),V(mr),E([]),oe([]),h(!1);return}const Ce=a==="all"?void 0:a,Pe=await n.fetchQuery({...wc({client:Y,path:{name:t},query:Ce?{window:Ce}:void 0}),staleTime:mn}).then(mt=>mt),Yt=Pe.windowStart||Pe.windowEnd?{...Pe.windowStart?{startDate:Pe.windowStart}:{},...Pe.windowEnd?{endDate:Pe.windowEnd}:{}}:void 0,[Jt,yt,St]=await Promise.all([n.fetchQuery({...al({client:Y,path:{name:t},query:Ce?{window:Ce}:void 0}),staleTime:mn}).catch(()=>mr),n.fetchQuery({...Sc({client:Y,path:{name:t},query:Ce?{window:Ce}:void 0}),staleTime:mn}).catch(()=>[]),n.fetchQuery({...Cc({client:Y,path:{name:t},query:Yt}),staleTime:mn}).catch(()=>[])]);if(te.current)return;c(Pe),V(Jt),E(yt),oe(St),h(!1)}catch(qe){if(te.current)return;g(qe instanceof Error?qe.message:"Failed to load GA4 data"),h(!1)}}l.useEffect(()=>{const te={current:!1};return Z(te),()=>{te.current=!0}},[t,a,n]);async function ge(){u(!0),g(null),S(null);try{const te=await rl(t);S(`Synced ${te.rowCount.toLocaleString()} page rows, ${te.aiReferralCount.toLocaleString()} AI and ${te.socialReferralCount.toLocaleString()} social referral rows (${te.days} days)`),await Nt(n,"ga"),await Z({current:!1})}catch(te){g(te instanceof Error?te.message:"Sync failed")}finally{u(!1)}}async function X(){p(!0),g(null),S(null);try{await kc(t),await Nt(n,"ga"),o({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),c(null),S("GA4 disconnected")}catch(te){g(te instanceof Error?te.message:"Disconnect failed")}finally{p(!1)}}function de(te){re.setPage(1),j===te?y(qe=>qe==="desc"?"asc":"desc"):(D(te),y("desc"))}function xe(te){w===te?L(qe=>qe==="desc"?"asc":"desc"):(N(te),L("desc"))}function ne(te){F===te?J(qe=>qe==="desc"?"asc":"desc"):(H(te),J("desc"))}const Q=l.useMemo(()=>i?.topPages?[...i.topPages].sort((te,qe)=>{const Ce=te[j],Pe=qe[j];return typeof Ce=="string"&&typeof Pe=="string"?A==="asc"?Ce.localeCompare(Pe):Pe.localeCompare(Ce):A==="asc"?Ce-Pe:Pe-Ce}):[],[i?.topPages,j,A]),re=fn({rows:Q,getSearchText:te=>Nl(te.landingPage),pageSize:tx}),Ee=l.useMemo(()=>i?.aiReferrals?[...i.aiReferrals].sort((te,qe)=>{const Ce=te[w],Pe=qe[w];return typeof Ce=="string"&&typeof Pe=="string"?M==="asc"?Ce.localeCompare(Pe):Pe.localeCompare(Ce):M==="asc"?Ce-Pe:Pe-Ce}):[],[i?.aiReferrals,w,M]),we=l.useMemo(()=>i?.aiReferralLandingPages?[...i.aiReferralLandingPages].sort((te,qe)=>{const Ce=te[G],Pe=qe[G];return typeof Ce=="string"&&typeof Pe=="string"?ae==="asc"?Ce.localeCompare(Pe):Pe.localeCompare(Ce):ae==="asc"?Ce-Pe:Pe-Ce}):[],[i?.aiReferralLandingPages,G,ae]),Se=fn({rows:we,getSearchText:Zh,pageSize:ex}),et=Se.totalRows>0?`${Se.totalRows.toLocaleString()} ${Se.hasQuery?Se.totalRows===1?"match":"matches":Se.totalRows===1?"row":"rows"}`:Se.hasQuery&&(i?.aiReferralLandingPages.length??0)>0?"0 matches":"No landing-page rows";function Ke(te){Se.setPage(1),G===te?q(qe=>qe==="desc"?"asc":"desc"):(C(te),q("desc"))}const Qe=l.useMemo(()=>i?.socialReferrals?[...i.socialReferrals].sort((te,qe)=>{const Ce=te[F],Pe=qe[F];return typeof Ce=="string"&&typeof Pe=="string"?O==="asc"?Ce.localeCompare(Pe):Pe.localeCompare(Ce):O==="asc"?Ce-Pe:Pe-Ce}):[],[i?.socialReferrals,F,O]),{socialChartData:We,socialChartSources:Ge,socialOtherCount:_}=l.useMemo(()=>{const te=Hh(R);return{socialChartData:te.data,socialChartSources:te.sources,socialOtherCount:te.otherCount}},[R]),{chartData:U,chartSources:W,dateRange:Re}=l.useMemo(()=>{const te=Yh(se,B);return{chartData:te.data,chartSources:te.sources,dateRange:te.dateRange}},[se,B]);if(d&&!r)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!r?.connected)return ie()?e.jsx(ye,{className:"p-5",children:e.jsx("div",{className:"text-sm text-secondary",children:"No Google Analytics 4 property connected yet."})}):e.jsx(rx,{projectName:t,onConnected:()=>{(async()=>(await Nt(n,"ga"),await Z({current:!1})))()}});const _e=i?.organicSharePctDisplay??"0%",Ue=i?.channelBreakdown?.organic.sharePctDisplay??_e,le=i?.channelBreakdown?.organic.sessions??i?.totalOrganicSessions??0,pt=i?.aiSessionsDeduped??0,ut=i?.channelBreakdown?.ai.sessions??i?.aiSessionsBySession??0,ze=i?.channelBreakdown?.ai.sharePctDisplay??i?.aiSharePctBySessionDisplay??"0%",Fe=i?.paidAiSessionsBySession??0,wt=i?.paidAiSharePctBySessionDisplay??"0%",Be=i?new Set(i.aiReferrals.map(te=>te.source.toLowerCase())).size:0,Me=Ee[0]??null,tt=i?.totalDirectSessions??0,$t=i?.directSharePctDisplay??"0%",Mt=i?.channelBreakdown?.direct.sessions??tt,De=i?.channelBreakdown?.direct.sharePctDisplay??$t,k=i?.channelBreakdown?.other.sessions??i?.otherSessions??0,Ae=i?.channelBreakdown?.other.sharePctDisplay??i?.otherSharePctDisplay??"0%",ve=i?.socialSessions??0,He=i?.socialSharePctDisplay??"0%",vt=i?.channelBreakdown?.social.sessions??ve,st=i?.channelBreakdown?.social.sharePctDisplay??He,Lt=i?new Set(i.socialReferrals.map(te=>te.source.toLowerCase())).size:0,Xe=Qe[0]??null;return e.jsxs(e.Fragment,{children:[x&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative",children:x}),f&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-positive-900/20 border border-positive-800/60 text-sm text-positive",children:f}),e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-positive-500"}),e.jsxs("span",{className:"text-xs text-secondary",children:["Property ",e.jsx("span",{className:"text-neutral",children:r.propertyId}),r.clientEmail&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"text-muted",children:r.clientEmail})]})]})]}),!ie()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(P,{variant:"outline",size:"sm",disabled:m,onClick:Ye(ge),children:[e.jsx(ta,{className:`w-3.5 h-3.5 mr-1.5 ${m?"animate-spin":""}`}),m?"Syncing…":"Sync"]}),e.jsxs(P,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:b,onClick:Ye(X),children:[e.jsx(qm,{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(Ve,{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(hr,{value:ja(i.totalSessions),label:"Total Sessions",subtitle:i.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(hr,{value:ja(i.totalOrganicSessions),label:"Organic Sessions",subtitle:`${_e} of total`,tone:"positive"}),e.jsx(hr,{value:i.totalUsers===null?"—":ja(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."}),!ie()&&e.jsxs(P,{variant:"outline",size:"sm",disabled:m,onClick:Ye(ge),children:[e.jsx(ta,{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(Ve,{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."})]})]}),Re&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(Re.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(Re.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),U.length>0&&e.jsxs(ye,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:W.length>0?"AI vs. total sessions":"All sessions (baseline)"}),W.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),W.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(Xs,{width:"100%",height:"100%",children:e.jsxs(Zs,{data:U,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(en,{dataKey:"date",tick:Ft,tickLine:!1,axisLine:{stroke:ds},tickFormatter:yn}),e.jsx(tn,{tick:Ft,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(sn,{...ts,labelFormatter:Vt,formatter:(te,qe)=>{const Ce=typeof te=="number"?te.toLocaleString():String(te??0),Pe=String(qe??"");return Pe==="_totalSessions"?[Ce,"Total Sessions"]:Pe==="_organicSessions"?[Ce,"Organic Sessions"]:[Ce,Pe]}}),e.jsx(Ua,{wrapperStyle:{fontSize:11,color:us.text},formatter:te=>te==="_totalSessions"?"Total Sessions":te==="_organicSessions"?"Organic Sessions":te}),e.jsx(Bs,{type:"monotone",dataKey:"_totalSessions",stroke:us.textFaint,fill:us.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),W.map((te,qe)=>e.jsx(Bs,{type:"monotone",dataKey:te,stackId:"ai",stroke:Us[qe%Us.length],fill:Us[qe%Us.length],fillOpacity:.4,strokeWidth:1.5},te))]})})})]}),e.jsxs(ye,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Summary"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Sessions by channel"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(gs,{label:"Organic",value:Ue,hint:`${le.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(gs,{label:"Social",value:st,hint:`${vt.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(gs,{label:"Direct",value:De,hint:`${Mt.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(gs,{label:"Visitors from AI (at least)",value:ze,hint:Fe>0?`${ut.toLocaleString()} sessions · ${Fe.toLocaleString()} paid`:`${ut.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(gs,{label:"Other channels",value:Ae,hint:`${k.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."})]}),Me&&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:Me.source})," via ",Me.medium,", accounting for ",Me.sessions.toLocaleString()," sessions.",Fe>0&&e.jsxs("span",{children:[" Paid AI: ",Fe.toLocaleString()," sessions (",wt,")."]})]})]}),e.jsxs(ye,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Detail"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Where AI visitors came from"})]}),e.jsx("p",{className:"text-xs text-muted",children:i.aiReferrals.length>0?`${Be} 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(is,{label:"Source",sortKey:"source",current:w,dir:M,onSort:xe,align:"left"}),e.jsx(is,{label:"Medium",sortKey:"medium",current:w,dir:M,onSort:xe,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(is,{label:"Sessions",sortKey:"sessions",current:w,dir:M,onSort:xe,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:Ee.map(te=>e.jsx(ox,{referral:te,totalSessions:pt},`${te.source}:${te.medium}:${te.sourceDimension}`))})]})}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No AI referrer sessions detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"AI engines that preserve a referrer (Perplexity, copy/paste from ChatGPT, etc.) will appear here. Most AI traffic strips the referrer — see the Direct cell above for the upper bound."})]})]}),e.jsxs(ye,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Detail"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Pages AI visitors landed on"})]}),e.jsx("p",{className:"text-xs text-muted",children:et})]}),i.aiReferralLandingPages.length>0?e.jsxs(e.Fragment,{children:[e.jsx(zs,{value:Se.query,onChange:Se.setQuery,label:"Filter landing page URLs or query parameters",placeholder:"Filter URL or query parameters",className:"mb-4 max-w-md"}),Se.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(is,{label:"Landing Page",sortKey:"landingPage",current:G,dir:ae,onSort:Ke,align:"left"}),e.jsx(is,{label:"Source",sortKey:"source",current:G,dir:ae,onSort:Ke,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(is,{label:"Sessions",sortKey:"sessions",current:G,dir:ae,onSort:Ke,align:"right"})]})}),e.jsx("tbody",{children:Se.rows.map(te=>e.jsx(lx,{row:te},`${te.landingPage}:${te.source}:${te.medium}:${te.sourceDimension}`))})]})}),e.jsx(Ls,{page:Se.page,pageSize:Se.pageSize,visibleRows:Se.rows.length,totalRows:Se.totalRows,onPageChange:Se.setPage,itemLabel:Se.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:()=>Se.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(Ve,{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(ye,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Summary"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"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(gs,{label:"Social Sessions",value:ja(ve),hint:`${ve.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(gs,{label:"Share of Traffic",value:He,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(gs,{label:"Platforms",value:String(Lt),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."})]}),Xe&&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:`${Xe.source} via ${Xe.medium}`,children:ql(Mn(Xe.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:Xe.medium,children:["via ",Mn(Xe.medium)," · ",Xe.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(gs,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(gs,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(gs,{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."})]})]})]}),We.length>0&&e.jsxs(ye,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social sessions"})]}),_>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",Ge.length-1," sources · ",_," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(Xs,{width:"100%",height:"100%",children:e.jsxs(Zs,{data:We,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(en,{dataKey:"date",tick:Ft,tickLine:!1,axisLine:{stroke:ds},tickFormatter:yn}),e.jsx(tn,{tick:Ft,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(sn,{...ts,labelFormatter:Vt,formatter:(te,qe)=>{const Ce=typeof te=="number"?te.toLocaleString():String(te??0),Pe=String(qe??"");if(Pe===$n)return[Ce,"Total Social"];if(Pe===qn){const Yt=`Other (${_} source${_===1?"":"s"})`;return[Ce,Yt]}return[Ce,Mn(Pe)]}}),e.jsx(Bs,{type:"monotone",dataKey:$n,stroke:El,fill:us.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),Ge.map((te,qe)=>{const Pe=te===qn?Vr:Us[qe%Us.length];return e.jsx(Bs,{type:"monotone",dataKey:te,stackId:"social",stroke:Pe,fill:Pe,fillOpacity:.4,strokeWidth:1.5},te)})]})})}),e.jsx(dx,{sources:Ge,otherCount:_})]}),e.jsxs(ye,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Breakdown"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social sources"})]}),e.jsx("p",{className:"text-xs text-muted",children:i.socialReferrals.length>0?Qe.length>_n&&!T?`Top ${_n} of ${Qe.length}`:`${Qe.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(is,{label:"Source",sortKey:"source",current:F,dir:O,onSort:ne,align:"left"}),e.jsx(is,{label:"Medium",sortKey:"medium",current:F,dir:O,onSort:ne,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(is,{label:"Sessions",sortKey:"sessions",current:F,dir:O,onSort:ne,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:(T?Qe:Qe.slice(0,_n)).map(te=>e.jsx(cx,{referral:te,totalSessions:ve},`${te.source}:${te.medium}:${te.channelGroup}`))})]})}),Qe.length>_n&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>ee(te=>!te),className:"rounded-md border border-base px-3 py-1.5 text-xs text-secondary transition-colors hover:border-strong hover:text-strong",children:T?`Show top ${_n}`:`Show all ${Qe.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(Ve,{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(zs,{value:re.query,onChange:re.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(is,{label:"Landing Page",sortKey:"landingPage",current:j,dir:A,onSort:de,align:"left"}),e.jsx(is,{label:"Sessions",sortKey:"sessions",current:j,dir:A,onSort:de,align:"right"}),e.jsx(is,{label:"Organic",sortKey:"organicSessions",current:j,dir:A,onSort:de,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"})]})}),e.jsx("tbody",{children:re.rows.map(te=>e.jsx(ix,{page:te},te.landingPage))})]})}),re.totalRows===0&&re.hasQuery&&e.jsx("p",{className:"text-sm text-secondary mt-3",children:"No landing pages match this filter"}),e.jsx(Ls,{page:re.page,pageSize:re.pageSize,visibleRows:re.rows.length,totalRows:re.totalRows,onPageChange:re.setPage,itemLabel:re.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 ${Dl(i.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:i?`${i.topPages.length} pages · ${i.aiReferrals.length} AI rows · ${i.socialReferrals.length} social rows`:""})]})]})}function rx({projectName:t,onConnected:s}){const[n,a]=l.useState(""),[r,o]=l.useState(null),[i,c]=l.useState(null),[d,h]=l.useState(!1),[m,u]=l.useState(null),b=l.useRef(null),p=l.useCallback(g=>{const f=g.target.files?.[0];if(!f)return;u(null),o(f.name);const S=new FileReader;S.onload=()=>{const j=S.result;try{const D=JSON.parse(j);if(!D.client_email||!D.private_key){u("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(j)}catch{u("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),c(null)}},S.onerror=()=>{u("Failed to read file."),c(null)},S.readAsText(f)},[]);async function x(){if(u(null),!n.trim()){u("Property ID is required.");return}if(!i){u("Please upload a service account key file.");return}h(!0);try{await Ac(t,{propertyId:n.trim(),keyJson:i});try{await rl(t)}catch{}s()}catch(g){u(g instanceof Error?g.message:"Failed to connect GA4")}finally{h(!1)}}return e.jsxs(ye,{className:"surface-card p-6",children:[e.jsx("h3",{className:"text-base font-semibold text-primary mb-1",children:"Connect Google Analytics 4"}),e.jsx("p",{className:"text-sm text-secondary mb-5",children:"Connect a GA4 property to see traffic data for this project. You'll need a service account key file from Google Cloud Console."}),m&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative",children:m}),e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{htmlFor:"ga4-property-id",className:"block text-xs font-medium text-secondary mb-1.5",children:"GA4 Property ID"}),e.jsx("input",{id:"ga4-property-id",type:"text",placeholder:"e.g. 123456789",value:n,onChange:g=>a(g.target.value),className:"w-full rounded-lg bg-bg-elevated/60 border border-default px-3 py-2 text-sm text-strong placeholder-mono-600 focus:outline-none focus:ring-1 focus:ring-mono-600"}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:"Find this in GA4 → Admin → Property Settings. It's a numeric ID, not the Measurement ID (G-XXXXXX)."})]}),e.jsxs("div",{className:"mb-5",children:[e.jsx("label",{className:"block text-xs font-medium text-secondary mb-1.5",children:"Service Account Key File"}),e.jsx("input",{ref:b,type:"file",accept:".json,application/json",onChange:p,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>b.current?.click(),className:"flex items-center gap-2 w-full rounded-lg bg-bg-elevated/60 border border-default border-dashed px-4 py-3 text-sm text-secondary hover:border-mono-600 hover:text-neutral transition-colors cursor-pointer",children:[e.jsx(Em,{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(P,{variant:"default",size:"sm",disabled:d||!n.trim()||!i,onClick:Ye(x),children:d?"Connecting & syncing…":"Connect GA4"})]})}function is({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 Ol={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function hr({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 ${Ol[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function gs({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(Ve,{text:r})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${Ol[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function ix({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 Fl={session:"Session",first_user:"First Visit",manual_utm:"UTM"},Kl={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 ox({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=Fl[t.sourceDimension]??t.sourceDimension,r=Kl[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 lx({row:t}){const s=Fl[t.sourceDimension]??t.sourceDimension,n=Kl[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(qa,{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 cx({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=t.channelGroup==="Paid Social"?"Paid":"Organic",r=Mn(t.source),o=Mn(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 dx({sources:t,otherCount:s}){const n=[{key:$n,color:El,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const r=t[a];if(r===qn)n.push({key:qn,color:Vr,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const o=Mn(r);n.push({key:r,color:Us[a%Us.length]??Vr,label:ql(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 ux(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 mx="Search Console is not connected yet. Your Canonry team can set this up.",hx=["7d","30d","90d","all"],Na=500,Zi=[{key:"clicks",label:"Clicks",color:rt[1],format:t=>t.toLocaleString()},{key:"impressions",label:"Impressions",color:rt[4],format:t=>t.toLocaleString()},{key:"ctr",label:"CTR",color:qs.caution,format:t=>`${(t*100).toFixed(1)}%`},{key:"position",label:"Avg position",color:rt[2],inverted:!0,format:t=>t.toFixed(1)}],Ks=25,xx="canonry:google-oauth-complete",px=new Intl.NumberFormat(void 0,{maximumFractionDigits:1});function gx(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 d=t.prior[s],h=t.trailing[s];return d!==null&&h!==null&&d<=0&&h>0?`new in the last ${a}d`:d===null||d<=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%":`${px.format(o)}%`;return`${(n?r<0:r>0)?"↑":"↓"} ${i} vs prior ${a}d`}function fx(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}`,d=`Tile percentages compare these ${s} ${o} (${c}) with the ${s} ${o} before them (${i}).`;return n!=="split-window"?d:`${d} 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 eo(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function to(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 so(t){return t.isPending?"Processing":Number(t.errors??0)>0?"Errors":Number(t.warnings??0)>0?"Warnings":"Success"}function yx({projectName:t,refreshNonce:s}){const n=ms(),{isAdmin:a}=bn(),[r,o]=l.useState(!1),[i,c]=l.useState([]),[d,h]=l.useState([]),[m,u]=l.useState([]),[b,p]=l.useState(null),[x,g]=l.useState([]),[f,S]=l.useState([]),[j,D]=l.useState(null),[A,y]=l.useState(""),[w,N]=l.useState(""),[M,L]=l.useState("30"),[F,H]=l.useState(!1),[O,J]=l.useState("30d"),[G,C]=l.useState(["clicks","impressions"]),[ae,q]=l.useState(!0),[se,V]=l.useState(null),[B,E]=l.useState(0),[R,oe]=l.useState({startDate:"",endDate:"",query:"",page:""}),[T,ee]=l.useState(0),[Z,ge]=l.useState(!1),[X,de]=l.useState(0),[xe,ne]=l.useState(!1),[Q,re]=l.useState(""),[Ee,we]=l.useState(!0),[Se,et]=l.useState(!1),[Ke,Qe]=l.useState(!1),[We,Ge]=l.useState(!1),[_,U]=l.useState(!1),[W,Re]=l.useState(!1),[_e,Ue]=l.useState(!1),[le,pt]=l.useState(null),[ut,ze]=l.useState(!1),[Fe,wt]=l.useState(!1),[Be,Me]=l.useState(null),[tt,$t]=l.useState(null),[Mt,De]=l.useState([]),[k,Ae]=l.useState(new Set),[ve,He]=l.useState({}),[vt,st]=l.useState(new Set),[Lt,Xe]=l.useState(""),[te,qe]=l.useState(null),[Ce,Pe]=l.useState(""),[Yt,Jt]=l.useState(!1),[yt,St]=l.useState(!1),[mt,Xt]=l.useState(!1),[Qt,ss]=l.useState(!1),[at,fs]=l.useState("indexed"),[gt,dt]=l.useState(null),Ct=!!(R.query.trim()||R.page.trim()||gt),ns=gt!==null,hs=l.useMemo(()=>{if(!gt)return m;const{key:v,dir:z}=gt;return[...m].sort((he,be)=>{const Ze=v===hn.CTR?Number.isFinite(he.ctr)?he.ctr:0:he[v],nt=v===hn.CTR?Number.isFinite(be.ctr)?be.ctr:0:be[v];return z==="asc"?Ze-nt:nt-Ze})},[m,gt]),qt=fn({rows:hs,pageSize:Rs}),Ps=xe?qt.rows:hs,zt=fn({rows:(Be??[]).filter(v=>v.path.toLowerCase().includes(Lt.trim().toLowerCase())),pageSize:Rs}),[kt,xs]=l.useState([]),[ht,Zt]=l.useState(null),[ys,ps]=l.useState(1),K=l.useMemo(()=>{if(kt.length<2)return null;const v=kt[kt.length-1],z=kt[kt.length-2];return{indexed:v.indexed-z.indexed,notIndexed:v.notIndexed-z.notIndexed}},[kt]);l.useEffect(()=>{ps(1)},[le,at,ht]);const ce=l.useMemo(()=>ht?(le?.reasonGroups??[]).find(v=>v.reason===ht):void 0,[le,ht]),Ne=l.useMemo(()=>le?at==="indexed"?le.indexed:at==="deindexed"?le.deindexed:at==="notIndexed"?ht?ce?.urls??[]:(le.reasonGroups??[]).length===0?le.notIndexed:[]:[]:[],[le,at,ht,ce]),me=Math.max(1,Math.ceil(Ne.length/Ks)),je=Math.min(Math.max(1,ys),me),Ie=(je-1)*Ks,as=l.useMemo(()=>le?.indexed.slice(Ie,Ie+Ks)??[],[le,Ie]),ot=l.useMemo(()=>le?.notIndexed.slice(Ie,Ie+Ks)??[],[le,Ie]),bs=l.useMemo(()=>le?.deindexed.slice(Ie,Ie+Ks)??[],[le,Ie]),$=l.useMemo(()=>(ce?.urls??[]).slice(Ie,Ie+Ks),[ce,Ie]),[pe,it]=l.useState(!1),[At,Oe]=l.useState(null),[Kt,Pt]=l.useState(null),[vn,Wt]=l.useState(null);function jn(v,z){const he=Zm(v),be=ux(he);be?(Pt(be),Oe(null)):(Pt(null),Oe(he.message||z))}const Rt=i.find(v=>v.connectionType==="gsc"),vs=(Rt?.scopes??[]).includes("https://www.googleapis.com/auth/webmasters"),la=Mt.length>0?Mt:(Be??[]).map(v=>v.path),Nn=la.filter(v=>Be?.some(z=>z.path===v&&z.isSitemapsIndex)).length,ca=Nn===1?"Resubmit sitemap index":Nn>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",Ja=m.length>0||x.length>0||f.length>0,Ds=Pc(),Dn=Rc();async function da(v,z=!1){if(!v){h([]),y("");return}Qe(!0);try{const{sites:he}=await n.fetchQuery({...Uc({client:Y,path:{name:t}}),staleTime:z?0:Ut});h(he),y(v.propertyId??he[0]?.siteUrl??""),Pt(null)}catch(he){h([]),jn(he,"Failed to load Search Console properties")}finally{Qe(!1)}}async function nn(v){U(!0);const z=v??T;try{const he=Ct?Na:Rs,be=Ct?0:z,Ze={limit:String(he)};R.startDate&&(Ze.startDate=R.startDate),R.endDate&&(Ze.endDate=R.endDate),R.query&&(Ze.query=R.query),R.page&&(Ze.page=R.page),be>0&&(Ze.offset=String(be)),O&&O!=="all"&&!R.startDate&&(Ze.window=O);const nt=await n.fetchQuery({...$c({client:Y,path:{name:t},query:Ze}),staleTime:Ut}),lt=nt.rows;Ct?(ge(!1),u(lt),de(lt.length),ne(!0)):(ge(be+lt.length<nt.totalMatching),u(lt),de(0),ne(!1))}catch(he){u([]),ge(!1),de(0),Oe(he instanceof Error?he.message:"Failed to load GSC performance data")}finally{U(!1)}}async function On(){try{const v={};R.startDate&&(v.startDate=R.startDate),R.endDate&&(v.endDate=R.endDate),O&&O!=="all"&&!R.startDate&&(v.window=O);const z=await n.fetchQuery({...Tc({client:Y,path:{name:t},query:v}),staleTime:Ut});p(z)}catch{p(null)}}async function wn(v=!1){Re(!0);try{const z=Q.trim()||void 0,he={limit:"20"};z&&(he.url=z);const[be,Ze]=await Promise.all([n.fetchQuery({...Gc({client:Y,path:{name:t},query:he}),staleTime:v?0:Ut}),n.fetchQuery({..._c({client:Y,path:{name:t}}),staleTime:v?0:Ut})]);g(be),S(Ze)}catch(z){g([]),S([]),Oe(z instanceof Error?z.message:"Failed to load GSC inspection history")}finally{Re(!1)}}async function ua(v=!1){ze(!0);try{const[z,he]=await Promise.all([n.fetchQuery({...qc({client:Y,path:{name:t}}),staleTime:v?0:Ut}),n.fetchQuery({...Ec({client:Y,path:{name:t}}),staleTime:v?0:Ut}).catch(()=>[])]);pt(z),xs(he)}catch(z){pt(null),xs([]),Oe(z instanceof Error?z.message:"Failed to load coverage data")}finally{ze(!1)}}async function Fn(v){it(!0),Oe(null);try{const z=await Ci(t,{urls:v}),{succeeded:he,failed:be,total:Ze}=z.summary;$e({title:"Indexing requested",detail:be===0?`${he} URL${he!==1?"s":""} submitted for indexing.`:`${he}/${Ze} submitted successfully, ${be} failed.`,tone:be===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(z){Oe(z instanceof Error?z.message:"Failed to request indexing")}finally{it(!1)}}async function Xa(){it(!0),Oe(null);try{const v=await Ci(t,{urls:[],allUnindexed:!0}),{succeeded:z,failed:he,total:be}=v.summary;$e({title:"Indexing requested",detail:he===0?`${z} unindexed URL${z!==1?"s":""} submitted for indexing.`:`${z}/${be} submitted successfully, ${he} failed.`,tone:he===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(v){Oe(v instanceof Error?v.message:"Failed to request indexing")}finally{it(!1)}}async function Sn(){wt(!0),Oe(null);try{const v=await er(t);n.setQueryData(Dc({client:Y,path:{name:t}}),v),Me(v.sitemaps),$t(v.summary),De(v.preferredSubmissionUrls),Ae(new Set),He({}),v.sitemaps.length===0&&Wt("No sitemaps found in this GSC property. Submit one here to start Google processing it.")}catch(v){Oe(v instanceof Error?v.message:"Failed to list sitemaps")}finally{wt(!1)}}async function ma(v){const z=k.has(v);if(Ae(he=>{const be=new Set(he);return z?be.delete(v):be.add(v),be}),!(z||ve[v])){st(he=>new Set(he).add(v));try{const he=await er(t,v);He(be=>({...be,[v]:he.sitemaps}))}catch(he){Oe(he instanceof Error?he.message:"Failed to load sitemap files")}finally{st(he=>{const be=new Set(he);return be.delete(v),be})}}}async function jt(v){if(!vs||v.length===0)return;const z=[...new Set(v)];St(!0),Oe(null),qe({completed:0,total:z.length});let he=0,be=0,Ze=0,nt=null;try{for(let It=0;It<z.length;It+=50){const ct=z.slice(It,It+50);try{const ke=await Oc(t,ct);he+=ke.summary.accepted,be+=ke.summary.failed,Ze+=ct.length,qe({completed:Ze,total:z.length})}catch(ke){Ze+=ct.length;const Os=ct.length,Gn=z.length-Ze,fa=ke instanceof Error?ke.message:"The batch request failed",Fs=`${he} accepted, ${be} failed, ${Os} unconfirmed, ${Gn} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;nt=`Sitemap submission stopped after a batch request failed. ${Fs} ${fa}`,Oe(nt),$e({title:"Sitemap resubmission partially completed",detail:Fs,tone:"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"});return}}const lt=z.length;$e({title:be===0?"Sitemap submitted to Google":"Some sitemap submissions need attention",detail:be===0?"Google accepted the sitemap submission/refetch request; indexing is not guaranteed.":`Google accepted ${he}/${lt} sitemap submissions; ${be} failed. Indexing is not guaranteed.`,tone:be===0?"positive":"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"}),Pe("")}catch(lt){Oe(lt instanceof Error?lt.message:"Failed to submit sitemap to Google")}finally{St(!1),qe(null),await Sn(),nt&&Oe(nt)}}async function Za(){St(!0);const v=Be??[];try{const z=v.filter(be=>be.isSitemapsIndex),he=[];for(let be=0;be<z.length;be+=4)(await Promise.all(z.slice(be,be+4).map(async nt=>{const lt=ve[nt.path];if(lt)return lt;const It=await er(t,nt.path);return He(ct=>({...ct,[nt.path]:It.sitemaps})),It.sitemaps}))).forEach((nt,lt)=>{he.push(...nt.length>0?nt.map(It=>It.path):[z[be+lt].path])});await jt([...v.filter(be=>!be.isSitemapsIndex).map(be=>be.path),...he])}catch(z){Oe(z instanceof Error?z.message:"Failed to load sitemap files"),St(!1)}}async function ha(v){Jt(!0),Oe(null);try{await Fc(t,"gsc",v),await Nt(n,"google"),c(z=>z.map(he=>he.connectionType==="gsc"?{...he,sitemapUrl:v}:he)),$e({title:"Default sitemap updated",detail:v,tone:"positive",dedupeKey:`gsc:sitemap-default:${t}`,dedupeMode:"replace"})}catch(z){Oe(z instanceof Error?z.message:"Failed to set the default sitemap")}finally{Jt(!1)}}async function xa(v){try{await Dn.mutateAsync({projectName:t,projectLabel:t,opts:v?{sitemapUrl:v}:void 0})}catch{}}async function pa(){we(!0),Oe(null);try{const[v,z]=await Promise.all([a?il().catch(()=>null):Promise.resolve(null),n.fetchQuery({...ai({client:Y,path:{name:t}}),staleTime:Ut}).catch(()=>[])]);o(!!v?.google?.configured),c(z);const he=z.find(be=>be.connectionType==="gsc");await Promise.all([da(he),nn(),On(),wn(),ua(),he?.propertyId?Sn():Promise.resolve()])}finally{we(!1)}}l.useEffect(()=>{pa()},[t,s,a]),l.useEffect(()=>{ee(0),V(null),oe(v=>v.startDate||v.endDate?{...v,startDate:"",endDate:""}:v),E(v=>v+1),On()},[O]);const ga=l.useRef(!1);l.useEffect(()=>{if(!ga.current){ga.current=!0;return}ee(0),qt.setPage(1),nn(0)},[B]);function Kn(v){const z=se===v?null:v;V(z),oe(he=>({...he,startDate:z??"",endDate:z??""})),E(he=>he+1)}const I=l.useRef(!1);l.useEffect(()=>{if(!I.current){I.current=!0;return}ee(0),nn(0)},[ns]);async function fe(){if(!r){Oe("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}et(!0),Oe(null),Wt(null);try{let v=function(ke){if(ke.source!==be||ke.origin!==Ze||!ke.data||typeof ke.data!="object")return;const Os=ke.data;Os.type!==xx||Os.connectionType!=="gsc"||ct(!0)};const{authUrl:z,redirectUri:he}=await Lc(t,"gsc");if(!z.startsWith("https://accounts.google.com/")){Oe("Unexpected OAuth redirect URL. Please try again.");return}const be=window.open(z,"_blank","width=600,height=700");if(!be){window.location.assign(z);return}const Ze=he?new URL(he).origin:window.location.origin;let nt=!1,lt=null;const It=()=>{lt!==null&&window.clearInterval(lt),window.removeEventListener("message",v)},ct=async ke=>{if(!nt){nt=!0,It(),Wt(ke?"Google connected. Refreshing access…":"Refreshing Google connection…");try{await Nt(n,"google"),await pa()}finally{Wt(null)}}};window.addEventListener("message",v),Wt("Finish the Google consent flow in the popup. This page will refresh automatically."),lt=window.setInterval(()=>{be.closed&&ct(!1)},1e3)}catch(v){Oe(v instanceof Error?v.message:"Failed to start OAuth flow")}finally{et(!1)}}async function Le(){Oe(null),Wt(null);try{await Mc(t,"gsc"),await Nt(n,"google"),c(v=>v.filter(z=>z.connectionType!=="gsc")),h([]),y("")}catch(v){Oe(v instanceof Error?v.message:"Failed to disconnect")}}async function es(){if(A){Ge(!0),Oe(null);try{await Bc(t,"gsc",A),await Nt(n,"google"),c(v=>v.map(z=>z.connectionType==="gsc"?{...z,propertyId:A}:z)),$e({title:"GSC property updated",detail:`${t} is now linked to ${A}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(v){Oe(v instanceof Error?v.message:"Failed to save GSC property")}finally{Ge(!1)}}}async function js(){Oe(null),Wt(null);try{await Ds.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(M,10)||void 0,full:F||void 0}}),await Nt(n,"gsc")}catch{}}async function wi(){if(w.trim()){Ue(!0),Oe(null),Wt(null);try{const v=await Kc(t,w.trim());await Nt(n,"gsc"),D(v),N(""),await wn()}catch(v){Oe(v instanceof Error?v.message:"Failed to inspect URL")}finally{Ue(!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"})]})}),Kt&&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:Kt.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:Kt.message}),(_s(Kt.enableUrl)||_s(Kt.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[_s(Kt.enableUrl)&&e.jsx("a",{href:_s(Kt.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 ↗"}),_s(Kt.indexingApiUrl)&&e.jsx("a",{href:_s(Kt.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:()=>Pt(null),children:"×"})]})}),At&&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:[At,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>Oe(null),children:"×"})]}),vn&&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:[vn,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>Wt(null),children:"×"})]}),Ee?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[Rt?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:Rt.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Coverage measured"," ",le?.lastInspectedAt?Ht(le.lastInspectedAt):"never"]}),e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:Ye(Le),children:"Disconnect"})]}):a?e.jsxs(ye,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(ue,{tone:r?"caution":"negative",children:r?"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:r?"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:[r?e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:Se,onClick:Ye(fe),children:Se?"Opening…":"Connect Google Search Console"}):e.jsx(P,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(As,{to:"/settings",children:"Open Settings"})}),!r&&e.jsx("p",{className:"text-xs text-muted",children:"The same Google OAuth app credentials are shared across all projects."})]})]})]}):e.jsx(ye,{className:"surface-card",children:e.jsx("p",{className:"text-sm text-secondary",children:mx})}),(Rt||Ja)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs(ye,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Performance"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Search performance"}),e.jsx(Ve,{text:`${fx(b?.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 ${Na.toLocaleString()} matching rows while the table shows ${Rs} per page.`})]}),b?.window?.startDate&&b.window.endDate&&e.jsxs("p",{className:"text-xs text-muted",children:[b.window.startDate," to ",b.window.endDate,(b.window.daysSinceLatestData??0)>0&&` · latest data ${b.window.daysSinceLatestData} day${b.window.daysSinceLatestData===1?"":"s"} ago`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ha,{windows:hx,value:O,onChange:v=>{J(v),ee(0),qt.setPage(1)},label:"Search Console time period",formatOption:v=>v==="all"?"All":v}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:_,onClick:()=>{ee(0),qt.setPage(1),nn(0),On()},children:_?"Loading…":"Apply filters"})]})]}),b&&b.daily.length>0&&(()=>{const{totals:v,daily:z,trends:he,periodComparison:be}=b,nt=Zi.filter(ke=>G.includes(ke.key)).map(ke=>({dataKey:ke.key,label:ke.label,color:ke.color,axisId:ke.key,inverted:ke.inverted,formatValue:ke.format,trend:ae?he?.[ke.key]??null:null})),lt=ke=>v[ke]??null,It=new Map(z.map(ke=>[ke.date,ke])),ct=z.length===0?[]:rh(z[0].date,z[z.length-1].date).map(ke=>It.get(ke)??{date:ke});return e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:Zi.map(ke=>{const Os=G.includes(ke.key),Gn=lt(ke.key),fa=Gn===null;return e.jsxs("button",{type:"button","aria-pressed":Os,disabled:fa,className:`rounded-md border px-3 py-2 text-left transition-colors ${Os?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${fa?"cursor-not-allowed opacity-50":""}`,onClick:()=>{C(Fs=>Fs.includes(ke.key)?Fs.length===1?Fs:Fs.filter(hc=>hc!==ke.key):[...Fs,ke.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:Os?ke.color:"transparent",border:`1px solid ${ke.color}`}}),e.jsx("span",{className:"text-xs text-secondary",children:ke.label})]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:Gn===null?"—":ke.format(Gn)}),e.jsx("span",{className:"block text-[11px] tabular-nums text-muted",children:gx(be,ke.key,ke.inverted)})]},ke.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:ae,onChange:ke=>q(ke.target.checked)}),"Trend line"]})}),e.jsx("div",{className:"mt-1",children:e.jsx(wl,{data:ct,xKey:"date",series:nt,xTickFormatter:yn,labelFormatter:Vt,onSelectX:Kn,selectedX:se})}),e.jsx("div",{role:"group","aria-label":"Filter the table to a single day",children:z.map(ke=>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":se===ke.date,onClick:()=>Kn(ke.date),children:[Vt(ke.date),": ",ke.clicks," clicks, ",ke.impressions," impressions"]},ke.date))}),se&&e.jsxs("div",{className:"mt-1 flex items-center gap-2 text-xs",children:[e.jsxs("span",{className:"text-secondary",children:["Table showing ",Vt(se)]}),e.jsxs("button",{type:"button",className:"text-link hover:underline",onClick:()=>Kn(se),children:["Show all ",v.days," days"]})]}),v.position!==null&&(v.positionDays??v.days)<v.days&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position covers ",v.positionDays," of ",v.days," days. The rest have no property-level position recorded."]}),(v.position===null||v.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:R.startDate,onChange:v=>oe(z=>({...z,startDate:v.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:R.endDate,onChange:v=>oe(z=>({...z,endDate:v.target.value}))}),e.jsx(zs,{value:R.query,onChange:v=>oe(z=>({...z,query:v})),label:"Filter search queries",placeholder:"Contains query…"}),e.jsx(zs,{value:R.page,onChange:v=>oe(z=>({...z,page:v})),label:"Filter page URLs",placeholder:"Contains page URL…"})]}),m.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Date"}),e.jsx("th",{className:"text-left",children:"Query"}),e.jsx("th",{className:"text-left",children:"Page"}),Object.values(hn).map(v=>e.jsx("th",{className:"text-right","aria-sort":gt?.key===v?gt.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:()=>{qt.setPage(1),dt(z=>z?.key===v?z.dir==="desc"?{key:v,dir:"asc"}:null:{key:v,dir:"desc"})},children:[Ic[v],gt?.key===v?gt.dir==="desc"?" ↓":" ↑":""]})},v))]})}),e.jsx("tbody",{children:Ps.map((v,z)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:v.date}),e.jsx("td",{className:"max-w-xs truncate text-strong",children:v.query}),e.jsx("td",{className:"max-w-xs text-secondary",children:e.jsx(qa,{value:v.page})}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:v.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:v.impressions.toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[(Number.isFinite(v.ctr)?v.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:v.position.toFixed(1)})]},`${v.date}:${v.query}:${v.page}:${z}`))})]})}),e.jsx(Ls,{page:xe?qt.page:Math.floor(T/Rs)+1,pageSize:Rs,visibleRows:Ps.length,totalRows:xe?X:void 0,hasNextPage:xe?void 0:Z,disabled:_,itemLabel:xe?"matches":"rows",onPageChange:v=>{if(xe){qt.setPage(v);return}const z=(v-1)*Rs;ee(z),nn(z)}}),xe&&X>=Na?e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Results are capped at ",Na.toLocaleString(),"; narrow the filters to search beyond this set."]}):null]}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No performance rows match the current filters yet."})]}),e.jsxs(ye,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Coverage"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Index coverage"}),e.jsx(Ve,{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:[le&&le.notIndexed.length>0&&e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:pe,onClick:()=>{Xa()},children:pe?"Requesting…":`Request indexing (${le.notIndexed.length})`}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:ut,onClick:()=>{ua(!0)},children:ut?"Loading…":"Reload saved coverage"})]})]}),le&&le.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const v=le.summary.indexed+le.summary.notIndexed,z=v>0?le.summary.indexed/v:0,he=v>0?le.summary.notIndexed/v:0,be=54,Ze=2*Math.PI*be,nt=Ze*(1-z),lt=Ze*he,It=Ze*z;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:be,fill:"none",stroke:us.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:be,fill:"none",stroke:qs.positiveDeep,strokeWidth:"14",strokeDasharray:Ze,strokeDashoffset:nt,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),le.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:be,fill:"none",stroke:us.textFaint,strokeWidth:"14",strokeDasharray:`${lt} ${Ze-lt}`,strokeDashoffset:-It,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:[(z*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:le.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:le.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:["Not indexed",(le.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-faint",children:["· ",(le.reasonGroups??[]).length," ",(le.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),le.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:le.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(v=>{const z=v==="indexed"?le.indexed.length:v==="notIndexed"?le.notIndexed.length:le.deindexed.length,he=v==="indexed"?"Indexed":v==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",role:"tab","aria-selected":at===v,className:`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${at===v?"border-accent text-heading":"border-transparent text-secondary hover:border-mono-600 hover:text-strong"}`,onClick:()=>{fs(v),Zt(null)},children:[he," (",z,")"]},v)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[at==="indexed"&&le.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:as.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:v.url}),e.jsx("td",{className:"text-secondary",children:v.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:v.crawlTime?v.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:v.isMobileFriendly===!0?"Yes":v.isMobileFriendly===!1?"No":"—"})]},v.id))})]}),at==="notIndexed"&&!ht&&(le.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:(le.reasonGroups??[]).map(v=>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(v.reason),onKeyDown:z=>{(z.key==="Enter"||z.key===" ")&&(z.preventDefault(),Zt(v.reason))},tabIndex:0,role:"button","aria-label":`View ${v.reason} pages`,children:[e.jsx("td",{className:"text-strong",children:v.reason}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:v.count})]},v.reason))})]}),at==="notIndexed"&&!ht&&(le.reasonGroups??[]).length===0&&le.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:ot.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:v.url}),e.jsx("td",{className:"text-secondary",children:v.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:v.coverageState??"Unknown"})]},v.id))})]}),at==="notIndexed"&&ht&&(()=>{const v=(le.reasonGroups??[]).find(z=>z.reason===ht);return v?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:v.reason}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[v.count," affected page",v.count!==1?"s":""]})]}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:pe,onClick:()=>{Fn(v.urls.map(z=>z.url))},children:pe?"Requesting…":`Request indexing (${v.count})`})]}),e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Last Crawl"}),e.jsx("th",{className:"w-8"})]})}),e.jsx("tbody",{children:$.map(z=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:z.url}),e.jsx("td",{className:"text-secondary",children:z.crawlTime?z.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-strong transition-colors",disabled:pe,onClick:()=>{Fn([z.url])},title:"Request indexing",children:"Index"})})]},z.id))})]})]}):null})(),at==="deindexed"&&le.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:bs.map((v,z)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:v.url}),e.jsx("td",{className:"text-secondary",children:v.previousState}),e.jsx("td",{className:"text-secondary",children:v.currentState}),e.jsx("td",{className:"text-secondary",children:v.transitionDate.split("T")[0]})]},`${v.url}-${z}`))})]}),(at==="indexed"&&le.indexed.length===0||at==="notIndexed"&&!ht&&le.notIndexed.length===0||at==="deindexed"&&le.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),e.jsx(Ls,{page:je,pageSize:Ks,visibleRows:Math.min(Ks,Ne.length-Ie),totalRows:Ne.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":Qt,onClick:()=>ss(v=>!v),children:[e.jsx("span",{children:"Coverage history"}),e.jsx("span",{children:Qt?"Hide snapshots":kt.length>0?`View ${kt.length} snapshots`:"View history"})]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["Current: ",le.summary.indexed.toLocaleString()," indexed, ",le.summary.notIndexed.toLocaleString()," not indexed.",K&&e.jsxs(e.Fragment,{children:[" Since the last snapshot: ",K.indexed>=0?"+":"",K.indexed.toLocaleString()," indexed, ",K.notIndexed>=0?"+":"",K.notIndexed.toLocaleString()," not indexed."]})]}),Qt&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:kt.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:kt.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:v.date}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:v.indexed.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:v.notIndexed.toLocaleString()})]},v.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:ut?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),e.jsxs(ye,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Sitemaps"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Sitemap operations"}),e.jsx(Ve,{text:"Submitting asks Google to refetch these sitemaps. Indexing is not guaranteed."})]})]}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:Fe||!Rt?.propertyId,onClick:()=>{Sn()},children:Fe?"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:Ce,onChange:v=>Pe(v.target.value),onKeyDown:v=>v.key==="Enter"&&void jt([Ce.trim()])}),e.jsx(P,{type:"button",size:"sm",disabled:!vs||yt||!Ce.trim(),onClick:()=>{jt([Ce.trim()])},children:yt?"Submitting…":"Submit sitemap to Google"})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:!vs||yt||la.length===0,onClick:()=>{jt(la)},children:yt?"Resubmitting…":ca}),e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:!vs||yt||!Be?.length,onClick:()=>{Za()},children:"Resubmit all files"}),tt&&e.jsxs("span",{className:"text-xs text-muted",children:["Top level: ",tt.indexes," index",tt.indexes===1?"":"es",", ",tt.files," file",tt.files===1?"":"s"]}),te&&e.jsxs("span",{className:"text-xs text-secondary",children:["Submitting ",te.completed,"/",te.total]})]}),!vs&&Rt&&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:Ye(fe),children:"Reconnect"})]}),Be&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:Be.length>0?e.jsxs(e.Fragment,{children:[e.jsx(zs,{value:Lt,onChange:v=>{Xe(v),zt.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:zt.rows.flatMap(v=>{const z=eo(v),he=to(v),be=so(v),Ze=ve[v.path]??[],nt=k.has(v.path),lt=e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs text-strong",children:e.jsx(qa,{value:v.path})}),e.jsx("td",{className:"text-secondary",children:v.isSitemapsIndex?e.jsx("button",{type:"button",className:"text-secondary hover:text-strong","aria-expanded":nt,"aria-label":`${nt?"Collapse":"Expand"} files in ${v.path}`,onClick:()=>{ma(v.path)},children:vt.has(v.path)?"Loading…":`${nt?"▾":"▸"} Index${ve[v.path]?` (${Ze.length})`:""}`}):"Sitemap"}),e.jsx("td",{className:"text-secondary",children:be}),e.jsx("td",{className:"text-secondary",children:v.lastSubmitted?v.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:v.lastDownloaded?v.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:z.toLocaleString()}),e.jsx("td",{className:"max-w-48 text-secondary",children:he||"—"}),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:!vs||yt,onClick:()=>{jt([v.path])},children:v.lastSubmitted?"Resubmit to Google":"Submit to Google"}),Rt?.sitemapUrl===v.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:Yt,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{ha(v.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Dn.isPending,onClick:()=>{xa(v.path)},children:"Inspect URLs"})]})})]},v.path),It=v.isSitemapsIndex&&nt?Ze.map(ct=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs pl-6 text-secondary",children:e.jsx(qa,{value:ct.path})}),e.jsx("td",{className:"text-secondary",children:"File"}),e.jsx("td",{className:"text-secondary",children:so(ct)}),e.jsx("td",{className:"text-secondary",children:ct.lastSubmitted?ct.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:ct.lastDownloaded?ct.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:eo(ct).toLocaleString()}),e.jsx("td",{className:"text-secondary",children:to(ct)||"—"}),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:!vs||yt,onClick:()=>{jt([ct.path])},children:"Resubmit"}),Rt?.sitemapUrl===ct.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:Yt,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{ha(ct.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Dn.isPending,onClick:()=>{xa(ct.path)},children:"Inspect URLs"})]})})]},`${v.path}:${ct.path}`)):[];return[lt,...It]})})]}),e.jsx(Ls,{page:zt.page,pageSize:Rs,visibleRows:zt.rows.length,totalRows:zt.totalRows,onPageChange:zt.setPage,itemLabel:"sitemaps"})]}):e.jsx("p",{className:"text-sm text-muted",children:"No sitemaps found for this property."})})]}),e.jsxs(ye,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Inspection"}),e.jsx("h3",{children:"Inspect a URL"})]})}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"url",placeholder:"https://example.com/page",value:w,onChange:v=>N(v.target.value),onKeyDown:v=>v.key==="Enter"&&void wi()}),e.jsx(P,{type:"button",size:"sm",disabled:_e||!Rt?.propertyId||!w.trim(),onClick:Ye(wi),children:_e?"Inspecting…":"Inspect URL"})]}),j&&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:j.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:j.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:Si(j.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:Ht(j.crawlTime)})]})]})]}),e.jsxs(ye,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Inspection log"})]}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:W,onClick:()=>{wn(!0)},children:W?"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:Q,onChange:v=>re(v.target.value)}),e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:W,onClick:()=>{wn(!0)},children:"Apply filter"})]}),x.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:x.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:v.url}),e.jsx("td",{className:"text-neutral",children:v.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:v.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:v.coverageState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:Si(v.isMobileFriendly??null)}),e.jsx("td",{className:"text-secondary",children:Ht(v.inspectedAt)})]},v.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No inspection history yet."})]}),e.jsxs(ye,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Deindexed"}),e.jsx("h3",{children:"Recent indexing losses"})]})}),f.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:f.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:v.url}),e.jsx("td",{className:"text-secondary",children:v.previousState??"Unknown"}),e.jsx("td",{className:"text-neutral",children:v.currentState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:Ht(v.transitionDate)})]},`${v.url}:${v.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No deindexed transitions recorded."})]})]}),Rt&&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:()=>Xt(v=>!v),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 ${mt?"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"})]})}),mt&&e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(ye,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Property"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Pick the Search Console property"}),e.jsx(Ve,{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:A,disabled:Ke||d.length===0,onChange:v=>y(v.target.value),children:d.length===0?e.jsx("option",{value:"",children:Ke?"Loading properties…":"No properties available"}):d.map(v=>e.jsxs("option",{value:v.siteUrl,children:[v.siteUrl," · ",v.permissionLevel]},v.siteUrl))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:Ke,onClick:()=>{da(Rt,!0)},children:Ke?"Refreshing…":"Refresh properties"}),e.jsx(P,{type:"button",size:"sm",disabled:!A||We,onClick:Ye(es),children:We?"Saving…":"Save property"})]})]})]}),e.jsxs(ye,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"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:M,onChange:v=>L(v.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:F,onChange:v=>H(v.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(P,{type:"button",size:"sm",disabled:Ds.isPending||!Rt.propertyId,onClick:Ye(js),children:Ds.isPending?"Queueing…":"Queue sync"}),!Rt.propertyId&&e.jsx("p",{className:"text-xs text-caution-400",children:"Select a Search Console property before queueing a sync."})]})]})]})})]})]})]})}const bx=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function vx({projectName:t,projectId:s}){const n=ms(),[a,r]=l.useState(null),[o,i]=l.useState(null),[c,d]=l.useState(!1),h=Te(ai({client:Y,path:{name:t}})),m=h.data?.find(X=>X.connectionType==="gbp"),u=!!m,b=a?{locationName:a}:void 0,p=Te({...Vc({client:Y,path:{name:t}}),enabled:u}),x=Te({...Qc({client:Y,path:{name:t},query:b}),enabled:u}),g=Te({...zc({client:Y,path:{name:t},query:b}),enabled:u}),f=Te({...Wc({client:Y,path:{name:t},query:b}),enabled:u}),S=Te({...Hc({client:Y,path:{name:t},query:b}),enabled:u}),j=Te({...Yc({client:Y,path:{name:t},query:b}),enabled:u}),D=Te({queryKey:["gbp-section-insights",t],queryFn:()=>Jc(t),enabled:u});function A(){Nt(n,"gbp")}const y=Tt({...Xc(),onSuccess:X=>{ol({id:X.runId,projectId:s,kind:Ys["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),$e({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),w=l.useSyncExternalStore(ll,Oa,Oa),N=Object.values(w.runs).some(X=>X.kind===Ys["gbp-sync"]&&X.projectId===s),M=y.isPending||N,L=Tt({...Zc(),onSuccess:()=>A()});if(l.useEffect(()=>{if(!a||!p.data)return;const X=p.data.locations.filter(de=>de.selected);(X.length<=1||!X.some(de=>de.locationName===a))&&r(null)},[a,p.data]),l.useEffect(()=>{if(!o||!p.data)return;(a?[a]:p.data.locations.filter(de=>de.selected).map(de=>de.locationName)).includes(o)||i(null)},[o,p.data,a]),h.isLoading)return null;if(!m){const X=[{title:"Connect your Google account",command:`canonry gbp connect ${t}`,note:"Opens Google OAuth. Grant Business Profile (business.manage) access."},{title:"Choose the account",command:`canonry gbp accounts ${t}`,note:"Pick which Business Profile account this project tracks."},{title:"Select locations",command:`canonry gbp locations discover ${t}`,note:e.jsxs(e.Fragment,{children:["Then adopt the ones to sync: ",e.jsxs("code",{className:"rounded bg-bg-elevated/80 px-1 py-0.5 font-mono text-[11px] text-secondary",children:["canonry gbp locations select ",t," <location>"]})]})},{title:"Sync, and keep it fresh",command:`canonry gbp sync ${t}`,note:e.jsxs(e.Fragment,{children:["Schedule it: ",e.jsxs("code",{className:"rounded bg-bg-elevated/80 px-1 py-0.5 font-mono text-[11px] text-secondary",children:["canonry schedule set ",t," --kind gbp-sync --preset daily"]})]})}];return e.jsx("section",{className:"page-section-divider",children:e.jsxs(ye,{className:"surface-card",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Local presence"}),e.jsx("h2",{children:"Connect Google Business Profile"}),e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-muted",children:"Track local performance, search terms, place-action CTAs, and how your public Maps listing compares to the profile you control. Four steps from the CLI:"}),e.jsx("ol",{className:"mt-5 space-y-4",children:X.map((de,xe)=>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:xe+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:de.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:de.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:de.note})]})]},de.title))})]})})}const F=x.data,H=p.data?.locations??[],O=H.filter(X=>X.selected),J=g.data?.keywords??[],G=f.data?.lodging??[],C=S.data?.placeActions??[],ae=j.data?.places??[],q=H.length>0?H[0].accountName:m.domain,se=a?H.find(X=>X.locationName===a)?.displayName??null:null,V=a?H.filter(X=>X.locationName===a):O,B=new Set(V.map(X=>X.locationName)),E=G.filter(X=>B.has(X.locationName)),R=C.filter(X=>B.has(X.locationName)),oe=ae.filter(X=>B.has(X.locationName)),T=new Set(O.map(X=>X.locationName)),ee=a?J:J.filter(X=>T.has(X.locationName)),Z=!a&&O.length>1,ge=(D.data??[]).filter(X=>!X.dismissed&&bx.has(X.type)&&(!se||X.query===se||X.query===a||X.title.startsWith(se)));return e.jsx("section",{className:"page-section-divider",children:e.jsxs(ye,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Local presence"}),e.jsxs("h2",{className:"flex items-center gap-2",children:["Google Business Profile",e.jsx(Ve,{text:"How AI answer engines and Maps surface this business: performance, search terms, and how your public listing compares to the profile you control."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ue,{tone:"positive",children:"Connected"}),!ie()&&e.jsx(Je,{type:"button",variant:"outline",size:"sm",disabled:M,onClick:()=>y.mutate({client:Y,path:{name:t},body:{}}),children:M?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-muted",children:[q?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-secondary",children:q})," · "]}):null,p.data?`${p.data.totalSelected} of ${p.data.totalDiscovered} locations tracked`:"Loading locations…"]}),O.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:X=>r(X.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"}),O.map(X=>e.jsx("option",{value:X.locationName,children:X.displayName},X.id))]})]}),O.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(X=>e.jsx("div",{className:["insight-card",Mx(X.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:[X.title,X.recommendation?.reason&&e.jsx(Ve,{text:X.recommendation.reason})]})},X.id))]}),F&&e.jsx(Dx,{performance:F.performance,freshness:F.freshness,timeseries:F.timeseries}),F?.profileCompleteness&&e.jsx(jx,{summary:F.profileCompleteness}),V.length>0&&e.jsx(Nx,{locations:V,lodging:E,places:oe,placeActions:R,expandedLocation:o,onToggleExpanded:X=>{i(de=>de===X?null:X)}}),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"}),g.data&&g.data.total>0&&e.jsxs("span",{className:"text-[11px] text-faint",children:[g.data.thresholdedPct,"% privacy-thresholded"]})]}),ee.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No keyword impressions stored yet."}):e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Search term"}),Z&&e.jsx("th",{className:"text-left",children:"Location"}),e.jsx("th",{className:"text-right",children:"Impressions"}),e.jsx("th",{className:"text-right",children:"Window"})]})}),e.jsx("tbody",{children:ee.slice(0,25).map(X=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-neutral",children:X.keyword}),Z&&e.jsx("td",{className:"text-muted",children:H.find(de=>de.locationName===X.locationName)?.displayName??X.locationName}),e.jsx("td",{className:"text-right font-mono text-strong",children:X.valueCount!==null?X.valueCount.toLocaleString():e.jsxs("span",{className:"text-muted",title:"Privacy floor — Google withheld the exact count",children:["<",X.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-faint",children:[X.periodStart,"–",X.periodEnd]})]},`${X.locationName}:${X.keyword}`))})]})]})]}),e.jsxs("div",{className:"mt-6 border-t border-default pt-4",children:[e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 text-xs font-medium text-secondary hover:text-strong",onClick:()=>d(X=>!X),"aria-expanded":c,children:[e.jsx("span",{"aria-hidden":"true",children:c?"▾":"▸"})," Manage locations (",H.length,")"]}),c&&e.jsx("div",{className:"mt-3",children:H.length===0?e.jsxs("p",{className:"text-sm text-muted",children:["No locations discovered. Run ",e.jsx("span",{className:"font-mono",children:"canonry gbp locations discover"}),"."]}):e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Location"}),e.jsx("th",{className:"text-left",children:"Address"}),e.jsx("th",{className:"text-left",children:"Status"}),!ie()&&e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:H.map(X=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:X.displayName}),e.jsx("td",{className:"text-muted",children:X.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(ue,{tone:X.selected?"positive":"neutral",children:X.selected?"Tracked":"Not tracked"})}),!ie()&&e.jsx("td",{className:"text-right",children:e.jsx(Je,{type:"button",variant:"outline",size:"sm",disabled:L.isPending,onClick:()=>L.mutate({client:Y,path:{name:t,locationName:X.locationName},body:{selected:!X.selected}}),children:X.selected?"Untrack":"Track"})})]},X.id))})]})})]})]})})}function jx({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:Un(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:Un(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:Un(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:Un(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:Un(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(Ve,{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 ${$x(a.tone)}`,children:a.value}),a.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-faint",children:a.detail})]},a.label))})]})}function Nx({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])),d=new Map;for(const h of a){const m=d.get(h.locationName)??[];m.push(h),d.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(Ve,{text:ie()?"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest sync, not that every Google product lacks the information.":"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest Canonry sync, not that every Google product lacks the information."})]}),e.jsxs("span",{className:"text-[11px] text-faint",children:[t.length," location",t.length===1?"":"s"]})]}),e.jsx("div",{className:"data-table-wrapper",children:e.jsxs("table",{className:"data-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"min-w-[14rem]",children:"Location"}),e.jsx("th",{className:"min-w-[15rem]",children:"Owner profile"}),e.jsx("th",{className:"min-w-[11rem]",children:"Hotel data"}),e.jsx("th",{className:"min-w-[11rem]",children:"Public Maps"}),e.jsx("th",{className:"min-w-[10rem]",children:"CTAs"}),e.jsx("th",{className:"text-right",children:"Detail"})]})}),e.jsx("tbody",{children:t.map(h=>{const m=i.get(h.locationName)??null,u=c.get(h.locationName)??null,b=d.get(h.locationName)??[],p=r===h.locationName;return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-strong",children:h.displayName}),e.jsx("p",{className:"mt-1 text-xs text-faint",children:h.primaryCategoryDisplayName??"Primary category not returned"}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[e.jsx(ue,{tone:h.selected?"positive":"neutral",children:h.selected?"Tracked":"Not tracked"}),h.openStatus&&h.openStatus!=="OPEN"&&e.jsx(ue,{tone:h.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:Gl(h.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(Sx,{location:h})}),e.jsx("td",{children:e.jsx(Cx,{lodging:m})}),e.jsx("td",{children:e.jsx(Ax,{place:u,mapsUri:h.mapsUri})}),e.jsx("td",{children:e.jsx(Rx,{actions:b})}),e.jsx("td",{className:"text-right",children:e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>o(h.locationName),children:p?"Hide":"Details"})})]}),p&&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(Tx,{location:h,lodging:m,place:u,placeActions:b})})})]},h.id)})})]})})]})}function wx(t){return[{label:"Description",tone:un(t.description)?"positive":"neutral",value:un(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:un(t.primaryPhone)?"positive":"neutral",value:un(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:un(t.websiteUri)?"positive":"neutral",value:un(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 Sx({location:t}){const s=wx(t);return e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>e.jsxs(ue,{tone:n.tone,children:[n.label," ",n.value]},n.label))})}function Cx({lodging:t}){return e.jsx(oi,{...kx(t)})}function kx(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 Ax({place:t,mapsUri:s}){return e.jsx(oi,{...Px(t,s)})}function Px(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 Rx({actions:t}){return e.jsx(oi,{...Ix(t)})}function Ix(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 oi({tone:t,label:s,detail:n}){return e.jsxs("div",{children:[e.jsx(ue,{tone:t,children:s}),e.jsx("p",{className:"mt-1.5 text-xs leading-5 text-faint",children:n})]})}function Tx({location:t,lodging:s,place:n,placeActions:a}){const r=s?qx(s.attributes):[];return e.jsxs("div",{className:"grid gap-5 text-xs lg:grid-cols-3",children:[e.jsxs(xr,{title:"Owner profile · Business Information",children:[e.jsx(Gt,{label:"Primary category",value:t.primaryCategoryDisplayName??"Not returned"}),e.jsx(Gt,{label:"Secondary categories",value:t.additionalCategories.length>0?t.additionalCategories.join(", "):"Not returned"}),e.jsx(Gt,{label:"Description",value:un(t.description)?t.description:"Not returned"}),e.jsx(Gt,{label:"Hours",value:t.regularHours?"Returned by Google":"Not returned"}),e.jsx(Gt,{label:"Service area",value:t.serviceArea?"Returned by Google":"Not returned"}),e.jsx(Gt,{label:"Phone",value:t.primaryPhone??"Not returned"}),e.jsx(Gt,{label:"Website",value:t.websiteUri??"Not returned"}),e.jsx(Gt,{label:"Open status",value:Gl(t.openStatus)}),e.jsx(Gt,{label:"Opening date",value:t.openingDate??"Not returned"})]}),e.jsx(xr,{title:"Hotel data · Lodging API",children:s?e.jsxs(e.Fragment,{children:[e.jsx(Gt,{label:"Last checked",value:no(s.syncedAt)}),e.jsx(Gt,{label:"Groups returned",value:String(s.populatedGroupCount)}),e.jsx(Gt,{label:"Populated groups",value:r.length>0?r.join(", "):"None returned"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Lodging API snapshot was stored for this location."})}),e.jsxs(xr,{title:"Public listing + CTAs",children:[n?e.jsxs(e.Fragment,{children:[e.jsx(Gt,{label:"Places tier",value:n.tier}),e.jsx(Gt,{label:"Last checked",value:no(n.syncedAt)}),e.jsx(Gt,{label:"Public signals",value:n.amenities.length>0?n.amenities.join(", "):"No supported signals detected"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Places Details snapshot was stored for this location."}),t.mapsUri&&e.jsx("a",{href:t.mapsUri,target:"_blank",rel:"noopener noreferrer",className:"inline-block text-muted hover:text-neutral",children:"View on Google Maps →"}),e.jsx("div",{className:"mt-3 border-t border-default pt-3",children:a.length===0?e.jsx("p",{className:"leading-5 text-muted",children:"No placeActionLinks returned."}):e.jsx("div",{className:"grid gap-2",children:a.map(o=>e.jsxs("div",{className:"grid gap-0.5",children:[e.jsxs("span",{className:"font-medium text-neutral",children:[Ba(o.placeActionType),o.isPreferred?" · preferred":""]}),e.jsxs("span",{className:"text-faint",children:[Ba(o.providerType),o.uri?` · ${Lx(o.uri)}`:""]})]},o.placeActionLinkName))})})]})]})}function xr({title:t,children:s}){return e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-[11px] font-semibold uppercase tracking-[0.14em] text-muted",children:t}),e.jsx("div",{className:"grid gap-2",children:s})]})}function Gt({label:t,value:s}){return e.jsxs("div",{className:"grid grid-cols-[7.25rem_minmax(0,1fr)] gap-3",children:[e.jsx("span",{className:"text-faint",children:t}),e.jsx("span",{className:"min-w-0 break-words text-secondary",children:s})]})}function Un(t,s,n){return t===s?"positive":t===0?n:"caution"}function $x(t){switch(t){case"positive":return"text-positive";case"caution":return"text-caution";case"negative":return"text-negative";case"neutral":return"text-neutral"}}function Mx(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function un(t){return typeof t=="string"&&t.trim().length>0}function Gl(t){return t?Ba(t):"Not returned"}function Ba(t){return t?t.toLowerCase().split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"Unknown"}function Lx(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function no(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function qx(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&Ex(n)).map(([s])=>Ba(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function Ex(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function Dx({performance:t,freshness:s,timeseries:n}){const a=t.totals,r=ed.filter(x=>(a[x]??0)>0),o=td.filter(x=>(a[x]??0)>0),i=Object.keys(a).filter(x=>(a[x]??0)>0&&sd(x)==="other").sort((x,g)=>(a[g]??0)-(a[x]??0)),c=Object.keys(a).filter(x=>(a[x]??0)===0).sort(),d=n.map(x=>{const g={date:x.date};for(const[f,S]of Object.entries(x.metrics))g[f]=S;return g}),h=n.find(x=>x.pending)?.date,m=n.length>0?n[n.length-1].date:void 0,u=d.length>0,b=s.dataThroughDate?`Data through ${Vt(s.dataThroughDate)}${s.pendingDays>0?` · ${s.pendingDays}d pending`:""}`:null,p=[...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"}),b&&e.jsx("span",{className:"text-[11px] text-muted",children:b})]}),!u||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(ao,{data:d,metrics:r,kind:"line",firstPending:h,lastDate:m}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-x-5 gap-y-1",children:p.map(x=>e.jsxs("span",{className:"text-sm text-secondary",children:[Fa(x)," ",e.jsx("span",{className:"font-mono text-heading",children:(a[x]??0).toLocaleString()})]},x))})]})]}),u&&o.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(ao,{data:d,metrics:o,kind:"area",firstPending:h,lastDate:m})]}),c.length>0&&e.jsxs("p",{className:"text-xs text-faint",children:["Not active: ",c.map(x=>Fa(x)).join(", ")]})]})}function ao({data:t,metrics:s,kind:n,firstPending:a,lastDate:r}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(Xs,{width:"100%",height:"100%",children:e.jsxs(Zs,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(na,{stroke:sa,vertical:!1}),e.jsx(en,{dataKey:"date",tick:Ft,tickLine:!1,axisLine:{stroke:ds},tickFormatter:yn,minTickGap:24}),e.jsx(tn,{tick:Ft,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(sn,{...ts,labelFormatter:Vt,formatter:(o,i)=>[typeof o=="number"?o.toLocaleString():String(o??0),Fa(String(i??""))]}),e.jsx(Ua,{wrapperStyle:{fontSize:11,color:us.text},formatter:o=>Fa(o)}),a&&r&&e.jsx(Kr,{x1:a,x2:r,fill:us.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:us.textDim,fontSize:10}}),s.map((o,i)=>n==="line"?e.jsx(Ms,{type:"monotone",dataKey:o,stroke:rt[i%rt.length],strokeWidth:2,dot:!1,isAnimationActive:!1},o):e.jsx(Bs,{type:"monotone",dataKey:o,stackId:"reach",stroke:rt[i%rt.length],fill:rt[i%rt.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},o))]})})})}function Ox(t){return Sl(Es(String(t)))}function Fx(t){return Ws(Es(String(t)))}function pr({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(Km,{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 wa=Rs;function Cn(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function gr(t){return t.toLocaleString()}function Kx(t){const s=Number(t);return Number.isFinite(s)?`${(s*100).toFixed(1)}%`:"—"}function Gx(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 _x(t){const s=t.filter(n=>n.kind===Ys["backlink-extract"]&&!cl(n.status));return s.length===0?null:s.reduce((n,a)=>n.createdAt>a.createdAt?n:a)}function Ux(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 Bx({projectName:t}){const[s,n]=l.useState(null),[a,r]=l.useState(null),[o,i]=l.useState([]),[c,d]=l.useState(null),[h,m]=l.useState(null),[u,b]=l.useState(null),[p,x]=l.useState(Date.now()),[g,f]=l.useState(0),[S,j]=l.useState(!0),[D,A]=l.useState(!1),[y,w]=l.useState(null),N=l.useCallback(async()=>{j(!0),w(null);try{const[q,se,V,B,E]=await Promise.all([nd().catch(()=>null),ad(t,{excludeCrawlers:!0}).catch(()=>null),rd(t,{limit:wa,offset:g,excludeCrawlers:!0}).catch(oe=>{if(oe instanceof pn&&oe.code==="NOT_FOUND")return null;throw oe}),id(t).catch(()=>[]),od(t).catch(()=>[])]);d(q),n(se),r(V),i(B);const R=_x(E);m(R)}catch(q){w(q instanceof Error?q.message:"Failed to load backlinks")}finally{j(!1)}},[t,g]);l.useEffect(()=>{N()},[N]),l.useEffect(()=>{if(!h)return;const q=h.id;let se=!1;const V=async()=>{try{const E=await Fr(q);if(se)return;cl(E.status)?(m(null),b(E),await N()):m(R=>R?.id===E.id?{...R,...E}:R)}catch{}},B=window.setInterval(()=>{V()},3e3);return()=>{se=!0,window.clearInterval(B)}},[h,N]),l.useEffect(()=>{if(!h)return;const q=window.setInterval(()=>x(Date.now()),1e3);return()=>window.clearInterval(q)},[h]),l.useEffect(()=>{if(!u||u.status==="failed")return;const q=window.setTimeout(()=>b(null),1e4);return()=>window.clearTimeout(q)},[u]);async function M(){A(!0),w(null);try{const q=await cd(t);m(q)}catch(q){q instanceof pn&&q.code==="MISSING_DEPENDENCY"?w("DuckDB is not installed. Visit the Backlinks admin page to install it."):w(q instanceof Error?q.message:"Failed to trigger extract")}finally{A(!1)}}const L=l.useMemo(()=>o.slice().sort((q,se)=>q.queriedAt.localeCompare(se.queriedAt)).map(q=>({date:q.queriedAt,linkingDomains:q.totalLinkingDomains})),[o]),F=a?.rows??[],H=a?.total??0,O=s?.excludedLinkingDomains??0,J=Math.floor(g/wa)+1;return l.useEffect(()=>{g>0&&g>=H&&f(0)},[g,H]),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"})]})}),y&&e.jsx(ye,{className:"surface-card p-4 mb-4 border-negative-800/60",children:e.jsx("p",{className:"text-sm text-negative",children:y})}),h&&e.jsx(ye,{className:"surface-card p-4 mb-4 border-info-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Dm,{className:"h-5 w-5 text-info-400 animate-spin shrink-0 mt-0.5","aria-hidden":!0}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"Extract running"}),e.jsx(ue,{tone:"neutral",children:h.status}),e.jsxs("span",{className:"text-sm text-secondary tabular-nums",children:[Ux(h.startedAt??null,h.createdAt)," elapsed · refreshing every 3s"]}),e.jsxs("span",{className:"sr-only",children:["now=",p]})]}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Refreshing this project from the current Common Crawl release."})]})]})}),u&&!h&&e.jsx(ye,{className:`surface-card p-4 mb-4 ${u.status==="failed"?"border-negative-800/60":"border-positive-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[u.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(Om,{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 ${u.status==="failed"?"text-negative":"text-positive"}`,children:u.status==="failed"?"Extract failed":"Extract complete"}),u.error?e.jsx("p",{className:"text-sm text-secondary mt-1",children:ld(u.error)}):u.status!=="failed"?e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),G()]});function G(){return S?e.jsx(ye,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading backlinks…"})}):C()}function C(){const q=s!==null&&s.totalLinkingDomains>0,se=u?.status==="failed",V=s!==null&&s.totalLinkingDomains===0&&!se,B=c?.status==="ready",E=c?.status==="failed",R=c&&(c.status==="downloading"||c.status==="querying"||c.status==="queued");return q?ae(e.jsxs(e.Fragment,{children:[!ie()&&e.jsxs(e.Fragment,{children:[e.jsxs(P,{type:"button",variant:"outline",size:"sm",disabled:D||h!==null,onClick:Ye(M),children:[e.jsx(bl,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":D?"Queuing…":"Re-run extract"]}),e.jsx(pr,{label:"About re-running",children:"Re-queries the current release for this project without downloading it again."})]}),!ie()&&e.jsx(P,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Cn("/backlinks"),children:"Open admin"})})]})):e.jsx(ye,{className:"surface-card p-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-bg-elevated text-secondary",children:e.jsx(Fm,{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."}),!ie()&&e.jsx("div",{className:"mt-4",children:e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Cn("/backlinks"),children:"Set up backlinks"})})})]}),R&&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."]}),!ie()&&e.jsx("div",{className:"mt-4",children:e.jsx(P,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Cn("/backlinks"),children:"View sync status"})})})]}),E&&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."}),!ie()&&e.jsx("div",{className:"mt-4",children:e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Cn("/backlinks"),children:"Go to Backlinks admin"})})})]}),B&&!R&&!V&&!se&&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."]}),!ie()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(P,{type:"button",size:"sm",disabled:D||h!==null,onClick:Ye(M),children:[e.jsx(_a,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":D?"Queuing…":"Run extract"]}),e.jsx(pr,{label:"About extraction",children:"Queries the current release for this project without downloading it again."})]})]}),se&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Last extract failed"}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"See the error above, then check the workspace source before retrying."}),!ie()&&e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Cn("/backlinks"),children:"Go to Backlinks admin"})})})]}),V&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No referring domains found"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["The latest release found no referring domains for ",s.targetDomain,". Try a newer release or re-run this extract."]}),!ie()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Cn("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(P,{type:"button",variant:"outline",size:"sm",disabled:D||h!==null,onClick:Ye(M),children:[e.jsx(_a,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":D?"Queuing…":"Re-run extract"]}),e.jsxs(pr,{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 ae(q){if(!s)return null;const se="Linking hosts",V="linking hosts",B="release";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"gauge-row",children:[e.jsxs("div",{className:"metric-card",children:[e.jsx("p",{className:"metric-card-eyebrow",children:"Referring domains"}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:gr(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 ",V]}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:gr(s.totalHosts)})}),e.jsxs("p",{className:"metric-card-sub",children:["aggregate ",V," 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:Kx(s.top10HostsShare)})}),e.jsxs("p",{className:"metric-card-sub",children:["share of ",V," from the 10 largest linking domains"]})]})]}),e.jsxs("p",{className:"text-xs text-muted mt-2",children:[e.jsx("span",{className:"text-secondary",children:"Common Crawl"})," · ",B," ",e.jsx("code",{className:"text-secondary",children:s.release})," · queried ",Gx(s.queriedAt),O>0&&e.jsxs(e.Fragment,{children:[" · ",O," excluded domain",O===1?"":"s"]})]}),L.length>=2&&e.jsxs(ye,{className:"surface-card p-4 mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Referring domains over time"}),e.jsx("div",{className:"h-40 mt-2",children:e.jsx(Xs,{width:"100%",height:"100%",children:e.jsxs(Zs,{data:L,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:rt[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:rt[0],stopOpacity:0})]})}),e.jsx(en,{dataKey:"date",tick:Ft,stroke:ds,tickFormatter:Ox}),e.jsx(tn,{tick:Ft,stroke:ds,allowDecimals:!1}),e.jsx(sn,{contentStyle:ts.contentStyle,labelStyle:ts.labelStyle,itemStyle:ts.itemStyle,labelFormatter:Fx}),e.jsx(Bs,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:rt[0],fill:"url(#bl-gradient)",strokeWidth:2})]})})})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Top referring domains"}),e.jsx(ye,{className:"surface-card overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base text-left text-xs uppercase tracking-wide text-faint",children:[e.jsx("th",{className:"px-4 py-2 font-medium",children:"Domain"}),e.jsx("th",{className:"px-4 py-2 text-right font-medium",children:se})]})}),e.jsxs("tbody",{children:[F.map(E=>e.jsxs("tr",{className:"border-b border-mono-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-strong",children:E.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-secondary tabular-nums",children:gr(E.numHosts)})]},E.linkingDomain)),F.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-muted",colSpan:2,children:O>0&&H===0?`Every referring domain in this ${B} was a crawler/proxy host (${O} hidden).`:`No referring domains in this ${B}.`})})]})]})}),e.jsx(Ls,{page:J,pageSize:wa,visibleRows:F.length,totalRows:H,onPageChange:E=>f((E-1)*wa)})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:q})]})}}function Vx({projectName:t}){const s=Te({...dd({client:Y,path:{name:t}}),staleTime:ri}),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:ea(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:Bt()?"text-sm text-secondary":"text-sm text-muted",children:n.reason==="no-queries"?"Add queries to start tracking AI citations.":Bt()?Js:"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(Ve,{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(Ve,{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(Qx,{data:n}),e.jsx(zx,{data:n}),n.competitorGaps.length>0&&e.jsx(Jx,{data:n})]})}function Qx({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(Sa,{label:"Cited + mentioned",value:`${n} / ${s}`,helper:"In sources AND named in answer",tone:n>0?"positive":"neutral"}),e.jsx(Sa,{label:"Cited only",value:`${a} / ${s}`,helper:"In sources, not named in answer",tone:a>0?"positive-dim":"neutral"}),e.jsx(Sa,{label:"Mentioned only",value:`${r} / ${s}`,helper:"Named in answer, no source link",tone:r>0?"caution":"neutral"}),e.jsx(Sa,{label:"Invisible",value:`${o} / ${s}`,helper:"No engine cites or mentions",tone:o>0?"negative":"neutral"})]})}function Sa({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 zx({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(Wx,{}),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(Ln,{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(vl,{className:"inline h-3.5 w-3.5 text-mono-700","aria-label":"no data"}):e.jsx(Hx,{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 Wx(){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(Rn,{active:!0,tone:"cited"}),e.jsx("span",{children:"cited (in sources)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Rn,{active:!0,tone:"mentioned"}),e.jsx("span",{children:"mentioned (in answer)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Rn,{active:!1,tone:"cited"}),e.jsx(Rn,{active:!1,tone:"mentioned"}),e.jsx("span",{children:"neither"})]})]})}function Hx({provider:t}){const s=Yx(t);return e.jsxs("span",{className:"inline-flex items-center justify-center gap-1",title:s,children:[e.jsx(Rn,{active:t.cited,tone:"cited"}),e.jsx(Rn,{active:t.mentioned,tone:"mentioned"})]})}function Yx(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 Rn({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 Jx({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(Ve,{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(Ln,{provider:s.provider})}),e.jsx("td",{className:"text-neutral",children:s.citingCompetitors.join(", ")})]},`${s.queryId}::${s.provider}`))})]})})]})}const ro="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",fr="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",Bn=t=>t.kind==="project"?"Whole site":t.label,Vn={allMarkets:"All markets",browse:t=>`Browse ${t}`,select:t=>`Select ${t}`,browseAll:"Browse all properties"},Xx=t=>t?.kind==="group"&&t.marketKeys?.length===1?t.marketKeys[0]:void 0,io=t=>`${t} ${t===1?"property":"properties"}`;function _l({options:t,selected:s,onSelect:n,marketKey:a,label:r="Measurement scope",allowGroupSelect:o=!0}){const i=[...t].sort((T,ee)=>T.label.localeCompare(ee.label,void 0,{numeric:!0})||T.id.localeCompare(ee.id)),[c,d]=l.useState(""),[h,m]=l.useState([]),[u,b]=l.useState(!1),p=l.useRef(null),x=l.useRef(null),g=l.useId(),f=i.filter(T=>T.kind==="group"),S=new Map(f.map(T=>[T.id,T])),j=S.get(h.at(-1)??""),D=S.get(h.at(-2)??""),A=c.trim().toLocaleLowerCase(),y=f.filter(T=>!T.parentGroupIds?.some(ee=>S.has(ee))),w=i.filter(T=>T.kind==="property"),N=T=>(T.parentGroupIds??[]).map(ee=>S.get(ee)?.label).filter(Boolean).join(" · "),M=T=>`${Bn(T)} ${N(T)}`.toLocaleLowerCase().includes(A),L=T=>{const ee=[...T.parentGroupIds??[]],Z=new Set;for(;ee.length;){const ge=ee.pop();if(ge===j?.id)return!0;Z.has(ge)||(Z.add(ge),ee.push(...S.get(ge)?.parentGroupIds??[]))}return!1},F=(u?[]:j?f.filter(T=>A?L(T):T.parentGroupIds?.includes(j.id)):A?f:y).filter(M),H=i.find(T=>T.kind==="market"&&T.id===(a??(s.kind==="market"?s.id:void 0))),O=j&&H&&(j.marketKeys?.includes(H.id)||H.parentGroupIds?.includes(j.id))?H.id:void 0,J=o?O??Xx(j):void 0,G=(j?w.filter(T=>T.parentGroupIds?.includes(j.id)&&(!J||T.marketKeys?.includes(J))):A||u||f.length===0?w:[]).filter(M),C=i.filter(T=>T.kind!=="market"||u||!o&&!j&&!A&&f.length>0||o&&j?.marketKeys?.length===1&&!A?!1:(j?A?L(T):T.parentGroupIds?.includes(j.id):A||!T.parentGroupIds?.some(Z=>S.has(Z)))&&M(T)),ae=j||u?[]:i.filter(T=>T.kind==="project"&&M(T));l.useEffect(()=>{const T=ee=>{p.current?.open&&ee.target instanceof Node&&!p.current.contains(ee.target)&&(p.current.open=!1)};return document.addEventListener("pointerdown",T),()=>document.removeEventListener("pointerdown",T)},[]);const q=T=>{p.current&&(p.current.open=!1,p.current.querySelector("summary")?.focus());const ee=o?T.kind==="property"?J:T.kind==="group"&&T.id===j?.id?O:void 0:void 0;ee?n(T,ee):n(T)},se=T=>{const ee=[];let Z=S.get(T.parentGroupIds?.[0]??"");for(;Z&&!ee.includes(Z.id)&&Z.id!==T.id;)ee.unshift(Z.id),Z=S.get(Z.parentGroupIds?.[0]??"");return[...ee,T.id]},V=()=>{const T=s.kind==="group"?S.get(s.id):void 0,ee=S.get(H?.parentGroupIds?.[0]??""),Z=(s.parentGroupIds??[]).flatMap(de=>{const xe=S.get(de);return xe?[se(xe)]:[]}),ge=Z.find(de=>de.at(-1)===j?.id)??Z.sort((de,xe)=>xe.length-de.length)[0]??[],X=ee?se(ee):s.marketKeys?.length?[]:ge;m(T?se(T):X),b(s.kind==="property"&&X.length===0&&f.length>0),d("")},B=T=>{m(se(T)),b(!1),d(""),x.current?.focus()},E=(T,ee=Bn(T))=>e.jsxs("div",{className:"flex items-stretch",children:[e.jsxs("button",{type:"button",className:fr,"aria-label":T.kind==="group"&&!o?Vn.browse(Bn(T)):Vn.select(Bn(T)),"aria-current":s.kind===T.kind&&s.id===T.id?"true":void 0,onClick:()=>T.kind==="group"&&!o?B(T):q(T),children:[e.jsxs("span",{className:"min-w-0 break-words",children:[ee,A&&N(T)?e.jsx("span",{className:"block text-[13px] text-secondary",children:N(T)}):null]}),e.jsx("span",{className:"shrink-0 text-right text-[13px] text-secondary",children:T.kind==="market"?o?"Query context":"Market":T.kind==="property"?"Property":io(T.targetCount)})]}),o&&T.kind==="group"&&T.id!==j?.id&&i.some(Z=>Z.parentGroupIds?.includes(T.id))?e.jsx("button",{type:"button","aria-label":Vn.browse(T.label),title:`Browse ${T.label}`,className:"flex min-h-11 min-w-11 items-center justify-center rounded text-secondary hover:bg-surface-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>B(T),children:e.jsx(Ga,{size:18,"aria-hidden":"true"})}):null]},`${T.kind}:${T.id}`),R=(T,ee)=>ee.length>0?e.jsxs("section",{"aria-label":T,className:"mt-2",children:[e.jsx("h3",{className:"px-2 py-2 text-[13px] font-medium text-secondary",children:T}),ee.map(Z=>E(Z))]}):null,oe=(T,ee,Z)=>ee.length>0?e.jsxs("details",{open:Z,className:"mt-2 border-y border-default",children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer px-2 py-3 text-sm text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",children:[T," (",ee.length,")"]}),ee.map(ge=>E(ge))]},`${j?.id??"root"}:${T}`):null;return e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{id:`${g}-label`,className:"mb-1 block text-sm font-medium text-heading",children:r}),e.jsxs("details",{ref:p,className:"relative",onToggle:T=>{T.target===T.currentTarget&&T.currentTarget.open&&x.current?.focus()},onKeyDown:T=>{T.key==="Escape"&&(T.preventDefault(),T.currentTarget.open=!1,T.currentTarget.querySelector("summary")?.focus())},children:[e.jsxs("summary",{id:`${g}-value`,"aria-labelledby":`${g}-label ${g}-value`,className:`${ro} visibility-scope-trigger`,onClick:()=>{p.current?.open||V()},children:[`${Bn(s)}${s.kind==="group"?` · ${io(s.targetCount)}`:s.kind==="property"?` · ${i.find(T=>T.kind==="market"&&T.id===a)?.label??(s.marketKeys?.length?Vn.allMarkets:"Property")}`:s.kind==="market"?" · Market":""}`,e.jsx(gn,{size:16,"aria-hidden":"true",className:"shrink-0 text-secondary"})]}),e.jsxs("div",{className:"visibility-scope-menu",children:[j||u?e.jsxs("div",{className:"mb-2 border-b border-default pb-2",children:[e.jsx("button",{type:"button",className:fr,"aria-label":`Back to ${D?.label??"all groups"}`,onClick:()=>{m(h.slice(0,-1)),b(!1),d(""),x.current?.focus()},children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Gm,{size:16,"aria-hidden":"true"}),D?.label??"All groups"]})}),e.jsx("p",{className:"px-2 py-1 text-sm font-medium text-heading","aria-live":"polite",children:j?.label??"All properties"})]}):null,e.jsx("input",{ref:x,type:"search","aria-label":"Search scopes",className:ro,placeholder:j?"Search within this group":u?"Search properties":"Search groups or properties",value:c,onChange:T=>d(T.target.value)}),e.jsxs("div",{className:"mt-2 max-h-80 overflow-y-auto",children:[o&&j&&!A?E(j,"All properties in this group"):null,ae.map(T=>E(T)),j&&!A?oe("Subgroups",F,!0):R(j?"Subgroups":"Groups",F),A?R("Properties",G):oe(j&&F.length>0?"All properties":"Properties",G,!j||F.length===0),R("Markets",C),!j&&!u&&!A&&f.length>0&&w.length>0?e.jsxs("button",{type:"button",className:`${fr} mt-2 border-t border-default`,"aria-label":Vn.browseAll,onClick:()=>{b(!0),x.current?.focus()},children:[e.jsx("span",{children:"All properties"}),e.jsx(Ga,{size:18,"aria-hidden":"true"})]}):null,A&&F.length+G.length+C.length+ae.length===0?e.jsx("p",{className:"py-3 text-sm text-secondary",children:"No matching scopes."}):null]})]})]})]})}const ia="__cited__",oa="__mentioned__",cs="__mentionShare__";function Ul(t){const s=t,{dataStartDate:n,dataEndDate:a}=s;return typeof n!="string"||typeof a!="string"?null:{start:Es(n),end:Es(a),sweepCount:s.sweepCount??1}}function Va(t){const s=Ul(t);if(!s)return"Sweep date unavailable";const n=Ws(s.start),a=Ws(s.end);return n===a?n:`${n} – ${a} · ${s.sweepCount} sweeps combined`}function Zx(t){const s=Ul(t);return s?Sl(s.start):""}function En(t){return t.trim().toLowerCase()}function Qr(t){return Math.round(t*1e3)/10}function zr(t){return t.byProvider??{}}function ep(t,s,n){const a=t.buckets.length>0,r=t.buckets.length===1;if(n==="overall"){const d=s==="cited"?ia:oa,h=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(u=>({date:u.startDate,[d]:Qr(u[h])})),series:[d],hasData:a,singleBucket:r}}const o=s==="mentioned"?"mentionRate":"citationRate",i=[...new Set(t.buckets.flatMap(d=>Object.keys(zr(d))))].sort();return{rows:t.buckets.map(d=>{const h={date:d.startDate},m=zr(d);for(const u of i){const b=m[u];h[u]=b?Qr(b[o]):null}return h}),series:i,hasData:a,singleBucket:r}}function Bl(t){const s=t;return Object.hasOwn(s,"modelEvidenceByProvider")?s.modelEvidenceByProvider??{}:null}function tp(t){const s=t;return Object.hasOwn(s,"modelAttribution")?s.modelAttribution??{}:null}function sp(t){return t.servedModelAttribution??{}}function np(t){return t.modelServiceMismatch??{}}function ap(t){return t.modelPointerChanges??{}}function rp(t){return t.length>0?t.join(", "):null}function oo(t,s){const n=En(s);return Object.entries(t).find(([a])=>En(a)===n)?.[1]}function Is(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 ip(t,s){for(let n=t.length-1;n>=0;n-=1){const a=t[n];if(!oo(zr(a),s))continue;const r=Bl(a);return r?oo(r,s)??null:null}return null}function op(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 lp(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:op(s),beforeWindow:n.sort((a,r)=>a.event.observedAt.localeCompare(r.event.observedAt)||a.provider.localeCompare(r.provider))}}function cp(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 dp(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 up(t){const s=t.buckets.map(a=>{const r=a.mentionShare;return{date:a.startDate,[cs]:r?.rate==null?null:Qr(r.rate)}}),n=s.map(a=>a[cs]).filter(a=>typeof a=="number"&&Number.isFinite(a));return{rows:s,series:[cs],hasData:n.length>0,singleBucket:n.length===1}}function mp(t,s,n){return s==="mentionShare"?up(t):ep(t,s,n)}function lo(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 co(t){const[,s,n]=t.slice(0,10).split("-");return!s||!n?t:`${s}/${n}`}function uo(t){return t>0?`+${t}`:`${t}`}function hp(t){if(t.length===0)return null;if(t.length<=2)return`Query set changed: ${t.map(n=>`${uo(n.delta)} on ${co(n.date)}`).join(", ")}`;const s=[...t].sort((n,a)=>a.date.localeCompare(n.date))[0];return`Query set changed ${t.length} times (latest ${uo(s.delta)} on ${co(s.date)})`}const xp=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],mo="Measured answers",pp="Close answers",Ts={"non-brand":"Non-brand queries",branded:"Branded queries",unknown:"Unclassified queries"},In="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",Wr=new Intl.NumberFormat("en",{style:"percent",maximumFractionDigits:1});function gp(t){return t.kind==="project"?"Whole site":t.kind==="group"?`${t.label} · Group`:t.kind==="market"?`${t.label} · Market`:t.label}function Cs({value:t,unit:s}){return t.rate===null?e.jsx("span",{className:"text-sm text-secondary",children:t.reason==="identity-ambiguous"?Et.ambiguous: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:Wr.format(t.rate)}),e.jsxs("span",{className:"text-sm tabular-nums text-secondary",children:[t.numerator," of ",t.denominator,s?` ${s}`:""]})]})}const fp={otherQueries:"Other queries"};function yp(t,s){const n=new Map;for(const r of t){const o=n.get(r.queryKey);o?o.rows.push(r):n.set(r.queryKey,{queryKey:r.queryKey,query:r.query,rows:[r]})}const a=[...n.values()];if(!s||!t.some(r=>r.marketKeys?.length))return a;for(const r of a){const o=[...new Set(r.rows.flatMap(i=>i.marketKeys??[]))].sort();r.marketLabel=o.map(i=>s.get(i)??i).join(" · ")||fp.otherQueries}return a.sort((r,o)=>r.marketLabel.localeCompare(o.marketLabel)||r.query.localeCompare(o.query))}function ho({value:t,singleAnswer:s}){if(s&&t.denominator===1&&(t.rate===0||t.rate===1)){const n=t.rate===1;return e.jsxs("span",{className:`inline-flex items-center gap-2 text-sm ${n?"text-positive":"text-secondary"}`,children:[n?e.jsx(_m,{size:16,"aria-hidden":"true"}):e.jsx(vl,{size:16,"aria-hidden":"true"}),n?"Yes":"No"]})}return e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Cs,{value:t}),t.reason==="evidence-incomplete"?e.jsx(Ve,{text:"The saved evidence is incomplete, so this result cannot be measured. It does not mean the answer had no citation."}):null]})}function xo({targetKeys:t,labels:s}){return t.length===0?e.jsx("span",{children:"No assigned properties"}):t.length===1?e.jsx("span",{children:s.get(t[0])??t[0]}):e.jsxs("details",{children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-3 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",children:[t.length," properties"]}),e.jsx("ul",{className:"max-h-48 space-y-2 overflow-y-auto pb-3",children:t.map(n=>e.jsx("li",{children:s.get(n)??n},n))})]})}function bp({group:t,advanced:s,targetLabels:n,marketHeading:a,onViewAnswers:r}){const o=t.rows[0],i=m=>JSON.stringify([...m.targetKeys].sort()),c=t.rows.every(m=>i(m)===i(o)),d=t.rows.every(m=>m.location===o.location),h=m=>m===null?"No location targeting":`Search location: ${m}`;return e.jsxs("tbody",{"data-query-key":t.queryKey,children:[a?e.jsx("tr",{children:e.jsx("th",{colSpan:4,className:"border-t border-default py-4 text-left",children:e.jsx("h3",{className:"text-base font-semibold text-heading",children:a})})}):null,e.jsx("tr",{className:"measurement-result-heading",children:e.jsxs("th",{scope:"rowgroup",colSpan:4,children:[e.jsx("h3",{className:"break-words text-base font-medium text-heading",children:t.query}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 text-sm font-normal text-secondary",children:[s&&c?e.jsx(xo,{targetKeys:o.targetKeys,labels:n}):null,d?e.jsx("span",{children:h(o.location)}):null]})]})}),t.rows.map(m=>e.jsxs("tr",{className:"measurement-engine-result",children:[e.jsxs("td",{className:"measurement-result-engine",children:[e.jsx("span",{className:"font-medium text-heading",children:ks(m.provider)}),e.jsx("span",{className:"block break-words text-sm text-secondary",children:m.model??"Model not recorded"}),s&&!c?e.jsx("div",{className:"mt-1 text-sm text-secondary",children:e.jsx(xo,{targetKeys:m.targetKeys,labels:n})}):null,d?null:e.jsx("span",{className:"mt-1 block text-sm text-secondary",children:h(m.location)})]}),e.jsxs("td",{children:[e.jsx("span",{className:"measurement-result-mobile-label","aria-hidden":"true",children:"Mentioned"}),e.jsx(ho,{value:m.mentionCoverage,singleAnswer:m.answerCount===1})]}),e.jsxs("td",{children:[e.jsx("span",{className:"measurement-result-mobile-label","aria-hidden":"true",children:"Cited"}),e.jsx(ho,{value:m.citationCoverage,singleAnswer:m.answerCount===1})]}),e.jsx("td",{className:"measurement-result-action",children:e.jsxs(P,{variant:"ghost",className:"min-h-11","aria-label":`View answers for ${m.query} · ${m.provider}`,onClick:u=>r(m,u.currentTarget),children:[m.answerCount===1?"View answer":"View answers",e.jsx(Ga,{size:16,"aria-hidden":"true"})]})})]},JSON.stringify([m.provider,m.model,m.location])))]})}function vp({population:t}){const s=l.useId();let n=0;const a=t.trend.map((d,h)=>(h>0&&d.continuity.state!=="comparable"&&(n+=1),{createdAt:Date.parse(d.createdAt),[`mentioned-${n}`]:d.mentionCoverage.rate,[`cited-${n}`]:d.citationCoverage.rate})),r=Array.from({length:n+1},(d,h)=>h),o=new Set(t.trend.slice(1).map(d=>d.continuity.state)),i=[...a.length===1?["First measurement. A trend appears after another comparable run."]:[],...o.has("definition-changed")?["Gaps mark changes to what was measured."]:[],...o.has("model-changed")?["Gaps mark changes to answer engines or models."]:[],...o.has("legacy-unknown")?["Older runs lack the details needed for comparison."]:[],...t.trend.some(d=>d.citationCoverage.reason==="evidence-incomplete")?["Missing citation results mean the saved evidence is incomplete."]:[]];if(a.length===0)return e.jsx("p",{className:"py-6 text-sm text-secondary",children:"No measured trend for this selection."});const c=t.trend.some(d=>d.mentionCoverage.rate!==null||d.citationCoverage.rate!==null);return e.jsxs(e.Fragment,{children:[c?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:rt[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:qs.positive}}),"Cited"]})]}),i.length>0&&e.jsx("p",{id:s,className:"pb-3 text-sm text-secondary",children:i.join(" ")}),e.jsx("div",{className:"visibility-trend-chart",role:"img","aria-describedby":i.length>0?s:void 0,"aria-label":`${Ts[t.queryClass]} mention and citation trend`,children:e.jsx(Xs,{width:"100%",height:"100%",children:e.jsxs(Zs,{data:a,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(na,{stroke:sa,vertical:!1}),e.jsx(en,{dataKey:"createdAt",type:"number",scale:"time",domain:["dataMin","dataMax"],tick:Ft,tickLine:!1,axisLine:{stroke:ds},tickFormatter:d=>new Date(Number(d)).toLocaleDateString(void 0,{month:"short",day:"numeric"}),minTickGap:24}),e.jsx(tn,{domain:[0,1],tick:Ft,tickLine:!1,axisLine:!1,width:48,tickFormatter:d=>Wr.format(Number(d))}),e.jsx(sn,{...ts,formatter:d=>typeof d=="number"?Wr.format(d):"Not measured",labelFormatter:d=>new Date(Number(d)).toLocaleDateString()}),r.map(d=>e.jsxs(l.Fragment,{children:[e.jsx(Ms,{type:"linear",dataKey:`mentioned-${d}`,name:"Mentioned",stroke:rt[1],strokeWidth:2,connectNulls:!1,isAnimationActive:!1,dot:{r:3}}),e.jsx(Ms,{type:"linear",dataKey:`cited-${d}`,name:"Cited",stroke:qs.positive,strokeWidth:2,connectNulls:!1,isAnimationActive:!1,dot:{r:3}})]},d))]})})})]}):e.jsx("p",{className:"py-6 text-sm text-secondary",children:"No measured trend for this selection."}),e.jsx("div",{className:c?"sr-only":"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table","aria-label":`${Ts[t.queryClass]} trend data`,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(d=>e.jsxs("tr",{children:[e.jsx("td",{children:new Date(d.createdAt).toLocaleDateString()}),e.jsx("td",{children:e.jsx(Cs,{value:d.mentionCoverage})}),e.jsx("td",{children:e.jsx(Cs,{value:d.citationCoverage})}),e.jsx("td",{children:d.continuity.state.replaceAll("-"," ")})]},d.runId))})]})})]})}function Hr(t,s){return s?t?.populations.find(n=>[...n.queries.items,...n.evidence.items].some(a=>a.queryKey===s)):void 0}function li(t,s,n,a){const r=t.selection.queryClass==="all"?n?.queryClass:t.selection.queryClass,o=t.populations.find(h=>h.queryClass===r);if(o)return o;const i=Hr(a,s)??Hr(t,s),c=t.populations.find(h=>h.queryClass===i?.queryClass);if(c)return c;const d=["non-brand","branded","unknown"].map(h=>t.populations.find(m=>m.queryClass===h));return d.find(h=>h&&(h.summary.queryCount>0||h.trend.some(m=>m.queryCount>0)))??d.find(h=>h!==void 0)??t.populations[0]}function jp({report:t,onSelectionChange:s,queryClass:n=li(t).queryClass}){const{selection:a,scopeOptions:r,filterOptions:o}=t,i=(c,d,h,m)=>e.jsxs("label",{className:"min-w-0",children:[e.jsx("span",{className:"mb-1 block text-sm font-medium text-heading",children:c}),e.jsx("select",{"aria-label":c,className:In,value:h,onChange:u=>s({[d]:u.target.value||void 0,measurementQueryKey:void 0}),children:m.map(u=>e.jsx("option",{value:u.value,children:u.label},u.value))})]});return e.jsx("div",{className:"visibility-filter-container",children:e.jsxs("div",{className:"visibility-report-filters","data-has-scope":r.length>1,role:"group","aria-label":"Visibility filters",children:[r.length>1?e.jsx(_l,{options:r,selected:a.scope,marketKey:a.market?.id,onSelect:(c,d)=>{s({measurementScope:c.kind,measurementScopeKey:c.kind==="project"?void 0:c.id,measurementMarketKey:d})}}):null,i("Query type","queryClass",n,[{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"},{value:"unknown",label:"Unclassified"}]),i("Answer engine","measurementProvider",a.provider??"",[{value:"",label:"All engines"},...o.providers.map(c=>({value:c,label:c}))]),i("Search location","measurementLocation",a.location.kind==="exact"?a.location.value:a.location.kind==="none"?"none":"",[{value:"",label:"All locations"},...o.locations.filter(c=>c.kind!=="all").map(c=>({value:c.kind==="exact"?c.value:"none",label:c.kind==="exact"?c.value:"No location"}))])]})})}function Np({report:t,isRefreshing:s=!1,onSelectionChange:n,onManageQueries:a,onPage:r,onSearch:o,search:i="",queryKey:c,answerSelection:d,evidenceReport:h,isEvidenceLoading:m=!1,evidenceError:u,onRetryEvidence:b,onEvidencePage:p}){const x=l.useRef(null),g=l.useRef(void 0),f=l.useRef(null),S=li(t,c,d,h),j=h??t,D=j.populations.filter(C=>[...C.queries.items,...C.evidence.items].some(ae=>ae.queryKey===c)),A=d?[d.queryClass]:(D.length?D:m?[]:[S]).map(C=>C.queryClass),y=c?JSON.stringify([d??c,A]):void 0,w=l.useId();l.useEffect(()=>{if(!y){s||(g.current=void 0);return}if(g.current===y)return;const C=x.current?.querySelectorAll(`[aria-label="${mo}"]`);if(C?.length){for(const ae of C){const q=ae.closest("details[data-query-results]");q&&(q.open=!0)}C[0].focus({preventScroll:!0}),C[0].scrollIntoView?.({block:"start"}),g.current=y}},[y,s]);const{selection:N,filterOptions:M}=t,L=N.measurement,F=gp(N.scope),H=new Map(t.scopeOptions.filter(C=>C.kind==="property").map(C=>[C.id,C.label])),O=C=>{const ae=j.populations.find(q=>q.queryClass===C.queryClass)?.evidence;return{items:ae?.items.filter(q=>q.queryKey===c&&(!d||q.provider===d.provider&&q.model===d.model&&q.location===d.location&&(d.runId===null||q.runId===d.runId)))??[],nextCursor:ae?.nextCursor}},J=()=>{g.current=void 0;const C=f.current;C!==null&&C.row.queryKey===c&&(!d||C.row.provider===d.provider&&C.row.model===d.model&&C.row.location===d.location)&&C?.element.isConnected?C.element.focus():x.current?.querySelector(`details[data-query-results="${S.queryClass}"] > summary`)?.focus(),n({measurementQueryKey:void 0,measurementAnswer:void 0})},G=(C,ae,q,se,V)=>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:`${w}-${ae}`,className:"text-sm font-medium text-heading",children:C}),e.jsx(Ve,{text:V})]}),e.jsx("select",{id:`${w}-${ae}`,className:In,value:q,onChange:B=>n({[ae]:B.target.value||void 0,measurementQueryKey:void 0}),children:se.map(B=>e.jsx("option",{value:B.value,children:B.label},B.value))})]});return e.jsxs("section",{ref:x,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(ue,{tone:L.state==="measured"?"positive":"neutral",children:L.state==="measured"?"Complete":L.state==="partial"?"Partial":"Not measured"}),L.completedAt?e.jsx("span",{className:"text-sm text-secondary",children:new Date(L.completedAt).toLocaleDateString()}):null]}),a?e.jsx(P,{variant:"outline",onClick:a,children:"Manage queries"}):null]}),N.provenance.kind==="legacy-simple"&&N.queryClass!=="unknown"&&N.queryClass!=="all"?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:"These saved results aren't separated by query type."}),e.jsx(P,{variant:"outline",onClick:()=>n({queryClass:"all",measurementQueryKey:void 0}),children:"View all saved results"})]}):null,e.jsx(jp,{report:t,queryClass:S.queryClass,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:In,value:N.time.from?.slice(0,10)??"",onChange:C=>n({measurementFrom:C.target.value?`${C.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:In,value:N.time.to?.slice(0,10)??"",onChange:C=>n({measurementTo:C.target.value?`${C.target.value}T23:59:59.999Z`:void 0})})]}),G("AI model","measurementModel",N.model??"",[{value:"",label:"All models"},...Array.from(new Set(M.models.filter(C=>!N.provider||C.provider===N.provider).map(C=>C.model))).map(C=>({value:C,label:C}))],"Filter by the AI model recorded with each answer. This does not change the model used by future sweeps."),G("Results from","measurementRunId",N.run.explicit?N.run.id??"":"",[{value:"",label:"Latest saved sweep"},...[...S.trend].reverse().map(C=>({value:C.runId,label:new Date(C.createdAt).toLocaleString()}))],"Choose a saved AI sweep to view its results. No new sweep starts.")]})]}),[S].map(C=>{const ae=yp(C.queries.items,N.scope.kind==="property"&&!N.market&&C.queryClass==="non-brand"?new Map(t.scopeOptions.filter(V=>V.kind==="market").map(V=>[V.id,V.label])):void 0),q=O(C),se=q.items[0]?.query??C.queries.items.find(V=>V.queryKey===c)?.query;return e.jsxs("section",{"aria-label":Ts[C.queryClass],className:"py-4",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("h2",{children:Ts[C.queryClass]}),e.jsx(Ve,{text:C.queryClass==="non-brand"?"Queries that do not name the measured identity. Geography alone is not a brand.":C.queryClass==="branded"?"Queries that name the measured identity.":"These queries were not labeled as branded or non-brand when measured. Their saved results remain available here, separate from branded and 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:N.mode==="advanced"&&N.scope.kind!=="property"?"Answers mentioning a property":"Mentioned answers"}),N.mode==="advanced"?e.jsx(Ve,{text:"An answer counts when it mentions any assigned property. This does not mean every property was mentioned."}):null]}),e.jsx(Cs,{value:C.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:N.mode==="advanced"&&N.scope.kind!=="property"?"Answers citing a property":"Cited answers"}),N.mode==="advanced"?e.jsx(Ve,{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(Cs,{value:C.summary.citationCoverage,unit:"answers"})]}),N.mode==="advanced"&&N.scope.kind!=="property"?e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-sm text-secondary",children:"Properties mentioned"}),e.jsx(Cs,{value:C.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:C.summary.queryCount})]})]}),e.jsx(vp,{population:C}),N.mode==="advanced"?e.jsxs("details",{className:"border-t border-default text-sm text-secondary","aria-label":`${Ts[C.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(([V,B])=>e.jsxs("div",{children:[e.jsx("strong",{className:"block tabular-nums text-heading",children:C.summary.outcomes[V]}),e.jsx("span",{className:"text-sm text-secondary",children:B}),V==="notMeasured"?e.jsx(Ve,{text:"No eligible completed measurement for this selection. This is not the same as a measured answer with neither signal."}):null]},V))})]}):null,N.mode==="advanced"&&N.scope.kind!=="property"&&(C.breakdown.groups.length>0||C.breakdown.properties.length>0)?e.jsx(wp,{population:C,scope:N.scope,scopeOptions:t.scopeOptions,marketKey:N.market?.id,onSelectionChange:n},`${N.scope.kind}:${N.scope.id}`):null,e.jsxs("details",{className:"border-t border-default","data-query-results":C.queryClass,"aria-label":`${Ts[C.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:[C.queries.total," ",C.queries.total===1?"result":"results"," · ",F]})]}),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 ${Ts[C.queryClass]}`,placeholder:"Search queries",className:`${In} max-w-sm`,value:i,onChange:V=>o(V.target.value)}):null,e.jsx(Ve,{text:N.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 measurement-results-table","aria-label":`${Ts[C.queryClass]} engine results`,children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Answer engine"}),e.jsx("th",{scope:"col",children:"Mentioned"}),e.jsx("th",{scope:"col",children:"Cited"}),e.jsx("th",{scope:"col",children:e.jsx("span",{className:"sr-only",children:"Evidence"})})]})}),ae.map((V,B)=>e.jsx(bp,{group:V,marketHeading:V.marketLabel!==ae[B-1]?.marketLabel?V.marketLabel:void 0,advanced:N.mode==="advanced",targetLabels:H,onViewAnswers:(E,R)=>{f.current={row:E,element:R},n({measurementQueryKey:E.queryKey,measurementAnswer:JSON.stringify({queryKey:E.queryKey,queryClass:C.queryClass,provider:E.provider,model:E.model,location:E.location,runId:N.run.id,revision:N.revision})})}},V.queryKey))]})}),C.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:[ae.length," ",ae.length===1?"query":"queries"," · ",C.queries.items.length," ",C.queries.items.length===1?"engine result":"engine results"," shown of ",C.queries.total," results"]}),C.queries.nextCursor&&r?e.jsx(P,{variant:"outline",onClick:()=>r(C.queries.nextCursor),children:"Next queries"}):null,c&&A.includes(C.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":mo,"aria-busy":m,children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsx("h3",{className:"min-w-0 flex-1 text-base font-semibold text-heading [overflow-wrap:anywhere]",children:se??"Answers"}),e.jsx(P,{variant:"ghost",className:"min-h-11",onClick:J,children:pp})]}),m?e.jsx("p",{role:"status",className:"py-4 text-sm text-secondary",children:"Loading saved answers…"}):u?e.jsxs("div",{role:"alert",className:"py-4 text-sm text-secondary",children:[e.jsxs("p",{children:["Saved answers unavailable: ",u]}),b?e.jsx(P,{variant:"outline",onClick:b,children:"Retry answers"}):null]}):e.jsxs(e.Fragment,{children:[q.items.map(V=>e.jsxs("article",{className:"border-b border-default py-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-2",children:[e.jsx("strong",{className:"text-sm text-heading",children:V.provider}),V.model?e.jsx("span",{className:"text-[13px] text-secondary",children:V.model}):null,e.jsx("span",{className:"text-[13px] text-secondary",children:V.location??"No location"}),e.jsx("span",{className:"text-[13px] text-secondary",children:new Date(V.createdAt).toLocaleDateString()}),e.jsx(ue,{tone:"neutral",children:V.mentioned===null?V.mentionUnavailableReason==="identity-ambiguous"?Et.ambiguous:"Mention not checked":V.mentioned?"Mentioned":"Not mentioned"}),e.jsx(ue,{tone:"neutral",children:V.cited===null?"Citation not checked":V.cited?"Cited":"Not cited"})]}),e.jsx("div",{className:"mt-4",children:e.jsx(Cl,{headingLevel:4,copyable:!!V.answerText?.trim(),children:V.answerText??"Answer text unavailable."})}),V.sources.length>0?e.jsxs("details",{className:"mt-2","data-answer-sources":!0,children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-3 text-sm text-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",children:[th," (",V.sources.length,")"]}),e.jsx("ul",{className:"space-y-2 pb-3",children:V.sources.map(B=>{const E=_s(B);return e.jsx("li",{className:"break-all text-sm",children:E?e.jsx("a",{href:E,target:"_blank",rel:"noopener noreferrer",className:"text-link underline",children:B}):e.jsx("span",{className:"text-secondary",children:B})},B)})})]}):null]},V.answerId)),O(C).items.length===0?e.jsx("p",{className:"py-4 text-sm text-secondary",children:O(C).nextCursor?"No matching answers on this page. Continue to the next answers.":"No matching saved answers on this page."}):null,O(C).nextCursor&&p?e.jsx(P,{variant:"outline",onClick:()=>p(O(C).nextCursor),children:"Next answers"}):null]})]}):null]})]}),e.jsxs("details",{className:"border-t border-default","aria-label":`${Ts[C.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:C.competitorAvailability.state==="unavailable"?"Not available":`${C.competitors.length} measured`})]}),e.jsxs("div",{className:"pb-5",children:[C.competitorAvailability.state==="unavailable"?e.jsx("p",{className:"text-sm text-secondary",children:"Competitor rates unavailable for this historical definition."}):C.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:C.competitors.map(V=>e.jsxs("tr",{children:[e.jsx("td",{children:V.domain}),e.jsx("td",{children:e.jsx(Cs,{value:V.mentionCoverage})}),e.jsx("td",{children:e.jsx(Cs,{value:V.citationCoverage})})]},V.domain))})]})}),C.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:C.observedCompetitors.map(V=>e.jsxs("li",{className:"flex items-center justify-between gap-4 py-3",children:[e.jsx("span",{children:V.name}),e.jsxs("span",{className:"tabular-nums text-secondary",children:[V.answerCount," ",V.answerCount===1?"answer":"answers"]})]},V.name))}),e.jsx("p",{className:"py-2 text-secondary",children:"Observed names, not additions to your tracked competitors."})]}):null]})]})]},C.queryClass)})]})}function wp({population:t,scope:s,scopeOptions:n,marketKey:a,onSelectionChange:r}){const o=new Map(n.filter(u=>u.kind==="group").map(u=>[u.id,u])),i=[...o.values()].some(u=>u.parentGroupIds?.length),c=t.breakdown.groups.filter(u=>{const b=o.get(u.id)?.parentGroupIds??[];return s.kind==="project"?b.length===0:s.kind==="group"&&i?b.includes(s.id):!0}),[d,h]=l.useState(()=>s.kind==="project"&&c.length>0?"groups":"properties"),m=fn({rows:d==="groups"?c:t.breakdown.properties,getSearchText:u=>u.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(u=>e.jsx(P,{variant:d===u?"secondary":"ghost",onClick:()=>{h(u),m.setPage(1)},children:u==="groups"?"Groups":"Properties"},u))}),e.jsx("input",{type:"search","aria-label":"Search breakdown",placeholder:"Search",value:m.query,onChange:u=>m.setQuery(u.target.value),className:`${In} 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:d==="groups"?"Group":"Property"}),e.jsx("th",{children:"Queries"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"})]})}),e.jsx("tbody",{children:m.rows.map(u=>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:()=>r({measurementScope:d==="groups"?"group":"property",measurementScopeKey:u.id,measurementMarketKey:a}),children:u.label})}),e.jsx("td",{children:u.queryCount}),e.jsx("td",{children:e.jsx(Cs,{value:u.mentionCoverage})}),e.jsx("td",{children:e.jsx(Cs,{value:u.citationCoverage})})]},u.id))})]})}),m.rows.length===0?e.jsxs("p",{className:"py-3 text-sm text-secondary",children:["No ",d," match this search."]}):null,e.jsx(Ls,{page:m.page,pageSize:m.pageSize,visibleRows:m.rows.length,totalRows:m.totalRows,itemLabel:d,onPageChange:m.setPage})]})}function Sp({projectName:t,selection:s,onSelectionChange:n,onManageQueries:a,fallback:r,showUnmeasuredFallback:o=!1}){const[i,c]=l.useState(),[d,h]=l.useState(""),[m,u]=l.useState(),b=ms(),p=l.useMemo(()=>({scope:s.measurementScope,scopeKey:s.measurementScopeKey,marketKey:s.marketKey,queryClass:s.queryClass,provider:s.provider,model:s.model,location:s.location,from:s.from,to:s.to,revision:s.revision,runId:s.measurementRunId}),[s.measurementScope,s.measurementScopeKey,s.marketKey,s.queryClass,s.provider,s.model,s.location,s.from,s.to,s.revision,s.measurementRunId]),x=Te({...tr({client:Y,path:{name:t},query:{...p,limit:25,cursor:i,search:d||void 0}}),staleTime:hd,retry:!1,placeholderData:ni}),g={...p,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??x.data?.selection.run.id??s.measurementRunId,revision:s.answer?.revision??x.data?.selection.revision??s.revision,limit:50},f=JSON.stringify(g),S=Te({...tr({client:Y,path:{name:t},query:{...g,cursor:m?.selection===f?m.cursor:void 0}}),enabled:!!s.queryKey&&!!x.data&&!x.isPlaceholderData,retry:!1});if(l.useEffect(()=>{if(s.queryClass!=="all"||!x.data||x.isPlaceholderData||x.isFetching||x.isError||x.data.selection.availability.state==="unsupported"||x.data.populations.length===0||s.queryKey&&!s.answer&&!Hr(x.data,s.queryKey)&&!S.data)return;const j=li(x.data,s.queryKey,s.answer,S.data);if(!i&&!d){const{queryKey:D}=tr({client:Y,path:{name:t},query:{...p,queryClass:j.queryClass,limit:25}});b.setQueryData(D,{...x.data,selection:{...x.data.selection,queryClass:j.queryClass},populations:[j]},{updatedAt:x.dataUpdatedAt})}n({queryClass:j.queryClass,...s.queryKey?{measurementQueryKey:s.queryKey,measurementAnswer:s.answer?JSON.stringify(s.answer):void 0}:{}})},[s.queryClass,s.queryKey,s.answer,x.data,x.dataUpdatedAt,x.isPlaceholderData,x.isFetching,x.isError,S.data,n,b,t,p,i,d]),x.data?.selection.availability.state==="unsupported")return e.jsx(e.Fragment,{children:r});if(o&&x.data?.selection.mode==="simple"&&x.data.selection.measurement.state==="not-measured")return e.jsx(e.Fragment,{children:r});if(x.error){const j=ea(x.error),D=s.measurementScope!=="project"&&j.includes("scope")&&j.includes("is not in this frozen definition.");return 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:D?"This saved group or property filter is unavailable for this measurement. Show the whole site to choose another.":j}),D?e.jsx(P,{variant:"outline",onClick:()=>{c(void 0),n({measurementScope:"project",measurementScopeKey:void 0})},children:"Show whole site"}):e.jsx(P,{variant:"outline",onClick:()=>{c(void 0),x.refetch()},children:"Retry"})]})}return x.data?e.jsx("div",{"aria-busy":x.isFetching,children:e.jsx(Np,{report:x.data,isRefreshing:x.isFetching,queryKey:s.queryKey,answerSelection:s.answer,evidenceReport:S.data,isEvidenceLoading:S.isFetching||!!s.queryKey&&S.isPending,evidenceError:S.error?ea(S.error):void 0,onRetryEvidence:()=>{S.refetch()},onEvidencePage:S.isFetching?void 0:j=>u({selection:f,cursor:j}),search:d,onSearch:j=>{h(j),c(void 0)},onPage:x.isFetching?void 0:c,onSelectionChange:j=>{(!("measurementQueryKey"in j)||Object.keys(j).some(D=>D!=="measurementQueryKey"&&D!=="measurementAnswer"))&&c(void 0),u(void 0),n(j)},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 Cp=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],kp=[{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."}],ci=rt[2],Ap="var(--chart-tooltip-bg)",Pp={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",local:"Local"};function ks(t){const s=En(t);return Pp[s]??t.charAt(0).toUpperCase()+t.slice(1)}function Vs(t){return Math.round(t*10)/10}function Rp(t){return t===ia||t===oa||t===cs}function Vl(t){return t===ia?"Cited":t===oa?"Mentioned":t===cs?"Mention share":ks(t)}function Wn(t,s){return t===ia?qs.positive:t===oa?rt[1]:t===cs?ci:Wm(En(t),s)}function Ip(t,s){for(const n of t){const a=n[s];if(typeof a=="number"&&Number.isFinite(a))return a}return null}function Tp(t){return t.map(s=>s.trim().toLowerCase()).filter(Boolean).sort().join(`
1
+ import{j as e,r as l,u as Te,L as As,h as ms,o as Tt,B as ni,C as Zo,D as xc,k as pc,l as gc}from"./vendor-tanstack-ZXXkndVj.js";import{T as ue,t as fc,a as yc,M as el,I as Ve,s as tl,B as P,b as bc,u as sl,C as vc,P as Ln,h as jc,c as Nc,d as mn,g as nl,e as al,f as ye,i as Y,j as ie,k as Nt,l as Ye,m as wc,n as Sc,o as Cc,p as rl,q as kc,r as Ac,v as bn,S as hn,w as Pc,x as Rc,y as _s,z as Ht,A as Ic,D as Si,E as il,G as Ut,F as ai,H as Tc,J as $c,K as Mc,L as Lc,N as Ci,O as $e,Q as qc,R as Ec,U as er,V as Dc,W as Oc,X as Fc,Y as Kc,Z as Gc,_ as _c,$ as Uc,a0 as Bc,a1 as Vc,a2 as Qc,a3 as zc,a4 as Wc,a5 as Hc,a6 as Yc,a7 as Jc,a8 as ol,a9 as Ys,aa as Xc,ab as ll,ac as Oa,ad as Zc,ae as Je,af as ed,ag as td,ah as sd,ai as Fa,aj as nd,ak as ad,al as rd,am as pn,an as id,ao as od,ap as ld,aq as cl,ar as Fr,as as cd,at as ri,au as dd,av as ea,aw as Js,ax as Bt,ay as ud,az as md,aA as hd,aB as tr,aC as Et,aD as xd,aE as pd,aF as gd,aG as fd,aH as yd,aI as Xn,aJ as ki,aK as ya,aL as sr,aM as bd,aN as vd,aO as Ai,aP as nr,aQ as xn,aR as jd,aS as dl,aT as ul,aU as Nd,aV as wd,aW as Pi,aX as Sd,aY as Cd,aZ as kd,a_ as Ad,a$ as Pd,b0 as Rd,b1 as Id,b2 as Td,b3 as $d,b4 as Md,b5 as Ld,b6 as qd,b7 as Ed,b8 as Dd,b9 as Od,ba as Fd,bb as Kd,bc as Gd,bd as _d,be as Ud,bf as Bd,bg as Vd,bh as Qd,bi as zd,bj as Wd,bk as Hd,bl as Yd,bm as Jd,bn as Ns,bo as Xd,bp as xt,bq as Zd,br as eu,bs as tu,bt as su,bu as nu,bv as au,bw as ru,bx as iu,by as ou,bz as lu,bA as cu,bB as du,bC as uu,bD as mu,bE as hu,bF as xu,bG as pu,bH as gu,bI as fu,bJ as yu,bK as bu,bL as vu,bM as ju,bN as Ri,bO as Ii,bP as Ti,bQ as Nu,bR as wu,bS as Su,bT as Cu,bU as ku,bV as Au,bW as Pu,bX as Ru,bY as Iu,bZ as Tu,b_ as $u,b$ as Mu,c0 as Lu,c1 as qu,c2 as Eu,c3 as Du,c4 as Ou,c5 as Fu,c6 as Ku,c7 as Gu,c8 as ml,c9 as ar,ca as _u,cb as $i,cc as Uu,cd as Bu,ce as Vu,cf as Qu,cg as zu,ch as Wu,ci as Hu,cj as hl,ck as Yu,cl as xl,cm as pl,cn as gl,co as fl,cp as Ju,cq as Xu,cr as Zu,cs as em,ct as tm,cu as sm,cv as Mi,cw as nm,cx as am,cy as rm,cz as im,cA as om,cB as Li,cC as lm,cD as cm,cE as dm,cF as um,cG as mm,cH as hm,cI as Ka,cJ as xm,cK as rr,cL as pm,cM as gm,cN as fm,cO as ym,cP as bm,cQ as vm,cR as jm,cS as Nm,cT as wm,cU as Sm,cV as yl,cW as Cm,cX as km,cY as Am,cZ as Pm,c_ as Rm,c$ as Im,d0 as ba,d1 as Tm,d2 as $m,d3 as Mm,d4 as qi,d5 as Lm}from"./index-DQGEzxrN.js";import{C as gn,e as Ga,q as ta,U as qm,r as Em,L as Dm,s as Om,i as Fm,P as _a,D as bl,t as Km,u as vl,v as Gm,d as _m,E as Um,p as Bm,w as Vm,x as jl}from"./vendor-lucide-CW2qe0uH.js";import{R as Qm}from"./RunRow-2cNW8FHz.js";import{u as fn,D as zs,a as Ls,b as Nl,M as qa,c as Rs,S as zm}from"./SiteHealthSection-C0aJ_UhN.js";import{C as sa,f as yn,a as ds,b as Ft,c as Vt,d as ts,e as rt,g as us,h as qs,M as wl,i as Sl,o as Es,j as Ws,p as Wm}from"./ChartPrimitives-Bxa_vFmq.js";import{u as Hm,a as Ym,b as Jm,t as Xm,e as Zm,c as ft}from"./extract-error-message-BzB8j3fC.js";import{R as Xs,C as Zs,a as na,X as en,Y as tn,T as sn,b as Kr,L as Ua,A as Bs,d as Ms,e as eh}from"./vendor-recharts-D-cUuLZo.js";import{A as Cl,a as th,b as sh,c as nh}from"./v2-overview-adapter-CWWPfsm-.js";import{A as ah}from"./AuditHistoryPanel-Dc_pymFg.js";import"./vendor-radix-twS1M3FF.js";import"./vendor-markdown-B-Oq2NYq.js";import"./vendor-yaml-GWJz5H2G.js";function Hs(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 rh(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=ih(r,1));return a}function ih(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 oh(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 lh(t,s){const n=oh(t,s);return n===null?null:Math.round(n*100)}function ir(t,s,n="vs prior 7 days"){return t.deltaPct===null?t.prior===0?"First baseline week":"":t.deltaPct>0?`Up ${t.deltaPct}% ${n} (${Hs(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${Hs(t.prior)} ${s})`:`Flat ${n} (${Hs(t.prior)} ${s})`}const kl=30;function Ei(t){return Math.round(t*10)/10}function ch(t){return t.prior>=kl&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% vs prior`:`${t.deltaAbs>0?"+":""}${Ei(t.deltaAbs)} vs ${Ei(t.prior)}`}function dh(t,s,n){return t.prior>=kl&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% ${n}`:`${t.deltaAbs>0?"+":""}${Hs(Math.round(t.deltaAbs))} ${s} ${n}`}function uh(t,s="UTC"){const n=new Date(t);if(!Number.isFinite(n.getTime()))return null;const a={weekday:"short",year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"};try{return n.toLocaleString("en-US",{...a,timeZone:s})}catch{return n.toLocaleString("en-US",{...a,timeZone:"UTC"})}}const mh=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function Al(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function Pl(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 Rl(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(Al).map(Pl).filter(Boolean)):new Set}function Il(t,s){const n=Al(t).map(Pl).filter(Boolean).filter(a=>!mh.has(a)).filter(a=>!s.has(a));return[...new Set(n)].sort().join(" ")}function hh(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function xh(t,s){const n=Rl(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=Il(hh(o),n);!i||a.has(i)||(a.add(i),r.push(o))}return r}function ph(t){const s=Rl(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const a=new Set;return n.filter(r=>{const o=Il(r.query,s);return!o||a.has(o)?!1:(a.add(o),!0)})}const gh=1e6;function fh(t,s="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:s}).format(t/gh)}const ii={queryClass:"all"},yh=["all","non-brand","branded"];function Tl(t){return typeof t=="string"&&yh.includes(t)}function $l(t){const s=Tl(t.class)?t.class:ii.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 bh(t,s){return s===null||t===null?!1:t!==s}function vh(t){return{scope:t.scope==="group"&&t.groupKey?`group:${t.groupKey}`:void 0,class:t.queryClass===ii.queryClass?void 0:t.queryClass}}function jh(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 Nh(t){const s=h=>typeof t[h]=="string"&&t[h]!==""?t[h]:void 0,n=$l({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==="unknown"||Tl(o)?o:ii.queryClass};i.measurementScope!=="project"&&(i.measurementScopeKey=r);for(const[h,m]of[["measurementMarketKey","marketKey"],["measurementProvider","provider"],["measurementModel","model"],["measurementLocation","location"],["measurementFrom","from"],["measurementTo","to"],["measurementRunId","measurementRunId"],["measurementQueryKey","queryKey"]]){const u=s(h);u!==void 0&&(i[m]=u)}const c=Number(t.measurementRevision);Number.isSafeInteger(c)&&c>0&&(i.revision=c);const d=jh(t.measurementAnswer,i.queryKey);return d&&(i.answer=d),i}function wh(t,s){const n={...t,...s};return["measurementScope","measurementScopeKey","measurementMarketKey","queryClass","measurementProvider","measurementModel","measurementLocation","measurementFrom","measurementTo","measurementRevision","measurementRunId"].some(a=>a in s)?(n.measurementQueryKey=s.measurementQueryKey,n.measurementAnswer=s.measurementAnswer):"measurementQueryKey"in s&&!("measurementAnswer"in s)&&(n.measurementAnswer=void 0),"measurementScope"in s&&(n.scope=void 0,"measurementMarketKey"in s||(n.measurementMarketKey=void 0),n.measurementQueryKey=void 0,s.measurementScope==="project"&&(n.measurementScopeKey=void 0)),"queryClass"in s&&(n.class=void 0),n}function Gr({state:t,label:s}){return e.jsx(ue,{tone:yc(t),children:s??fc(t)})}const an=[{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],Di={"non-brand":"Non-brand",branded:"Branded",pooled:"All queries"},Sh={"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."},Ch="Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other.";function kh(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 Ah({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(Ve,{text:Ch})]}),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 Ph({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,d=c?a:"non-brand",h=i?"pooled":d,m=d==="branded"?t.branded:t.breakdown,u=d==="branded"?t.breakdown:t.branded,b=kh(m,{hasCompetitors:n.length>0,unavailable:t.unavailable===!0,noRun:t.breakdown.snapshotsTotal===0&&t.branded.snapshotsTotal===0,otherClassHasData:u.snapshotsTotal>0}),p=h==="non-brand"?el[t.tone]:"text-secondary";function x(g){const f=an.findIndex(j=>j.value===d);let S=null;g.key==="ArrowRight"||g.key==="ArrowDown"?S=(f+1)%an.length:g.key==="ArrowLeft"||g.key==="ArrowUp"?S=(f-1+an.length)%an.length:g.key==="Home"?S=0:g.key==="End"&&(S=an.length-1),S!==null&&(g.preventDefault(),r(an[S].value),g.currentTarget.querySelectorAll('[role="radio"]')[S]?.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(Ve,{text:Sh[h]})]}),c?e.jsx("div",{role:"radiogroup","aria-labelledby":o,className:"segmented flex-wrap",onKeyDown:x,children:an.map(g=>{const f=g.value===d;return e.jsx("button",{type:"button",role:"radio","aria-checked":f,tabIndex:f?0:-1,onClick:()=>r(g.value),className:`segmented-option min-h-11 ${f?"segmented-option-active":""}`,children:g.label},g.value)})}):e.jsx("span",{className:"mention-share-class",children:Di[h]})]}),b.numeric?e.jsxs("p",{className:`mention-share-value ${p}`,children:[b.headline,e.jsx("span",{className:"text-faint",children:"%"})]}):e.jsx("p",{className:"mention-share-value-text",children:b.headline}),e.jsxs("p",{className:"mention-share-caption",children:[e.jsx("span",{className:"mention-share-caption-scope",children:Di[h]}),` · ${b.detail}`]}),i&&e.jsx("p",{className:"mention-share-note",children:"Set a brand name to split branded from non-brand."}),b.showRows&&e.jsx(Ah,{breakdown:m,projectLabel:s,competitorDomains:n})]})}const rn=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],Oi=5;function Rh(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 Ih(t){return t?t.evidence.answeredResults>0||t.evidence.sourceResults>0?"measured":"not-measured":"unavailable"}function or(t){return t==="unavailable"?"Unavailable":"Not measured"}function Ml(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 Th({value:t,onChange:s}){function n(a){const r=rn.findIndex(c=>c.value===t);let o=null;if(a.key==="ArrowRight"||a.key==="ArrowDown"?o=(r+1)%rn.length:a.key==="ArrowLeft"||a.key==="ArrowUp"?o=(r-1+rn.length)%rn.length:a.key==="Home"?o=0:a.key==="End"&&(o=rn.length-1),o===null)return;a.preventDefault();const i=rn[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:rn.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 _r({row:t,isProject:s=!1,metricState:n="measured",shareContext:a,canManage:r,onPin:o,onUnpin:i}){const c=!s&&r&&!t.pinned&&!!o,d=!s&&r&&t.pinned&&!!i,h=n==="measured",m=h&&t.sampleUrls.length>0,[u,b]=l.useState(!1),[p,x]=l.useState(null);async function g(f,S){if(!(!S||u)){b(!0),x(null);try{await S(t.domain)===!1&&x(`Could not ${f} competitor. Try again.`)}catch{x(`Could not ${f} competitor. Try again.`)}finally{b(!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":Ml(t.surfaceClass)}),e.jsx("td",{className:"tabular-nums text-strong",children:h?bc(t.shareOfVoice,a):or(n)}),e.jsx("td",{className:"tabular-nums text-secondary",children:h?t.mentionCount:or(n)}),e.jsx("td",{className:"tabular-nums text-secondary",children:h?t.citationCount:or(n)}),e.jsx("td",{className:"text-right",children:c||d||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(f=>e.jsx("li",{className:"break-all",children:f},f))})]}):null,d&&i?e.jsxs(P,{type:"button",size:"sm",variant:"outline",disabled:u,onClick:()=>{g("unpin",i)},children:["Unpin"," ",e.jsx("span",{className:"sr-only",children:t.domain})]}):null,c&&o?e.jsxs(P,{type:"button",size:"sm",variant:"outline",disabled:u,onClick:()=>{g("pin",o)},children:["Pin"," ",e.jsx("span",{className:"sr-only",children:t.domain})]}):null,p?e.jsx("span",{role:"alert",className:"sr-only",children:p}):null]}):e.jsx("span",{className:"text-faint",children:"—"})})]})}function Ur({children:t}){return e.jsx("tr",{className:"competitor-landscape-group",children:e.jsx("th",{scope:"rowgroup",colSpan:6,children:t})})}function $h({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(Ur,{children:"Observed in this window"}),i.map(c=>e.jsx(_r,{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(P,{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 Mh({onAddCompetitor:t}){const s=l.useId(),[n,a]=l.useState(""),[r,o]=l.useState(!1),[i,c]=l.useState(null);async function d(){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(),d()},"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(P,{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 Lh({window:t,landscape:s,pinnedFallback:n=[],canWrite:a,isEmbed:r,onWindowChange:o,onPin:i,onUnpin:c,onAddCompetitor:d,error:h,onRetry:m,isLoading:u=!1,scopeLabel:b}){const p=a&&!r,x=s?.pinned??n,g=s?.observed??[],f=s?.otherSources??[],S=s?.evidence,j=Ih(s),D=s?.marketState?.draft?.pendingCompetitorDomains.length??0;return e.jsxs("section",{"aria-labelledby":"competitor-landscape-title","aria-busy":u,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"}),b?e.jsx("p",{className:"supporting-copy mt-1",children:b}):null,s?e.jsx("p",{className:"supporting-copy mt-1",children:Rh(s.filters?.queryClass)}):null,s?.reason?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:tl(s.reason)}):null]}),e.jsx(Th,{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(P,{type:"button",size:"sm",variant:"outline",onClick:m,children:"Retry competitor history"}):null]}):null,u&&!s&&x.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(Ur,{children:"You"}),e.jsx(_r,{row:s.project,shareContext:s,isProject:!0,metricState:j,canManage:!1})]}):null,e.jsx(Ur,{children:"Pinned"}),x.length>0?x.map(A=>e.jsx(_r,{row:{...A,pinned:!0},shareContext:s,metricState:j,canManage:p,onUnpin:c},A.domain)):e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"text-secondary",children:"No pinned competitors."})})]}),s&&g.length>0?e.jsx($h,{shareContext:s,rows:g,canManage:p,onPin:i},JSON.stringify([t,s.project.domain,s.scope,s.filters])):null]})}),S?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:[S.answeredResults," ",S.answeredResults===1?"answer":"answers"]}),S.missingAnswerTextResults>0?e.jsx("span",{className:"text-caution",children:"Answer data incomplete"}):null,S.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(gn,{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:[g.length===0?e.jsx("p",{children:"No additional competitors were identified in this period."}):null,e.jsxs("p",{children:[S.sourceResults," ",S.sourceResults===1?"result includes":"results include"," source URLs."]}),S.missingAnswerTextResults>0?e.jsxs("p",{children:[S.missingAnswerTextResults," ",S.missingAnswerTextResults===1?"result has":"results have"," no answer text and ",S.missingAnswerTextResults===1?"is":"are"," excluded from mention share."]}):null,S.incompleteSourceResults>0?e.jsxs("p",{children:[S.incompleteSourceResults," ",S.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,S.excludedProbeResults+S.excludedNonCompletedResults>0?e.jsxs("p",{children:[S.excludedProbeResults+S.excludedNonCompletedResults," test or unfinished ",S.excludedProbeResults+S.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,D>0?e.jsx("p",{className:"text-sm text-secondary",children:s?.scope.kind==="all-markets"?`${D} competitor${D===1?" is":"s are"} pending publication across markets.`:`${D} competitor${D===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(A=>e.jsxs("li",{children:[A.name," · ",A.answerCount," answers"]},A.name))})]}):null,f.length>0?e.jsxs("details",{className:"inline-disclosure",children:[e.jsxs("summary",{children:["Other observed sources (",f.length,")"]}),e.jsx("ul",{className:"mt-3 space-y-2 text-sm text-secondary",children:f.map(A=>e.jsxs("li",{children:[e.jsxs("span",{children:[A.label," · ",Ml(A.surfaceClass)," · ",A.citationCount," citations"]}),A.sampleUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1 font-mono text-[11px] text-muted",children:A.sampleUrls.map(y=>e.jsx("li",{className:"break-all",children:y},y))}):null]},A.domain))})]}):null]}),p&&d?e.jsx(Mh,{onAddCompetitor:d}):null]})}function Fi({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"}),d=n.map((h,m)=>{const u=new Date(h.createdAt).toLocaleDateString();return`${m===o?"Latest run, ":""}${u}: ${h.citationState}${h.model?`, model ${h.model}`:""}`}).join("; ");return e.jsxs("div",{className:"flex items-center gap-1",role:"img","aria-label":`Citation history across ${n.length} runs. ${d}`,children:[e.jsx("span",{className:"text-[9px] text-faint shrink-0","aria-hidden":"true",children:i}),e.jsx("div",{className:"flex items-center gap-[3px]",title:`${n.length} runs`,"aria-hidden":"true",children:n.map((h,m)=>{const u=!!(h.model&&m>0&&n[m-1]?.model&&n[m-1].model!==h.model),b=m===o;return e.jsx("span",{className:`h-2.5 w-2.5 ${r[h.citationState]??"rounded-sm"} ${a[h.citationState]??"bg-mono-700"} ${u?"ring-1 ring-caution-300/80 ring-offset-1 ring-offset-bg":""} ${b?"outline outline-1 outline-offset-2 outline-mono-400":""}`,title:[h.citationState,new Date(h.createdAt).toLocaleDateString(),h.model?`model ${h.model}`:null,u?"model changed":null,b?"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 Br(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 qh=320;function Eh(t){return t==="branded"?"Branded":t==="non-brand"?"Non-brand":"Unclassified"}function Dh(t){return[t.phrase,t.location??"",...t.rawItems.map(s=>s.provider)].join(" ")}function Ki(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 Gi(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 _i(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 Oh(t,s){return t.map(n=>Ll(n,s))}function Ll(t,s){return s==="citations"?t:{...t,citationState:Ki(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:Ki(n,s)}))}}function Ui(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 Fh(t){const s=Br(Oh(t,"mentions")),n=Br(t);return[Ui(s,"mentions"),Ui(n,"citations")]}function Kh({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 Bi({items:t}){return e.jsx("div",{className:"mt-1 flex flex-wrap gap-1","aria-label":"Latest run mention and citation signals",children:Fh(t).map(s=>e.jsx(Kh,{signal:s},s.key))})}function Gh({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:a}=sl(),[r,o]=l.useState(new Set),[i,c]=l.useState("mentions"),[d,h]=l.useState(n),[m,u]=l.useState("all"),b=l.useMemo(()=>{const y=new Map;for(const w of t){const N=w.query,M=w.queryClass??null,L=s?w.location??null:null,F=JSON.stringify([N,M,L]),H=y.get(F)??{key:F,phrase:N,queryClass:M,location:L,items:[],rawItems:[]};H.items.push(Ll(w,i)),H.rawItems.push(w),y.set(F,H)}return[...y.values()]},[t,i,s]),p=l.useMemo(()=>b.filter(y=>m==="all"||(m==="unclassified"?y.queryClass===null:y.queryClass===m)),[b,m]),x=fn({rows:p,getSearchText:Dh}),g=x.rows.map(y=>y.key),f=g.length>0&&g.every(y=>r.has(y)),S=y=>{o(w=>{const N=new Set(w);return N.has(y)?N.delete(y):N.add(y),N})},j=i==="mentions"?"mentioned":"cited",D=i==="mentions"?"Mention History":"Citation History",A=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(y=>{const w=new Set(y);for(const N of g)f?w.delete(N):w.add(N);return w})},children:f?"Collapse page":"Expand page"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Density"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-bg-elevated/60 border border-subtle",role:"tablist","aria-label":"Evidence row density",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":d==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${d==="compact"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>h("compact"),children:"Compact"}),e.jsx("button",{type:"button",role:"tab","aria-selected":d==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${d==="detailed"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>h("detailed"),children:"Detailed"})]})]})]})]}),b.length>0?e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-3",children:[e.jsx(zs,{value:x.query,onChange:x.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:y=>{u(y.target.value),x.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:D}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:x.rows.map(({key:y,phrase:w,queryClass:N,location:M,items:L,rawItems:F})=>{const H=r.has(y),O=L.map(q=>q.citationState),J=O.includes("cited")?"cited":O.includes("emerging")?"emerging":O.includes("lost")?"lost":O.every(q=>q==="pending")?"pending":"not-cited",G=Br(L),C=L.filter(q=>q.citationState===vc.cited||q.citationState==="emerging").length,ae=_i(G,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:()=>S(y),onKeyDown:q=>{(q.key==="Enter"||q.key===" ")&&(q.preventDefault(),S(y))},tabIndex:0,role:"button","aria-expanded":H,children:[e.jsx("td",{children:e.jsx(Ga,{size:14,className:`transition-transform duration-150 text-muted ${H?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-heading",children:w}),s&&e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-muted",children:M??"No location"}),e.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[e.jsx(ue,{tone:"neutral",className:"whitespace-nowrap",children:Eh(N)}),L.map(q=>e.jsx(Ln,{provider:q.provider},q.id))]})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gr,{state:J,label:Gi(J,i)}),e.jsxs("span",{className:"text-[11px] text-muted",title:`${C} of ${L.length} engines ${A}`,children:[C,"/",L.length]})]})}),e.jsx("td",{children:e.jsx(Fi,{history:G})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:ae}),e.jsx(Bi,{items:F})]}),e.jsx("td",{})]}),H&&L.map((q,se)=>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(Ln,{provider:q.provider})}),e.jsx("td",{children:e.jsx(Gr,{state:q.citationState,label:Gi(q.citationState,i)})}),e.jsx("td",{children:e.jsx(Fi,{history:q.runHistory})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:_i(q.runHistory,i)}),e.jsx(Bi,{items:[F[se]??q]})]}),e.jsx("td",{children:e.jsx(P,{variant:"ghost",size:"sm",type:"button",onClick:V=>{V.stopPropagation(),a(q.id)},children:"View"})})]}),d==="detailed"&&e.jsxs("tr",{className:"bg-surface-subtle",children:[e.jsx("td",{}),e.jsx("td",{colSpan:5,className:"px-5 pb-4",children:e.jsx(Bh,{item:q,onViewFull:()=>a(q.id)})})]})]},q.id))]},y)})})]})}),x.totalRows===0&&(x.hasQuery||m!=="all")?e.jsx("p",{className:"supporting-copy mt-3",children:"No tracked queries match this filter."}):null,e.jsx(Ls,{page:x.page,pageSize:x.pageSize,visibleRows:x.rows.length,totalRows:x.totalRows,onPageChange:x.setPage,itemLabel:x.hasQuery||m!=="all"?"matches":"queries"}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",j==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function _h(t){const s=(t.matchedTerms??[]).filter(r=>r.trim().length>2),n=[...(t.mentionedCompetitorDomains??[]).flatMap(r=>{const o=Nc(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 Vi(t,s){const n=s.toLowerCase().replace(/^www\./,"");return(t.citedCompetitorDomains??[]).some(a=>a.toLowerCase().replace(/^www\./,"")===n)}function Uh(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 Bh({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}=Uh(t.answerSnippet,qh),o=_h(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:jc(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] ${Vi(t,i)?"border-negative-900/40 bg-negative-950/30 text-negative":"border-mono-700/60 bg-bg-elevated/60 text-neutral"}`,children:[i,Vi(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 va({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 Ha({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 lr=rt[0],cr=rt[1],Qi=rt[2],zi=rt[3],Vh=["both","server","ga4"],Wi={fontSize:11,paddingTop:6},Hi=new Set(["Pages crawled trend","Page fetches trend","Visits trend"]),Yi=t=>typeof t=="number"?Hs(Math.round(t)):String(t),rs=t=>typeof t=="number"&&Number.isFinite(t)?t:0;function dr(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 ur({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(Ve,{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 Qh(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 zh({projectName:t,sinceMinutes:s}){const[n,a]=l.useState(!0),[r,o]=l.useState(!0),[i,c]=l.useState("both"),d=Hm(t,{sinceMinutes:s,granularity:"day",limit:1}),h=Ym(t),u=Te({...nl({client:Y,path:{name:t}}),enabled:!!t,staleTime:mn}).data?.connected===!0,b=Te({...al({client:Y,path:{name:t},query:{window:s>=2160*60?"90d":s>=720*60?"30d":"7d"}}),enabled:!!t&&u,staleTime:mn}),p=l.useMemo(()=>d.data?.series?.points??[],[d.data]),x=l.useMemo(()=>{const M=b.data;return new Map((M?.days??[]).map(L=>[L.date,L.sessions]))},[b.data]),g=l.useMemo(()=>{const M=F=>F.measured!==!1;if(p.length===0||M(p[0]))return null;const L=p.findIndex(M)-1;return L<0?{from:p[0].bucket,to:p[p.length-1].bucket}:{from:p[0].bucket,to:p[L].bucket}},[p]),f=d.data?.series?.coverageStart??null,S=d.data?.series?.trends,j=l.useMemo(()=>{const M=dr(S?.crawlerContentHits,p.length),L=dr(S?.aiUserFetchHits,p.length),F=dr(S?.aiReferralLandedHits,p.length);return p.map((H,O)=>({...H,crawlerContentHits:H.measured!==!1?rs(H.crawlerContentHits):null,aiUserFetchHits:H.measured!==!1?rs(H.aiUserFetchHits):null,aiReferralLandedHits:H.measured!==!1?rs(H.aiReferralLandedHits):null,ga4Visits:x.get(H.bucket)??null,crawlTrend:M[O],fetchTrend:L[O],visitTrend:F[O]}))},[p,x,S]),D=d.data?.totals,A=D&&{crawlers:rs(D.crawlerContentHits),fetches:rs(D.aiUserFetchHits),visits:rs(D.aiReferralLandedHits)},y=l.useMemo(()=>p.reduce((M,L)=>({crawlers:M.crawlers+rs(L.crawlerContentHits),fetches:M.fetches+rs(L.aiUserFetchHits),visits:M.visits+rs(L.aiReferralLandedHits)}),{crawlers:0,fetches:0,visits:0}),[p]),w=A??y,N=w.crawlers>0||w.fetches>0||w.visits>0;if(d.isLoading)return e.jsx(ye,{className:"surface-card p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading AI traffic history…"})});if(d.isError)return e.jsxs(ye,{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(!N){const M=h.data?.sources,L=M!==void 0&&M.length===0,F=!L&&f===null;return e.jsxs(ye,{className:"surface-card p-5",children:[e.jsx("p",{className:"text-sm text-secondary",children:L?"No server-side traffic source connected yet.":F?"No AI activity recorded yet.":"No AI activity recorded in this period."}),e.jsx("p",{className:"text-xs text-muted mt-1",children:L?"Connect a traffic source to see how AI engines read this site over time.":F?"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(ye,{className:"surface-card p-5",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3 mb-5",children:[e.jsx(ur,{label:"AI crawlers",value:Hs(w.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(ur,{label:"AI page fetches",value:Hs(w.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(ur,{label:"AI visitors",value:Hs(w.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."})]}),p.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:rs(p[p.length-1].crawlerContentHits).toLocaleString()}),"pages crawled"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:rs(p[p.length-1].aiUserFetchHits).toLocaleString()}),"page fetches"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:rs(p[p.length-1].aiReferralLandedHits).toLocaleString()}),"visits, server"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:x.get(p[p.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(Ve,{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:M=>a(M.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:M=>o(M.target.checked),className:"accent-current"}),"Trend line"]})]})]}),e.jsx(Xs,{width:"100%",height:206,children:e.jsxs(Zs,{data:j,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(na,{stroke:sa,vertical:!1}),e.jsx(en,{dataKey:"bucket",tick:Ft,stroke:ds,tickFormatter:yn,minTickGap:28}),e.jsx(tn,{tick:Ft,stroke:ds,width:48,allowDecimals:!1}),e.jsx(sn,{contentStyle:ts.contentStyle,labelStyle:ts.labelStyle,itemStyle:ts.itemStyle,labelFormatter:Vt,formatter:Yi}),g&&e.jsx(Kr,{x1:g.from,x2:g.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(Ua,{wrapperStyle:Wi,iconType:"plainline",iconSize:14,formatter:M=>Hi.has(M)?"":M}),e.jsx(Bs,{type:"monotone",dataKey:"crawlerContentHits",name:"Pages crawled",stroke:lr,fill:lr,fillOpacity:.22,strokeWidth:1.8}),n&&e.jsx(Bs,{type:"monotone",dataKey:"aiUserFetchHits",name:"Page fetches",stroke:cr,fill:cr,fillOpacity:.18,strokeWidth:1.6}),r&&e.jsx(Ms,{type:"linear",dataKey:"crawlTrend",name:"Pages crawled trend",dot:!1,tooltipType:"none",stroke:lr,strokeWidth:1.4,strokeDasharray:"5 4",connectNulls:!0}),r&&n&&e.jsx(Ms,{type:"linear",dataKey:"fetchTrend",name:"Page fetches trend",dot:!1,tooltipType:"none",stroke:cr,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(Ve,{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(Ha,{windows:Vh,value:i,onChange:c,label:"Visit measurement source",formatOption:M=>M==="ga4"?"GA4":M==="both"?"Both":"Server"})]}),e.jsx(Xs,{width:"100%",height:176,children:e.jsxs(Zs,{data:j,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(na,{stroke:sa,vertical:!1}),e.jsx(en,{dataKey:"bucket",tick:Ft,stroke:ds,tickFormatter:yn,minTickGap:28}),e.jsx(tn,{tick:Ft,stroke:ds,width:48,allowDecimals:!1}),e.jsx(sn,{contentStyle:ts.contentStyle,labelStyle:ts.labelStyle,itemStyle:ts.itemStyle,labelFormatter:Vt,formatter:Yi}),g&&e.jsx(Kr,{x1:g.from,x2:g.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(Ua,{wrapperStyle:Wi,iconType:"plainline",iconSize:14,formatter:M=>Hi.has(M)?"":M}),i!=="ga4"&&e.jsx(Ms,{type:"monotone",dataKey:"aiReferralLandedHits",name:"Visits, server",stroke:Qi,strokeWidth:2,dot:!1}),i!=="server"&&e.jsx(Ms,{type:"monotone",dataKey:"ga4Visits",name:"Visits, GA4",connectNulls:!1,stroke:zi,strokeWidth:1.8,strokeDasharray:"5 3",dot:Qh(j.map(M=>M.ga4Visits),zi)}),r&&i!=="ga4"&&e.jsx(Ms,{type:"linear",dataKey:"visitTrend",name:"Visits trend",dot:!1,tooltipType:"none",stroke:Qi,strokeWidth:1.3,strokeDasharray:"5 4",connectNulls:!0})]})})]})}const Wh=6,qn="__other__",$n="_socialTotal";function Hh(t,s=Wh){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,u)=>u[1]!==m[1]?u[1]-m[1]:m[0].localeCompare(u[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 u=c.get(m.date);u||(u={date:m.date,[$n]:0},c.set(m.date,u));const b=o.has(m.source)?m.source:qn;u[b]=(u[b]??0)+m.sessions,u[$n]=(u[$n]??0)+m.sessions}const d=[...c.values()].sort((m,u)=>String(m.date).localeCompare(String(u.date))),h=r.map(([m])=>m);return i>0&&h.push(qn),{data:d,sources:h,otherCount:i}}function Mn(t){return t.replace(/\+/g," ")}function ql(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const Ji="_totalSessions",Xi="_organicSessions";function Yh(t,s){const n=new Map;for(const i of s)n.set(i.date,{[Ji]:i.sessions,[Xi]:i.organicSessions});for(const i of t.days){let c=n.get(i.date);c||(c={[Ji]:0,[Xi]:0},n.set(i.date,c));for(const d of i.bySource)c[d.source]=(c[d.source]??0)+d.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 Jh=["7d","30d","90d"],Xh={"7d":10080,"30d":720*60,"90d":2160*60,all:2160*60},Us=rt,Vr=us.textDim,El=us.textFaint,_n=25;function Zh(t){return Nl(t.landingPage)}const ex=25,tx=10,mr={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0};function ja(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function Dl(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({projectName:t}){const{data:s,isLoading:n,isError:a}=Jm(t);if(n)return e.jsx(ye,{className:"p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading server activity…"})});if(a)return e.jsx(ye,{className:"p-5",children:e.jsx("div",{className:"text-sm text-negative-400",children:"Failed to load server activity."})});const 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."," ",!ie()&&e.jsx(As,{to:"/traffic",className:"text-link hover:underline",children:"Manage sources →"})]})]})}),r.length===0?e.jsx(ye,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-secondary",children:["No server traffic source connected yet."," ",!ie()&&e.jsxs(e.Fragment,{children:[e.jsx(As,{to:"/traffic",className:"text-link hover:underline",children:"Connect a traffic source"})," ","to surface bot crawls and AI referrals straight from server logs."]})]})}):e.jsx(ye,{className:"overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-bg-elevated/50 text-[10px] uppercase tracking-wide text-muted",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Source"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Status"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Crawler hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI sessions 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Last sync"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium","aria-label":"open"})]})}),e.jsx("tbody",{children: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(ue,{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?Dl(o.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:ie()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(As,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:o.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},o.id))})]})})]})}function nx({projectName:t}){const[s,n]=l.useState("30d");return e.jsxs("div",{className:"space-y-10",children:[e.jsx(sx,{projectName:t}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(Ha,{windows:Jh,value:s,onChange:n,label:"Traffic time period"})}),e.jsx(ax,{projectName:t,window:s}),e.jsx(zh,{projectName:t,sinceMinutes:Xh[s]})]})}function ax({projectName:t,window:s}){const n=ms(),a=s??"30d",[r,o]=l.useState(null),[i,c]=l.useState(null),[d,h]=l.useState(!0),[m,u]=l.useState(!1),[b,p]=l.useState(!1),[x,g]=l.useState(null),[f,S]=l.useState(null),[j,D]=l.useState("sessions"),[A,y]=l.useState("desc"),[w,N]=l.useState("sessions"),[M,L]=l.useState("desc"),[F,H]=l.useState("sessions"),[O,J]=l.useState("desc"),[G,C]=l.useState("sessions"),[ae,q]=l.useState("desc"),[se,V]=l.useState(mr),[B,E]=l.useState([]),[R,oe]=l.useState([]),[T,ee]=l.useState(!1);async function Z(te){h(!0),g(null);try{const qe=await n.fetchQuery({...nl({client:Y,path:{name:t}}),staleTime:mn});if(te.current)return;if(o(qe),!qe.connected){c(null),V(mr),E([]),oe([]),h(!1);return}const Ce=a==="all"?void 0:a,Pe=await n.fetchQuery({...wc({client:Y,path:{name:t},query:Ce?{window:Ce}:void 0}),staleTime:mn}).then(mt=>mt),Yt=Pe.windowStart||Pe.windowEnd?{...Pe.windowStart?{startDate:Pe.windowStart}:{},...Pe.windowEnd?{endDate:Pe.windowEnd}:{}}:void 0,[Jt,yt,St]=await Promise.all([n.fetchQuery({...al({client:Y,path:{name:t},query:Ce?{window:Ce}:void 0}),staleTime:mn}).catch(()=>mr),n.fetchQuery({...Sc({client:Y,path:{name:t},query:Ce?{window:Ce}:void 0}),staleTime:mn}).catch(()=>[]),n.fetchQuery({...Cc({client:Y,path:{name:t},query:Yt}),staleTime:mn}).catch(()=>[])]);if(te.current)return;c(Pe),V(Jt),E(yt),oe(St),h(!1)}catch(qe){if(te.current)return;g(qe instanceof Error?qe.message:"Failed to load GA4 data"),h(!1)}}l.useEffect(()=>{const te={current:!1};return Z(te),()=>{te.current=!0}},[t,a,n]);async function ge(){u(!0),g(null),S(null);try{const te=await rl(t);S(`Synced ${te.rowCount.toLocaleString()} page rows, ${te.aiReferralCount.toLocaleString()} AI and ${te.socialReferralCount.toLocaleString()} social referral rows (${te.days} days)`),await Nt(n,"ga"),await Z({current:!1})}catch(te){g(te instanceof Error?te.message:"Sync failed")}finally{u(!1)}}async function X(){p(!0),g(null),S(null);try{await kc(t),await Nt(n,"ga"),o({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),c(null),S("GA4 disconnected")}catch(te){g(te instanceof Error?te.message:"Disconnect failed")}finally{p(!1)}}function de(te){re.setPage(1),j===te?y(qe=>qe==="desc"?"asc":"desc"):(D(te),y("desc"))}function xe(te){w===te?L(qe=>qe==="desc"?"asc":"desc"):(N(te),L("desc"))}function ne(te){F===te?J(qe=>qe==="desc"?"asc":"desc"):(H(te),J("desc"))}const Q=l.useMemo(()=>i?.topPages?[...i.topPages].sort((te,qe)=>{const Ce=te[j],Pe=qe[j];return typeof Ce=="string"&&typeof Pe=="string"?A==="asc"?Ce.localeCompare(Pe):Pe.localeCompare(Ce):A==="asc"?Ce-Pe:Pe-Ce}):[],[i?.topPages,j,A]),re=fn({rows:Q,getSearchText:te=>Nl(te.landingPage),pageSize:tx}),Ee=l.useMemo(()=>i?.aiReferrals?[...i.aiReferrals].sort((te,qe)=>{const Ce=te[w],Pe=qe[w];return typeof Ce=="string"&&typeof Pe=="string"?M==="asc"?Ce.localeCompare(Pe):Pe.localeCompare(Ce):M==="asc"?Ce-Pe:Pe-Ce}):[],[i?.aiReferrals,w,M]),we=l.useMemo(()=>i?.aiReferralLandingPages?[...i.aiReferralLandingPages].sort((te,qe)=>{const Ce=te[G],Pe=qe[G];return typeof Ce=="string"&&typeof Pe=="string"?ae==="asc"?Ce.localeCompare(Pe):Pe.localeCompare(Ce):ae==="asc"?Ce-Pe:Pe-Ce}):[],[i?.aiReferralLandingPages,G,ae]),Se=fn({rows:we,getSearchText:Zh,pageSize:ex}),et=Se.totalRows>0?`${Se.totalRows.toLocaleString()} ${Se.hasQuery?Se.totalRows===1?"match":"matches":Se.totalRows===1?"row":"rows"}`:Se.hasQuery&&(i?.aiReferralLandingPages.length??0)>0?"0 matches":"No landing-page rows";function Ke(te){Se.setPage(1),G===te?q(qe=>qe==="desc"?"asc":"desc"):(C(te),q("desc"))}const Qe=l.useMemo(()=>i?.socialReferrals?[...i.socialReferrals].sort((te,qe)=>{const Ce=te[F],Pe=qe[F];return typeof Ce=="string"&&typeof Pe=="string"?O==="asc"?Ce.localeCompare(Pe):Pe.localeCompare(Ce):O==="asc"?Ce-Pe:Pe-Ce}):[],[i?.socialReferrals,F,O]),{socialChartData:We,socialChartSources:Ge,socialOtherCount:_}=l.useMemo(()=>{const te=Hh(R);return{socialChartData:te.data,socialChartSources:te.sources,socialOtherCount:te.otherCount}},[R]),{chartData:U,chartSources:W,dateRange:Re}=l.useMemo(()=>{const te=Yh(se,B);return{chartData:te.data,chartSources:te.sources,dateRange:te.dateRange}},[se,B]);if(d&&!r)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!r?.connected)return ie()?e.jsx(ye,{className:"p-5",children:e.jsx("div",{className:"text-sm text-secondary",children:"No Google Analytics 4 property connected yet."})}):e.jsx(rx,{projectName:t,onConnected:()=>{(async()=>(await Nt(n,"ga"),await Z({current:!1})))()}});const _e=i?.organicSharePctDisplay??"0%",Ue=i?.channelBreakdown?.organic.sharePctDisplay??_e,le=i?.channelBreakdown?.organic.sessions??i?.totalOrganicSessions??0,pt=i?.aiSessionsDeduped??0,ut=i?.channelBreakdown?.ai.sessions??i?.aiSessionsBySession??0,ze=i?.channelBreakdown?.ai.sharePctDisplay??i?.aiSharePctBySessionDisplay??"0%",Fe=i?.paidAiSessionsBySession??0,wt=i?.paidAiSharePctBySessionDisplay??"0%",Be=i?new Set(i.aiReferrals.map(te=>te.source.toLowerCase())).size:0,Me=Ee[0]??null,tt=i?.totalDirectSessions??0,$t=i?.directSharePctDisplay??"0%",Mt=i?.channelBreakdown?.direct.sessions??tt,De=i?.channelBreakdown?.direct.sharePctDisplay??$t,k=i?.channelBreakdown?.other.sessions??i?.otherSessions??0,Ae=i?.channelBreakdown?.other.sharePctDisplay??i?.otherSharePctDisplay??"0%",ve=i?.socialSessions??0,He=i?.socialSharePctDisplay??"0%",vt=i?.channelBreakdown?.social.sessions??ve,st=i?.channelBreakdown?.social.sharePctDisplay??He,Lt=i?new Set(i.socialReferrals.map(te=>te.source.toLowerCase())).size:0,Xe=Qe[0]??null;return e.jsxs(e.Fragment,{children:[x&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative",children:x}),f&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-positive-900/20 border border-positive-800/60 text-sm text-positive",children:f}),e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-positive-500"}),e.jsxs("span",{className:"text-xs text-secondary",children:["Property ",e.jsx("span",{className:"text-neutral",children:r.propertyId}),r.clientEmail&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"text-muted",children:r.clientEmail})]})]})]}),!ie()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(P,{variant:"outline",size:"sm",disabled:m,onClick:Ye(ge),children:[e.jsx(ta,{className:`w-3.5 h-3.5 mr-1.5 ${m?"animate-spin":""}`}),m?"Syncing…":"Sync"]}),e.jsxs(P,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:b,onClick:Ye(X),children:[e.jsx(qm,{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(Ve,{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(hr,{value:ja(i.totalSessions),label:"Total Sessions",subtitle:i.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(hr,{value:ja(i.totalOrganicSessions),label:"Organic Sessions",subtitle:`${_e} of total`,tone:"positive"}),e.jsx(hr,{value:i.totalUsers===null?"—":ja(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."}),!ie()&&e.jsxs(P,{variant:"outline",size:"sm",disabled:m,onClick:Ye(ge),children:[e.jsx(ta,{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(Ve,{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."})]})]}),Re&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(Re.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(Re.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),U.length>0&&e.jsxs(ye,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:W.length>0?"AI vs. total sessions":"All sessions (baseline)"}),W.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),W.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(Xs,{width:"100%",height:"100%",children:e.jsxs(Zs,{data:U,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(en,{dataKey:"date",tick:Ft,tickLine:!1,axisLine:{stroke:ds},tickFormatter:yn}),e.jsx(tn,{tick:Ft,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(sn,{...ts,labelFormatter:Vt,formatter:(te,qe)=>{const Ce=typeof te=="number"?te.toLocaleString():String(te??0),Pe=String(qe??"");return Pe==="_totalSessions"?[Ce,"Total Sessions"]:Pe==="_organicSessions"?[Ce,"Organic Sessions"]:[Ce,Pe]}}),e.jsx(Ua,{wrapperStyle:{fontSize:11,color:us.text},formatter:te=>te==="_totalSessions"?"Total Sessions":te==="_organicSessions"?"Organic Sessions":te}),e.jsx(Bs,{type:"monotone",dataKey:"_totalSessions",stroke:us.textFaint,fill:us.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),W.map((te,qe)=>e.jsx(Bs,{type:"monotone",dataKey:te,stackId:"ai",stroke:Us[qe%Us.length],fill:Us[qe%Us.length],fillOpacity:.4,strokeWidth:1.5},te))]})})})]}),e.jsxs(ye,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Summary"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Sessions by channel"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(gs,{label:"Organic",value:Ue,hint:`${le.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(gs,{label:"Social",value:st,hint:`${vt.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(gs,{label:"Direct",value:De,hint:`${Mt.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(gs,{label:"Visitors from AI (at least)",value:ze,hint:Fe>0?`${ut.toLocaleString()} sessions · ${Fe.toLocaleString()} paid`:`${ut.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(gs,{label:"Other channels",value:Ae,hint:`${k.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."})]}),Me&&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:Me.source})," via ",Me.medium,", accounting for ",Me.sessions.toLocaleString()," sessions.",Fe>0&&e.jsxs("span",{children:[" Paid AI: ",Fe.toLocaleString()," sessions (",wt,")."]})]})]}),e.jsxs(ye,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Detail"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Where AI visitors came from"})]}),e.jsx("p",{className:"text-xs text-muted",children:i.aiReferrals.length>0?`${Be} 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(is,{label:"Source",sortKey:"source",current:w,dir:M,onSort:xe,align:"left"}),e.jsx(is,{label:"Medium",sortKey:"medium",current:w,dir:M,onSort:xe,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(is,{label:"Sessions",sortKey:"sessions",current:w,dir:M,onSort:xe,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:Ee.map(te=>e.jsx(ox,{referral:te,totalSessions:pt},`${te.source}:${te.medium}:${te.sourceDimension}`))})]})}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No AI referrer sessions detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"AI engines that preserve a referrer (Perplexity, copy/paste from ChatGPT, etc.) will appear here. Most AI traffic strips the referrer — see the Direct cell above for the upper bound."})]})]}),e.jsxs(ye,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Detail"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Pages AI visitors landed on"})]}),e.jsx("p",{className:"text-xs text-muted",children:et})]}),i.aiReferralLandingPages.length>0?e.jsxs(e.Fragment,{children:[e.jsx(zs,{value:Se.query,onChange:Se.setQuery,label:"Filter landing page URLs or query parameters",placeholder:"Filter URL or query parameters",className:"mb-4 max-w-md"}),Se.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(is,{label:"Landing Page",sortKey:"landingPage",current:G,dir:ae,onSort:Ke,align:"left"}),e.jsx(is,{label:"Source",sortKey:"source",current:G,dir:ae,onSort:Ke,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(is,{label:"Sessions",sortKey:"sessions",current:G,dir:ae,onSort:Ke,align:"right"})]})}),e.jsx("tbody",{children:Se.rows.map(te=>e.jsx(lx,{row:te},`${te.landingPage}:${te.source}:${te.medium}:${te.sourceDimension}`))})]})}),e.jsx(Ls,{page:Se.page,pageSize:Se.pageSize,visibleRows:Se.rows.length,totalRows:Se.totalRows,onPageChange:Se.setPage,itemLabel:Se.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:()=>Se.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(Ve,{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(ye,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Summary"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"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(gs,{label:"Social Sessions",value:ja(ve),hint:`${ve.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(gs,{label:"Share of Traffic",value:He,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(gs,{label:"Platforms",value:String(Lt),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."})]}),Xe&&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:`${Xe.source} via ${Xe.medium}`,children:ql(Mn(Xe.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:Xe.medium,children:["via ",Mn(Xe.medium)," · ",Xe.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(gs,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(gs,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(gs,{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."})]})]})]}),We.length>0&&e.jsxs(ye,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social sessions"})]}),_>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",Ge.length-1," sources · ",_," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(Xs,{width:"100%",height:"100%",children:e.jsxs(Zs,{data:We,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(en,{dataKey:"date",tick:Ft,tickLine:!1,axisLine:{stroke:ds},tickFormatter:yn}),e.jsx(tn,{tick:Ft,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(sn,{...ts,labelFormatter:Vt,formatter:(te,qe)=>{const Ce=typeof te=="number"?te.toLocaleString():String(te??0),Pe=String(qe??"");if(Pe===$n)return[Ce,"Total Social"];if(Pe===qn){const Yt=`Other (${_} source${_===1?"":"s"})`;return[Ce,Yt]}return[Ce,Mn(Pe)]}}),e.jsx(Bs,{type:"monotone",dataKey:$n,stroke:El,fill:us.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),Ge.map((te,qe)=>{const Pe=te===qn?Vr:Us[qe%Us.length];return e.jsx(Bs,{type:"monotone",dataKey:te,stackId:"social",stroke:Pe,fill:Pe,fillOpacity:.4,strokeWidth:1.5},te)})]})})}),e.jsx(dx,{sources:Ge,otherCount:_})]}),e.jsxs(ye,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Breakdown"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social sources"})]}),e.jsx("p",{className:"text-xs text-muted",children:i.socialReferrals.length>0?Qe.length>_n&&!T?`Top ${_n} of ${Qe.length}`:`${Qe.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(is,{label:"Source",sortKey:"source",current:F,dir:O,onSort:ne,align:"left"}),e.jsx(is,{label:"Medium",sortKey:"medium",current:F,dir:O,onSort:ne,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(is,{label:"Sessions",sortKey:"sessions",current:F,dir:O,onSort:ne,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:(T?Qe:Qe.slice(0,_n)).map(te=>e.jsx(cx,{referral:te,totalSessions:ve},`${te.source}:${te.medium}:${te.channelGroup}`))})]})}),Qe.length>_n&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>ee(te=>!te),className:"rounded-md border border-base px-3 py-1.5 text-xs text-secondary transition-colors hover:border-strong hover:text-strong",children:T?`Show top ${_n}`:`Show all ${Qe.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(Ve,{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(zs,{value:re.query,onChange:re.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(is,{label:"Landing Page",sortKey:"landingPage",current:j,dir:A,onSort:de,align:"left"}),e.jsx(is,{label:"Sessions",sortKey:"sessions",current:j,dir:A,onSort:de,align:"right"}),e.jsx(is,{label:"Organic",sortKey:"organicSessions",current:j,dir:A,onSort:de,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"})]})}),e.jsx("tbody",{children:re.rows.map(te=>e.jsx(ix,{page:te},te.landingPage))})]})}),re.totalRows===0&&re.hasQuery&&e.jsx("p",{className:"text-sm text-secondary mt-3",children:"No landing pages match this filter"}),e.jsx(Ls,{page:re.page,pageSize:re.pageSize,visibleRows:re.rows.length,totalRows:re.totalRows,onPageChange:re.setPage,itemLabel:re.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 ${Dl(i.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:i?`${i.topPages.length} pages · ${i.aiReferrals.length} AI rows · ${i.socialReferrals.length} social rows`:""})]})]})}function rx({projectName:t,onConnected:s}){const[n,a]=l.useState(""),[r,o]=l.useState(null),[i,c]=l.useState(null),[d,h]=l.useState(!1),[m,u]=l.useState(null),b=l.useRef(null),p=l.useCallback(g=>{const f=g.target.files?.[0];if(!f)return;u(null),o(f.name);const S=new FileReader;S.onload=()=>{const j=S.result;try{const D=JSON.parse(j);if(!D.client_email||!D.private_key){u("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(j)}catch{u("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),c(null)}},S.onerror=()=>{u("Failed to read file."),c(null)},S.readAsText(f)},[]);async function x(){if(u(null),!n.trim()){u("Property ID is required.");return}if(!i){u("Please upload a service account key file.");return}h(!0);try{await Ac(t,{propertyId:n.trim(),keyJson:i});try{await rl(t)}catch{}s()}catch(g){u(g instanceof Error?g.message:"Failed to connect GA4")}finally{h(!1)}}return e.jsxs(ye,{className:"surface-card p-6",children:[e.jsx("h3",{className:"text-base font-semibold text-primary mb-1",children:"Connect Google Analytics 4"}),e.jsx("p",{className:"text-sm text-secondary mb-5",children:"Connect a GA4 property to see traffic data for this project. You'll need a service account key file from Google Cloud Console."}),m&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative",children:m}),e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{htmlFor:"ga4-property-id",className:"block text-xs font-medium text-secondary mb-1.5",children:"GA4 Property ID"}),e.jsx("input",{id:"ga4-property-id",type:"text",placeholder:"e.g. 123456789",value:n,onChange:g=>a(g.target.value),className:"w-full rounded-lg bg-bg-elevated/60 border border-default px-3 py-2 text-sm text-strong placeholder-mono-600 focus:outline-none focus:ring-1 focus:ring-mono-600"}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:"Find this in GA4 → Admin → Property Settings. It's a numeric ID, not the Measurement ID (G-XXXXXX)."})]}),e.jsxs("div",{className:"mb-5",children:[e.jsx("label",{className:"block text-xs font-medium text-secondary mb-1.5",children:"Service Account Key File"}),e.jsx("input",{ref:b,type:"file",accept:".json,application/json",onChange:p,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>b.current?.click(),className:"flex items-center gap-2 w-full rounded-lg bg-bg-elevated/60 border border-default border-dashed px-4 py-3 text-sm text-secondary hover:border-mono-600 hover:text-neutral transition-colors cursor-pointer",children:[e.jsx(Em,{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(P,{variant:"default",size:"sm",disabled:d||!n.trim()||!i,onClick:Ye(x),children:d?"Connecting & syncing…":"Connect GA4"})]})}function is({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 Ol={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function hr({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 ${Ol[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function gs({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(Ve,{text:r})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${Ol[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function ix({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 Fl={session:"Session",first_user:"First Visit",manual_utm:"UTM"},Kl={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 ox({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=Fl[t.sourceDimension]??t.sourceDimension,r=Kl[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 lx({row:t}){const s=Fl[t.sourceDimension]??t.sourceDimension,n=Kl[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(qa,{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 cx({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=t.channelGroup==="Paid Social"?"Paid":"Organic",r=Mn(t.source),o=Mn(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 dx({sources:t,otherCount:s}){const n=[{key:$n,color:El,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const r=t[a];if(r===qn)n.push({key:qn,color:Vr,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const o=Mn(r);n.push({key:r,color:Us[a%Us.length]??Vr,label:ql(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 ux(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 mx="Search Console is not connected yet. Your Canonry team can set this up.",hx=["7d","30d","90d","all"],Na=500,Zi=[{key:"clicks",label:"Clicks",color:rt[1],format:t=>t.toLocaleString()},{key:"impressions",label:"Impressions",color:rt[4],format:t=>t.toLocaleString()},{key:"ctr",label:"CTR",color:qs.caution,format:t=>`${(t*100).toFixed(1)}%`},{key:"position",label:"Avg position",color:rt[2],inverted:!0,format:t=>t.toFixed(1)}],Ks=25,xx="canonry:google-oauth-complete",px=new Intl.NumberFormat(void 0,{maximumFractionDigits:1});function gx(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 d=t.prior[s],h=t.trailing[s];return d!==null&&h!==null&&d<=0&&h>0?`new in the last ${a}d`:d===null||d<=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%":`${px.format(o)}%`;return`${(n?r<0:r>0)?"↑":"↓"} ${i} vs prior ${a}d`}function fx(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}`,d=`Tile percentages compare these ${s} ${o} (${c}) with the ${s} ${o} before them (${i}).`;return n!=="split-window"?d:`${d} 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 eo(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function to(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 so(t){return t.isPending?"Processing":Number(t.errors??0)>0?"Errors":Number(t.warnings??0)>0?"Warnings":"Success"}function yx({projectName:t,refreshNonce:s}){const n=ms(),{isAdmin:a}=bn(),[r,o]=l.useState(!1),[i,c]=l.useState([]),[d,h]=l.useState([]),[m,u]=l.useState([]),[b,p]=l.useState(null),[x,g]=l.useState([]),[f,S]=l.useState([]),[j,D]=l.useState(null),[A,y]=l.useState(""),[w,N]=l.useState(""),[M,L]=l.useState("30"),[F,H]=l.useState(!1),[O,J]=l.useState("30d"),[G,C]=l.useState(["clicks","impressions"]),[ae,q]=l.useState(!0),[se,V]=l.useState(null),[B,E]=l.useState(0),[R,oe]=l.useState({startDate:"",endDate:"",query:"",page:""}),[T,ee]=l.useState(0),[Z,ge]=l.useState(!1),[X,de]=l.useState(0),[xe,ne]=l.useState(!1),[Q,re]=l.useState(""),[Ee,we]=l.useState(!0),[Se,et]=l.useState(!1),[Ke,Qe]=l.useState(!1),[We,Ge]=l.useState(!1),[_,U]=l.useState(!1),[W,Re]=l.useState(!1),[_e,Ue]=l.useState(!1),[le,pt]=l.useState(null),[ut,ze]=l.useState(!1),[Fe,wt]=l.useState(!1),[Be,Me]=l.useState(null),[tt,$t]=l.useState(null),[Mt,De]=l.useState([]),[k,Ae]=l.useState(new Set),[ve,He]=l.useState({}),[vt,st]=l.useState(new Set),[Lt,Xe]=l.useState(""),[te,qe]=l.useState(null),[Ce,Pe]=l.useState(""),[Yt,Jt]=l.useState(!1),[yt,St]=l.useState(!1),[mt,Xt]=l.useState(!1),[Qt,ss]=l.useState(!1),[at,fs]=l.useState("indexed"),[gt,dt]=l.useState(null),Ct=!!(R.query.trim()||R.page.trim()||gt),ns=gt!==null,hs=l.useMemo(()=>{if(!gt)return m;const{key:v,dir:z}=gt;return[...m].sort((he,be)=>{const Ze=v===hn.CTR?Number.isFinite(he.ctr)?he.ctr:0:he[v],nt=v===hn.CTR?Number.isFinite(be.ctr)?be.ctr:0:be[v];return z==="asc"?Ze-nt:nt-Ze})},[m,gt]),qt=fn({rows:hs,pageSize:Rs}),Ps=xe?qt.rows:hs,zt=fn({rows:(Be??[]).filter(v=>v.path.toLowerCase().includes(Lt.trim().toLowerCase())),pageSize:Rs}),[kt,xs]=l.useState([]),[ht,Zt]=l.useState(null),[ys,ps]=l.useState(1),K=l.useMemo(()=>{if(kt.length<2)return null;const v=kt[kt.length-1],z=kt[kt.length-2];return{indexed:v.indexed-z.indexed,notIndexed:v.notIndexed-z.notIndexed}},[kt]);l.useEffect(()=>{ps(1)},[le,at,ht]);const ce=l.useMemo(()=>ht?(le?.reasonGroups??[]).find(v=>v.reason===ht):void 0,[le,ht]),Ne=l.useMemo(()=>le?at==="indexed"?le.indexed:at==="deindexed"?le.deindexed:at==="notIndexed"?ht?ce?.urls??[]:(le.reasonGroups??[]).length===0?le.notIndexed:[]:[]:[],[le,at,ht,ce]),me=Math.max(1,Math.ceil(Ne.length/Ks)),je=Math.min(Math.max(1,ys),me),Ie=(je-1)*Ks,as=l.useMemo(()=>le?.indexed.slice(Ie,Ie+Ks)??[],[le,Ie]),ot=l.useMemo(()=>le?.notIndexed.slice(Ie,Ie+Ks)??[],[le,Ie]),bs=l.useMemo(()=>le?.deindexed.slice(Ie,Ie+Ks)??[],[le,Ie]),$=l.useMemo(()=>(ce?.urls??[]).slice(Ie,Ie+Ks),[ce,Ie]),[pe,it]=l.useState(!1),[At,Oe]=l.useState(null),[Kt,Pt]=l.useState(null),[vn,Wt]=l.useState(null);function jn(v,z){const he=Zm(v),be=ux(he);be?(Pt(be),Oe(null)):(Pt(null),Oe(he.message||z))}const Rt=i.find(v=>v.connectionType==="gsc"),vs=(Rt?.scopes??[]).includes("https://www.googleapis.com/auth/webmasters"),la=Mt.length>0?Mt:(Be??[]).map(v=>v.path),Nn=la.filter(v=>Be?.some(z=>z.path===v&&z.isSitemapsIndex)).length,ca=Nn===1?"Resubmit sitemap index":Nn>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",Ja=m.length>0||x.length>0||f.length>0,Ds=Pc(),Dn=Rc();async function da(v,z=!1){if(!v){h([]),y("");return}Qe(!0);try{const{sites:he}=await n.fetchQuery({...Uc({client:Y,path:{name:t}}),staleTime:z?0:Ut});h(he),y(v.propertyId??he[0]?.siteUrl??""),Pt(null)}catch(he){h([]),jn(he,"Failed to load Search Console properties")}finally{Qe(!1)}}async function nn(v){U(!0);const z=v??T;try{const he=Ct?Na:Rs,be=Ct?0:z,Ze={limit:String(he)};R.startDate&&(Ze.startDate=R.startDate),R.endDate&&(Ze.endDate=R.endDate),R.query&&(Ze.query=R.query),R.page&&(Ze.page=R.page),be>0&&(Ze.offset=String(be)),O&&O!=="all"&&!R.startDate&&(Ze.window=O);const nt=await n.fetchQuery({...$c({client:Y,path:{name:t},query:Ze}),staleTime:Ut}),lt=nt.rows;Ct?(ge(!1),u(lt),de(lt.length),ne(!0)):(ge(be+lt.length<nt.totalMatching),u(lt),de(0),ne(!1))}catch(he){u([]),ge(!1),de(0),Oe(he instanceof Error?he.message:"Failed to load GSC performance data")}finally{U(!1)}}async function On(){try{const v={};R.startDate&&(v.startDate=R.startDate),R.endDate&&(v.endDate=R.endDate),O&&O!=="all"&&!R.startDate&&(v.window=O);const z=await n.fetchQuery({...Tc({client:Y,path:{name:t},query:v}),staleTime:Ut});p(z)}catch{p(null)}}async function wn(v=!1){Re(!0);try{const z=Q.trim()||void 0,he={limit:"20"};z&&(he.url=z);const[be,Ze]=await Promise.all([n.fetchQuery({...Gc({client:Y,path:{name:t},query:he}),staleTime:v?0:Ut}),n.fetchQuery({..._c({client:Y,path:{name:t}}),staleTime:v?0:Ut})]);g(be),S(Ze)}catch(z){g([]),S([]),Oe(z instanceof Error?z.message:"Failed to load GSC inspection history")}finally{Re(!1)}}async function ua(v=!1){ze(!0);try{const[z,he]=await Promise.all([n.fetchQuery({...qc({client:Y,path:{name:t}}),staleTime:v?0:Ut}),n.fetchQuery({...Ec({client:Y,path:{name:t}}),staleTime:v?0:Ut}).catch(()=>[])]);pt(z),xs(he)}catch(z){pt(null),xs([]),Oe(z instanceof Error?z.message:"Failed to load coverage data")}finally{ze(!1)}}async function Fn(v){it(!0),Oe(null);try{const z=await Ci(t,{urls:v}),{succeeded:he,failed:be,total:Ze}=z.summary;$e({title:"Indexing requested",detail:be===0?`${he} URL${he!==1?"s":""} submitted for indexing.`:`${he}/${Ze} submitted successfully, ${be} failed.`,tone:be===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(z){Oe(z instanceof Error?z.message:"Failed to request indexing")}finally{it(!1)}}async function Xa(){it(!0),Oe(null);try{const v=await Ci(t,{urls:[],allUnindexed:!0}),{succeeded:z,failed:he,total:be}=v.summary;$e({title:"Indexing requested",detail:he===0?`${z} unindexed URL${z!==1?"s":""} submitted for indexing.`:`${z}/${be} submitted successfully, ${he} failed.`,tone:he===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(v){Oe(v instanceof Error?v.message:"Failed to request indexing")}finally{it(!1)}}async function Sn(){wt(!0),Oe(null);try{const v=await er(t);n.setQueryData(Dc({client:Y,path:{name:t}}),v),Me(v.sitemaps),$t(v.summary),De(v.preferredSubmissionUrls),Ae(new Set),He({}),v.sitemaps.length===0&&Wt("No sitemaps found in this GSC property. Submit one here to start Google processing it.")}catch(v){Oe(v instanceof Error?v.message:"Failed to list sitemaps")}finally{wt(!1)}}async function ma(v){const z=k.has(v);if(Ae(he=>{const be=new Set(he);return z?be.delete(v):be.add(v),be}),!(z||ve[v])){st(he=>new Set(he).add(v));try{const he=await er(t,v);He(be=>({...be,[v]:he.sitemaps}))}catch(he){Oe(he instanceof Error?he.message:"Failed to load sitemap files")}finally{st(he=>{const be=new Set(he);return be.delete(v),be})}}}async function jt(v){if(!vs||v.length===0)return;const z=[...new Set(v)];St(!0),Oe(null),qe({completed:0,total:z.length});let he=0,be=0,Ze=0,nt=null;try{for(let It=0;It<z.length;It+=50){const ct=z.slice(It,It+50);try{const ke=await Oc(t,ct);he+=ke.summary.accepted,be+=ke.summary.failed,Ze+=ct.length,qe({completed:Ze,total:z.length})}catch(ke){Ze+=ct.length;const Os=ct.length,Gn=z.length-Ze,fa=ke instanceof Error?ke.message:"The batch request failed",Fs=`${he} accepted, ${be} failed, ${Os} unconfirmed, ${Gn} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;nt=`Sitemap submission stopped after a batch request failed. ${Fs} ${fa}`,Oe(nt),$e({title:"Sitemap resubmission partially completed",detail:Fs,tone:"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"});return}}const lt=z.length;$e({title:be===0?"Sitemap submitted to Google":"Some sitemap submissions need attention",detail:be===0?"Google accepted the sitemap submission/refetch request; indexing is not guaranteed.":`Google accepted ${he}/${lt} sitemap submissions; ${be} failed. Indexing is not guaranteed.`,tone:be===0?"positive":"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"}),Pe("")}catch(lt){Oe(lt instanceof Error?lt.message:"Failed to submit sitemap to Google")}finally{St(!1),qe(null),await Sn(),nt&&Oe(nt)}}async function Za(){St(!0);const v=Be??[];try{const z=v.filter(be=>be.isSitemapsIndex),he=[];for(let be=0;be<z.length;be+=4)(await Promise.all(z.slice(be,be+4).map(async nt=>{const lt=ve[nt.path];if(lt)return lt;const It=await er(t,nt.path);return He(ct=>({...ct,[nt.path]:It.sitemaps})),It.sitemaps}))).forEach((nt,lt)=>{he.push(...nt.length>0?nt.map(It=>It.path):[z[be+lt].path])});await jt([...v.filter(be=>!be.isSitemapsIndex).map(be=>be.path),...he])}catch(z){Oe(z instanceof Error?z.message:"Failed to load sitemap files"),St(!1)}}async function ha(v){Jt(!0),Oe(null);try{await Fc(t,"gsc",v),await Nt(n,"google"),c(z=>z.map(he=>he.connectionType==="gsc"?{...he,sitemapUrl:v}:he)),$e({title:"Default sitemap updated",detail:v,tone:"positive",dedupeKey:`gsc:sitemap-default:${t}`,dedupeMode:"replace"})}catch(z){Oe(z instanceof Error?z.message:"Failed to set the default sitemap")}finally{Jt(!1)}}async function xa(v){try{await Dn.mutateAsync({projectName:t,projectLabel:t,opts:v?{sitemapUrl:v}:void 0})}catch{}}async function pa(){we(!0),Oe(null);try{const[v,z]=await Promise.all([a?il().catch(()=>null):Promise.resolve(null),n.fetchQuery({...ai({client:Y,path:{name:t}}),staleTime:Ut}).catch(()=>[])]);o(!!v?.google?.configured),c(z);const he=z.find(be=>be.connectionType==="gsc");await Promise.all([da(he),nn(),On(),wn(),ua(),he?.propertyId?Sn():Promise.resolve()])}finally{we(!1)}}l.useEffect(()=>{pa()},[t,s,a]),l.useEffect(()=>{ee(0),V(null),oe(v=>v.startDate||v.endDate?{...v,startDate:"",endDate:""}:v),E(v=>v+1),On()},[O]);const ga=l.useRef(!1);l.useEffect(()=>{if(!ga.current){ga.current=!0;return}ee(0),qt.setPage(1),nn(0)},[B]);function Kn(v){const z=se===v?null:v;V(z),oe(he=>({...he,startDate:z??"",endDate:z??""})),E(he=>he+1)}const I=l.useRef(!1);l.useEffect(()=>{if(!I.current){I.current=!0;return}ee(0),nn(0)},[ns]);async function fe(){if(!r){Oe("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}et(!0),Oe(null),Wt(null);try{let v=function(ke){if(ke.source!==be||ke.origin!==Ze||!ke.data||typeof ke.data!="object")return;const Os=ke.data;Os.type!==xx||Os.connectionType!=="gsc"||ct(!0)};const{authUrl:z,redirectUri:he}=await Lc(t,"gsc");if(!z.startsWith("https://accounts.google.com/")){Oe("Unexpected OAuth redirect URL. Please try again.");return}const be=window.open(z,"_blank","width=600,height=700");if(!be){window.location.assign(z);return}const Ze=he?new URL(he).origin:window.location.origin;let nt=!1,lt=null;const It=()=>{lt!==null&&window.clearInterval(lt),window.removeEventListener("message",v)},ct=async ke=>{if(!nt){nt=!0,It(),Wt(ke?"Google connected. Refreshing access…":"Refreshing Google connection…");try{await Nt(n,"google"),await pa()}finally{Wt(null)}}};window.addEventListener("message",v),Wt("Finish the Google consent flow in the popup. This page will refresh automatically."),lt=window.setInterval(()=>{be.closed&&ct(!1)},1e3)}catch(v){Oe(v instanceof Error?v.message:"Failed to start OAuth flow")}finally{et(!1)}}async function Le(){Oe(null),Wt(null);try{await Mc(t,"gsc"),await Nt(n,"google"),c(v=>v.filter(z=>z.connectionType!=="gsc")),h([]),y("")}catch(v){Oe(v instanceof Error?v.message:"Failed to disconnect")}}async function es(){if(A){Ge(!0),Oe(null);try{await Bc(t,"gsc",A),await Nt(n,"google"),c(v=>v.map(z=>z.connectionType==="gsc"?{...z,propertyId:A}:z)),$e({title:"GSC property updated",detail:`${t} is now linked to ${A}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(v){Oe(v instanceof Error?v.message:"Failed to save GSC property")}finally{Ge(!1)}}}async function js(){Oe(null),Wt(null);try{await Ds.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(M,10)||void 0,full:F||void 0}}),await Nt(n,"gsc")}catch{}}async function wi(){if(w.trim()){Ue(!0),Oe(null),Wt(null);try{const v=await Kc(t,w.trim());await Nt(n,"gsc"),D(v),N(""),await wn()}catch(v){Oe(v instanceof Error?v.message:"Failed to inspect URL")}finally{Ue(!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"})]})}),Kt&&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:Kt.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:Kt.message}),(_s(Kt.enableUrl)||_s(Kt.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[_s(Kt.enableUrl)&&e.jsx("a",{href:_s(Kt.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 ↗"}),_s(Kt.indexingApiUrl)&&e.jsx("a",{href:_s(Kt.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:()=>Pt(null),children:"×"})]})}),At&&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:[At,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>Oe(null),children:"×"})]}),vn&&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:[vn,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>Wt(null),children:"×"})]}),Ee?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[Rt?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:Rt.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Coverage measured"," ",le?.lastInspectedAt?Ht(le.lastInspectedAt):"never"]}),e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:Ye(Le),children:"Disconnect"})]}):a?e.jsxs(ye,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(ue,{tone:r?"caution":"negative",children:r?"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:r?"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:[r?e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:Se,onClick:Ye(fe),children:Se?"Opening…":"Connect Google Search Console"}):e.jsx(P,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(As,{to:"/settings",children:"Open Settings"})}),!r&&e.jsx("p",{className:"text-xs text-muted",children:"The same Google OAuth app credentials are shared across all projects."})]})]})]}):e.jsx(ye,{className:"surface-card",children:e.jsx("p",{className:"text-sm text-secondary",children:mx})}),(Rt||Ja)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs(ye,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Performance"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Search performance"}),e.jsx(Ve,{text:`${fx(b?.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 ${Na.toLocaleString()} matching rows while the table shows ${Rs} per page.`})]}),b?.window?.startDate&&b.window.endDate&&e.jsxs("p",{className:"text-xs text-muted",children:[b.window.startDate," to ",b.window.endDate,(b.window.daysSinceLatestData??0)>0&&` · latest data ${b.window.daysSinceLatestData} day${b.window.daysSinceLatestData===1?"":"s"} ago`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ha,{windows:hx,value:O,onChange:v=>{J(v),ee(0),qt.setPage(1)},label:"Search Console time period",formatOption:v=>v==="all"?"All":v}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:_,onClick:()=>{ee(0),qt.setPage(1),nn(0),On()},children:_?"Loading…":"Apply filters"})]})]}),b&&b.daily.length>0&&(()=>{const{totals:v,daily:z,trends:he,periodComparison:be}=b,nt=Zi.filter(ke=>G.includes(ke.key)).map(ke=>({dataKey:ke.key,label:ke.label,color:ke.color,axisId:ke.key,inverted:ke.inverted,formatValue:ke.format,trend:ae?he?.[ke.key]??null:null})),lt=ke=>v[ke]??null,It=new Map(z.map(ke=>[ke.date,ke])),ct=z.length===0?[]:rh(z[0].date,z[z.length-1].date).map(ke=>It.get(ke)??{date:ke});return e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:Zi.map(ke=>{const Os=G.includes(ke.key),Gn=lt(ke.key),fa=Gn===null;return e.jsxs("button",{type:"button","aria-pressed":Os,disabled:fa,className:`rounded-md border px-3 py-2 text-left transition-colors ${Os?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${fa?"cursor-not-allowed opacity-50":""}`,onClick:()=>{C(Fs=>Fs.includes(ke.key)?Fs.length===1?Fs:Fs.filter(hc=>hc!==ke.key):[...Fs,ke.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:Os?ke.color:"transparent",border:`1px solid ${ke.color}`}}),e.jsx("span",{className:"text-xs text-secondary",children:ke.label})]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:Gn===null?"—":ke.format(Gn)}),e.jsx("span",{className:"block text-[11px] tabular-nums text-muted",children:gx(be,ke.key,ke.inverted)})]},ke.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:ae,onChange:ke=>q(ke.target.checked)}),"Trend line"]})}),e.jsx("div",{className:"mt-1",children:e.jsx(wl,{data:ct,xKey:"date",series:nt,xTickFormatter:yn,labelFormatter:Vt,onSelectX:Kn,selectedX:se})}),e.jsx("div",{role:"group","aria-label":"Filter the table to a single day",children:z.map(ke=>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":se===ke.date,onClick:()=>Kn(ke.date),children:[Vt(ke.date),": ",ke.clicks," clicks, ",ke.impressions," impressions"]},ke.date))}),se&&e.jsxs("div",{className:"mt-1 flex items-center gap-2 text-xs",children:[e.jsxs("span",{className:"text-secondary",children:["Table showing ",Vt(se)]}),e.jsxs("button",{type:"button",className:"text-link hover:underline",onClick:()=>Kn(se),children:["Show all ",v.days," days"]})]}),v.position!==null&&(v.positionDays??v.days)<v.days&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position covers ",v.positionDays," of ",v.days," days. The rest have no property-level position recorded."]}),(v.position===null||v.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:R.startDate,onChange:v=>oe(z=>({...z,startDate:v.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:R.endDate,onChange:v=>oe(z=>({...z,endDate:v.target.value}))}),e.jsx(zs,{value:R.query,onChange:v=>oe(z=>({...z,query:v})),label:"Filter search queries",placeholder:"Contains query…"}),e.jsx(zs,{value:R.page,onChange:v=>oe(z=>({...z,page:v})),label:"Filter page URLs",placeholder:"Contains page URL…"})]}),m.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Date"}),e.jsx("th",{className:"text-left",children:"Query"}),e.jsx("th",{className:"text-left",children:"Page"}),Object.values(hn).map(v=>e.jsx("th",{className:"text-right","aria-sort":gt?.key===v?gt.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:()=>{qt.setPage(1),dt(z=>z?.key===v?z.dir==="desc"?{key:v,dir:"asc"}:null:{key:v,dir:"desc"})},children:[Ic[v],gt?.key===v?gt.dir==="desc"?" ↓":" ↑":""]})},v))]})}),e.jsx("tbody",{children:Ps.map((v,z)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:v.date}),e.jsx("td",{className:"max-w-xs truncate text-strong",children:v.query}),e.jsx("td",{className:"max-w-xs text-secondary",children:e.jsx(qa,{value:v.page})}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:v.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:v.impressions.toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[(Number.isFinite(v.ctr)?v.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:v.position.toFixed(1)})]},`${v.date}:${v.query}:${v.page}:${z}`))})]})}),e.jsx(Ls,{page:xe?qt.page:Math.floor(T/Rs)+1,pageSize:Rs,visibleRows:Ps.length,totalRows:xe?X:void 0,hasNextPage:xe?void 0:Z,disabled:_,itemLabel:xe?"matches":"rows",onPageChange:v=>{if(xe){qt.setPage(v);return}const z=(v-1)*Rs;ee(z),nn(z)}}),xe&&X>=Na?e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Results are capped at ",Na.toLocaleString(),"; narrow the filters to search beyond this set."]}):null]}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No performance rows match the current filters yet."})]}),e.jsxs(ye,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Coverage"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Index coverage"}),e.jsx(Ve,{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:[le&&le.notIndexed.length>0&&e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:pe,onClick:()=>{Xa()},children:pe?"Requesting…":`Request indexing (${le.notIndexed.length})`}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:ut,onClick:()=>{ua(!0)},children:ut?"Loading…":"Reload saved coverage"})]})]}),le&&le.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const v=le.summary.indexed+le.summary.notIndexed,z=v>0?le.summary.indexed/v:0,he=v>0?le.summary.notIndexed/v:0,be=54,Ze=2*Math.PI*be,nt=Ze*(1-z),lt=Ze*he,It=Ze*z;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:be,fill:"none",stroke:us.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:be,fill:"none",stroke:qs.positiveDeep,strokeWidth:"14",strokeDasharray:Ze,strokeDashoffset:nt,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),le.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:be,fill:"none",stroke:us.textFaint,strokeWidth:"14",strokeDasharray:`${lt} ${Ze-lt}`,strokeDashoffset:-It,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:[(z*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:le.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:le.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:["Not indexed",(le.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-faint",children:["· ",(le.reasonGroups??[]).length," ",(le.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),le.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:le.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(v=>{const z=v==="indexed"?le.indexed.length:v==="notIndexed"?le.notIndexed.length:le.deindexed.length,he=v==="indexed"?"Indexed":v==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",role:"tab","aria-selected":at===v,className:`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${at===v?"border-accent text-heading":"border-transparent text-secondary hover:border-mono-600 hover:text-strong"}`,onClick:()=>{fs(v),Zt(null)},children:[he," (",z,")"]},v)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[at==="indexed"&&le.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:as.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:v.url}),e.jsx("td",{className:"text-secondary",children:v.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:v.crawlTime?v.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:v.isMobileFriendly===!0?"Yes":v.isMobileFriendly===!1?"No":"—"})]},v.id))})]}),at==="notIndexed"&&!ht&&(le.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:(le.reasonGroups??[]).map(v=>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(v.reason),onKeyDown:z=>{(z.key==="Enter"||z.key===" ")&&(z.preventDefault(),Zt(v.reason))},tabIndex:0,role:"button","aria-label":`View ${v.reason} pages`,children:[e.jsx("td",{className:"text-strong",children:v.reason}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:v.count})]},v.reason))})]}),at==="notIndexed"&&!ht&&(le.reasonGroups??[]).length===0&&le.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:ot.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:v.url}),e.jsx("td",{className:"text-secondary",children:v.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:v.coverageState??"Unknown"})]},v.id))})]}),at==="notIndexed"&&ht&&(()=>{const v=(le.reasonGroups??[]).find(z=>z.reason===ht);return v?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:v.reason}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[v.count," affected page",v.count!==1?"s":""]})]}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:pe,onClick:()=>{Fn(v.urls.map(z=>z.url))},children:pe?"Requesting…":`Request indexing (${v.count})`})]}),e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Last Crawl"}),e.jsx("th",{className:"w-8"})]})}),e.jsx("tbody",{children:$.map(z=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:z.url}),e.jsx("td",{className:"text-secondary",children:z.crawlTime?z.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-strong transition-colors",disabled:pe,onClick:()=>{Fn([z.url])},title:"Request indexing",children:"Index"})})]},z.id))})]})]}):null})(),at==="deindexed"&&le.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:bs.map((v,z)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:v.url}),e.jsx("td",{className:"text-secondary",children:v.previousState}),e.jsx("td",{className:"text-secondary",children:v.currentState}),e.jsx("td",{className:"text-secondary",children:v.transitionDate.split("T")[0]})]},`${v.url}-${z}`))})]}),(at==="indexed"&&le.indexed.length===0||at==="notIndexed"&&!ht&&le.notIndexed.length===0||at==="deindexed"&&le.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),e.jsx(Ls,{page:je,pageSize:Ks,visibleRows:Math.min(Ks,Ne.length-Ie),totalRows:Ne.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":Qt,onClick:()=>ss(v=>!v),children:[e.jsx("span",{children:"Coverage history"}),e.jsx("span",{children:Qt?"Hide snapshots":kt.length>0?`View ${kt.length} snapshots`:"View history"})]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["Current: ",le.summary.indexed.toLocaleString()," indexed, ",le.summary.notIndexed.toLocaleString()," not indexed.",K&&e.jsxs(e.Fragment,{children:[" Since the last snapshot: ",K.indexed>=0?"+":"",K.indexed.toLocaleString()," indexed, ",K.notIndexed>=0?"+":"",K.notIndexed.toLocaleString()," not indexed."]})]}),Qt&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:kt.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:kt.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:v.date}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:v.indexed.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:v.notIndexed.toLocaleString()})]},v.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:ut?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),e.jsxs(ye,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Sitemaps"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Sitemap operations"}),e.jsx(Ve,{text:"Submitting asks Google to refetch these sitemaps. Indexing is not guaranteed."})]})]}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:Fe||!Rt?.propertyId,onClick:()=>{Sn()},children:Fe?"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:Ce,onChange:v=>Pe(v.target.value),onKeyDown:v=>v.key==="Enter"&&void jt([Ce.trim()])}),e.jsx(P,{type:"button",size:"sm",disabled:!vs||yt||!Ce.trim(),onClick:()=>{jt([Ce.trim()])},children:yt?"Submitting…":"Submit sitemap to Google"})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:!vs||yt||la.length===0,onClick:()=>{jt(la)},children:yt?"Resubmitting…":ca}),e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:!vs||yt||!Be?.length,onClick:()=>{Za()},children:"Resubmit all files"}),tt&&e.jsxs("span",{className:"text-xs text-muted",children:["Top level: ",tt.indexes," index",tt.indexes===1?"":"es",", ",tt.files," file",tt.files===1?"":"s"]}),te&&e.jsxs("span",{className:"text-xs text-secondary",children:["Submitting ",te.completed,"/",te.total]})]}),!vs&&Rt&&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:Ye(fe),children:"Reconnect"})]}),Be&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:Be.length>0?e.jsxs(e.Fragment,{children:[e.jsx(zs,{value:Lt,onChange:v=>{Xe(v),zt.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:zt.rows.flatMap(v=>{const z=eo(v),he=to(v),be=so(v),Ze=ve[v.path]??[],nt=k.has(v.path),lt=e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs text-strong",children:e.jsx(qa,{value:v.path})}),e.jsx("td",{className:"text-secondary",children:v.isSitemapsIndex?e.jsx("button",{type:"button",className:"text-secondary hover:text-strong","aria-expanded":nt,"aria-label":`${nt?"Collapse":"Expand"} files in ${v.path}`,onClick:()=>{ma(v.path)},children:vt.has(v.path)?"Loading…":`${nt?"▾":"▸"} Index${ve[v.path]?` (${Ze.length})`:""}`}):"Sitemap"}),e.jsx("td",{className:"text-secondary",children:be}),e.jsx("td",{className:"text-secondary",children:v.lastSubmitted?v.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:v.lastDownloaded?v.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:z.toLocaleString()}),e.jsx("td",{className:"max-w-48 text-secondary",children:he||"—"}),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:!vs||yt,onClick:()=>{jt([v.path])},children:v.lastSubmitted?"Resubmit to Google":"Submit to Google"}),Rt?.sitemapUrl===v.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:Yt,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{ha(v.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Dn.isPending,onClick:()=>{xa(v.path)},children:"Inspect URLs"})]})})]},v.path),It=v.isSitemapsIndex&&nt?Ze.map(ct=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs pl-6 text-secondary",children:e.jsx(qa,{value:ct.path})}),e.jsx("td",{className:"text-secondary",children:"File"}),e.jsx("td",{className:"text-secondary",children:so(ct)}),e.jsx("td",{className:"text-secondary",children:ct.lastSubmitted?ct.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:ct.lastDownloaded?ct.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:eo(ct).toLocaleString()}),e.jsx("td",{className:"text-secondary",children:to(ct)||"—"}),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:!vs||yt,onClick:()=>{jt([ct.path])},children:"Resubmit"}),Rt?.sitemapUrl===ct.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:Yt,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{ha(ct.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:Dn.isPending,onClick:()=>{xa(ct.path)},children:"Inspect URLs"})]})})]},`${v.path}:${ct.path}`)):[];return[lt,...It]})})]}),e.jsx(Ls,{page:zt.page,pageSize:Rs,visibleRows:zt.rows.length,totalRows:zt.totalRows,onPageChange:zt.setPage,itemLabel:"sitemaps"})]}):e.jsx("p",{className:"text-sm text-muted",children:"No sitemaps found for this property."})})]}),e.jsxs(ye,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Inspection"}),e.jsx("h3",{children:"Inspect a URL"})]})}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"url",placeholder:"https://example.com/page",value:w,onChange:v=>N(v.target.value),onKeyDown:v=>v.key==="Enter"&&void wi()}),e.jsx(P,{type:"button",size:"sm",disabled:_e||!Rt?.propertyId||!w.trim(),onClick:Ye(wi),children:_e?"Inspecting…":"Inspect URL"})]}),j&&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:j.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:j.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:Si(j.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:Ht(j.crawlTime)})]})]})]}),e.jsxs(ye,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Inspection log"})]}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:W,onClick:()=>{wn(!0)},children:W?"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:Q,onChange:v=>re(v.target.value)}),e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:W,onClick:()=>{wn(!0)},children:"Apply filter"})]}),x.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:x.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:v.url}),e.jsx("td",{className:"text-neutral",children:v.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:v.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:v.coverageState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:Si(v.isMobileFriendly??null)}),e.jsx("td",{className:"text-secondary",children:Ht(v.inspectedAt)})]},v.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No inspection history yet."})]}),e.jsxs(ye,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Deindexed"}),e.jsx("h3",{children:"Recent indexing losses"})]})}),f.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:f.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:v.url}),e.jsx("td",{className:"text-secondary",children:v.previousState??"Unknown"}),e.jsx("td",{className:"text-neutral",children:v.currentState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:Ht(v.transitionDate)})]},`${v.url}:${v.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No deindexed transitions recorded."})]})]}),Rt&&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:()=>Xt(v=>!v),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 ${mt?"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"})]})}),mt&&e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(ye,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Property"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Pick the Search Console property"}),e.jsx(Ve,{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:A,disabled:Ke||d.length===0,onChange:v=>y(v.target.value),children:d.length===0?e.jsx("option",{value:"",children:Ke?"Loading properties…":"No properties available"}):d.map(v=>e.jsxs("option",{value:v.siteUrl,children:[v.siteUrl," · ",v.permissionLevel]},v.siteUrl))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:Ke,onClick:()=>{da(Rt,!0)},children:Ke?"Refreshing…":"Refresh properties"}),e.jsx(P,{type:"button",size:"sm",disabled:!A||We,onClick:Ye(es),children:We?"Saving…":"Save property"})]})]})]}),e.jsxs(ye,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"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:M,onChange:v=>L(v.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:F,onChange:v=>H(v.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(P,{type:"button",size:"sm",disabled:Ds.isPending||!Rt.propertyId,onClick:Ye(js),children:Ds.isPending?"Queueing…":"Queue sync"}),!Rt.propertyId&&e.jsx("p",{className:"text-xs text-caution-400",children:"Select a Search Console property before queueing a sync."})]})]})]})})]})]})]})}const bx=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function vx({projectName:t,projectId:s}){const n=ms(),[a,r]=l.useState(null),[o,i]=l.useState(null),[c,d]=l.useState(!1),h=Te(ai({client:Y,path:{name:t}})),m=h.data?.find(X=>X.connectionType==="gbp"),u=!!m,b=a?{locationName:a}:void 0,p=Te({...Vc({client:Y,path:{name:t}}),enabled:u}),x=Te({...Qc({client:Y,path:{name:t},query:b}),enabled:u}),g=Te({...zc({client:Y,path:{name:t},query:b}),enabled:u}),f=Te({...Wc({client:Y,path:{name:t},query:b}),enabled:u}),S=Te({...Hc({client:Y,path:{name:t},query:b}),enabled:u}),j=Te({...Yc({client:Y,path:{name:t},query:b}),enabled:u}),D=Te({queryKey:["gbp-section-insights",t],queryFn:()=>Jc(t),enabled:u});function A(){Nt(n,"gbp")}const y=Tt({...Xc(),onSuccess:X=>{ol({id:X.runId,projectId:s,kind:Ys["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),$e({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),w=l.useSyncExternalStore(ll,Oa,Oa),N=Object.values(w.runs).some(X=>X.kind===Ys["gbp-sync"]&&X.projectId===s),M=y.isPending||N,L=Tt({...Zc(),onSuccess:()=>A()});if(l.useEffect(()=>{if(!a||!p.data)return;const X=p.data.locations.filter(de=>de.selected);(X.length<=1||!X.some(de=>de.locationName===a))&&r(null)},[a,p.data]),l.useEffect(()=>{if(!o||!p.data)return;(a?[a]:p.data.locations.filter(de=>de.selected).map(de=>de.locationName)).includes(o)||i(null)},[o,p.data,a]),h.isLoading)return null;if(!m){const X=[{title:"Connect your Google account",command:`canonry gbp connect ${t}`,note:"Opens Google OAuth. Grant Business Profile (business.manage) access."},{title:"Choose the account",command:`canonry gbp accounts ${t}`,note:"Pick which Business Profile account this project tracks."},{title:"Select locations",command:`canonry gbp locations discover ${t}`,note:e.jsxs(e.Fragment,{children:["Then adopt the ones to sync: ",e.jsxs("code",{className:"rounded bg-bg-elevated/80 px-1 py-0.5 font-mono text-[11px] text-secondary",children:["canonry gbp locations select ",t," <location>"]})]})},{title:"Sync, and keep it fresh",command:`canonry gbp sync ${t}`,note:e.jsxs(e.Fragment,{children:["Schedule it: ",e.jsxs("code",{className:"rounded bg-bg-elevated/80 px-1 py-0.5 font-mono text-[11px] text-secondary",children:["canonry schedule set ",t," --kind gbp-sync --preset daily"]})]})}];return e.jsx("section",{className:"page-section-divider",children:e.jsxs(ye,{className:"surface-card",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Local presence"}),e.jsx("h2",{children:"Connect Google Business Profile"}),e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-muted",children:"Track local performance, search terms, place-action CTAs, and how your public Maps listing compares to the profile you control. Four steps from the CLI:"}),e.jsx("ol",{className:"mt-5 space-y-4",children:X.map((de,xe)=>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:xe+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:de.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:de.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:de.note})]})]},de.title))})]})})}const F=x.data,H=p.data?.locations??[],O=H.filter(X=>X.selected),J=g.data?.keywords??[],G=f.data?.lodging??[],C=S.data?.placeActions??[],ae=j.data?.places??[],q=H.length>0?H[0].accountName:m.domain,se=a?H.find(X=>X.locationName===a)?.displayName??null:null,V=a?H.filter(X=>X.locationName===a):O,B=new Set(V.map(X=>X.locationName)),E=G.filter(X=>B.has(X.locationName)),R=C.filter(X=>B.has(X.locationName)),oe=ae.filter(X=>B.has(X.locationName)),T=new Set(O.map(X=>X.locationName)),ee=a?J:J.filter(X=>T.has(X.locationName)),Z=!a&&O.length>1,ge=(D.data??[]).filter(X=>!X.dismissed&&bx.has(X.type)&&(!se||X.query===se||X.query===a||X.title.startsWith(se)));return e.jsx("section",{className:"page-section-divider",children:e.jsxs(ye,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Local presence"}),e.jsxs("h2",{className:"flex items-center gap-2",children:["Google Business Profile",e.jsx(Ve,{text:"How AI answer engines and Maps surface this business: performance, search terms, and how your public listing compares to the profile you control."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ue,{tone:"positive",children:"Connected"}),!ie()&&e.jsx(Je,{type:"button",variant:"outline",size:"sm",disabled:M,onClick:()=>y.mutate({client:Y,path:{name:t},body:{}}),children:M?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-muted",children:[q?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-secondary",children:q})," · "]}):null,p.data?`${p.data.totalSelected} of ${p.data.totalDiscovered} locations tracked`:"Loading locations…"]}),O.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:X=>r(X.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"}),O.map(X=>e.jsx("option",{value:X.locationName,children:X.displayName},X.id))]})]}),O.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(X=>e.jsx("div",{className:["insight-card",Mx(X.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:[X.title,X.recommendation?.reason&&e.jsx(Ve,{text:X.recommendation.reason})]})},X.id))]}),F&&e.jsx(Dx,{performance:F.performance,freshness:F.freshness,timeseries:F.timeseries}),F?.profileCompleteness&&e.jsx(jx,{summary:F.profileCompleteness}),V.length>0&&e.jsx(Nx,{locations:V,lodging:E,places:oe,placeActions:R,expandedLocation:o,onToggleExpanded:X=>{i(de=>de===X?null:X)}}),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"}),g.data&&g.data.total>0&&e.jsxs("span",{className:"text-[11px] text-faint",children:[g.data.thresholdedPct,"% privacy-thresholded"]})]}),ee.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No keyword impressions stored yet."}):e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Search term"}),Z&&e.jsx("th",{className:"text-left",children:"Location"}),e.jsx("th",{className:"text-right",children:"Impressions"}),e.jsx("th",{className:"text-right",children:"Window"})]})}),e.jsx("tbody",{children:ee.slice(0,25).map(X=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-neutral",children:X.keyword}),Z&&e.jsx("td",{className:"text-muted",children:H.find(de=>de.locationName===X.locationName)?.displayName??X.locationName}),e.jsx("td",{className:"text-right font-mono text-strong",children:X.valueCount!==null?X.valueCount.toLocaleString():e.jsxs("span",{className:"text-muted",title:"Privacy floor — Google withheld the exact count",children:["<",X.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-faint",children:[X.periodStart,"–",X.periodEnd]})]},`${X.locationName}:${X.keyword}`))})]})]})]}),e.jsxs("div",{className:"mt-6 border-t border-default pt-4",children:[e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 text-xs font-medium text-secondary hover:text-strong",onClick:()=>d(X=>!X),"aria-expanded":c,children:[e.jsx("span",{"aria-hidden":"true",children:c?"▾":"▸"})," Manage locations (",H.length,")"]}),c&&e.jsx("div",{className:"mt-3",children:H.length===0?e.jsxs("p",{className:"text-sm text-muted",children:["No locations discovered. Run ",e.jsx("span",{className:"font-mono",children:"canonry gbp locations discover"}),"."]}):e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Location"}),e.jsx("th",{className:"text-left",children:"Address"}),e.jsx("th",{className:"text-left",children:"Status"}),!ie()&&e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:H.map(X=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:X.displayName}),e.jsx("td",{className:"text-muted",children:X.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(ue,{tone:X.selected?"positive":"neutral",children:X.selected?"Tracked":"Not tracked"})}),!ie()&&e.jsx("td",{className:"text-right",children:e.jsx(Je,{type:"button",variant:"outline",size:"sm",disabled:L.isPending,onClick:()=>L.mutate({client:Y,path:{name:t,locationName:X.locationName},body:{selected:!X.selected}}),children:X.selected?"Untrack":"Track"})})]},X.id))})]})})]})]})})}function jx({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:Un(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:Un(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:Un(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:Un(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:Un(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(Ve,{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 ${$x(a.tone)}`,children:a.value}),a.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-faint",children:a.detail})]},a.label))})]})}function Nx({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])),d=new Map;for(const h of a){const m=d.get(h.locationName)??[];m.push(h),d.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(Ve,{text:ie()?"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest sync, not that every Google product lacks the information.":"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest Canonry sync, not that every Google product lacks the information."})]}),e.jsxs("span",{className:"text-[11px] text-faint",children:[t.length," location",t.length===1?"":"s"]})]}),e.jsx("div",{className:"data-table-wrapper",children:e.jsxs("table",{className:"data-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"min-w-[14rem]",children:"Location"}),e.jsx("th",{className:"min-w-[15rem]",children:"Owner profile"}),e.jsx("th",{className:"min-w-[11rem]",children:"Hotel data"}),e.jsx("th",{className:"min-w-[11rem]",children:"Public Maps"}),e.jsx("th",{className:"min-w-[10rem]",children:"CTAs"}),e.jsx("th",{className:"text-right",children:"Detail"})]})}),e.jsx("tbody",{children:t.map(h=>{const m=i.get(h.locationName)??null,u=c.get(h.locationName)??null,b=d.get(h.locationName)??[],p=r===h.locationName;return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-strong",children:h.displayName}),e.jsx("p",{className:"mt-1 text-xs text-faint",children:h.primaryCategoryDisplayName??"Primary category not returned"}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[e.jsx(ue,{tone:h.selected?"positive":"neutral",children:h.selected?"Tracked":"Not tracked"}),h.openStatus&&h.openStatus!=="OPEN"&&e.jsx(ue,{tone:h.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:Gl(h.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(Sx,{location:h})}),e.jsx("td",{children:e.jsx(Cx,{lodging:m})}),e.jsx("td",{children:e.jsx(Ax,{place:u,mapsUri:h.mapsUri})}),e.jsx("td",{children:e.jsx(Rx,{actions:b})}),e.jsx("td",{className:"text-right",children:e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>o(h.locationName),children:p?"Hide":"Details"})})]}),p&&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(Tx,{location:h,lodging:m,place:u,placeActions:b})})})]},h.id)})})]})})]})}function wx(t){return[{label:"Description",tone:un(t.description)?"positive":"neutral",value:un(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:un(t.primaryPhone)?"positive":"neutral",value:un(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:un(t.websiteUri)?"positive":"neutral",value:un(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 Sx({location:t}){const s=wx(t);return e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>e.jsxs(ue,{tone:n.tone,children:[n.label," ",n.value]},n.label))})}function Cx({lodging:t}){return e.jsx(oi,{...kx(t)})}function kx(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 Ax({place:t,mapsUri:s}){return e.jsx(oi,{...Px(t,s)})}function Px(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 Rx({actions:t}){return e.jsx(oi,{...Ix(t)})}function Ix(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 oi({tone:t,label:s,detail:n}){return e.jsxs("div",{children:[e.jsx(ue,{tone:t,children:s}),e.jsx("p",{className:"mt-1.5 text-xs leading-5 text-faint",children:n})]})}function Tx({location:t,lodging:s,place:n,placeActions:a}){const r=s?qx(s.attributes):[];return e.jsxs("div",{className:"grid gap-5 text-xs lg:grid-cols-3",children:[e.jsxs(xr,{title:"Owner profile · Business Information",children:[e.jsx(Gt,{label:"Primary category",value:t.primaryCategoryDisplayName??"Not returned"}),e.jsx(Gt,{label:"Secondary categories",value:t.additionalCategories.length>0?t.additionalCategories.join(", "):"Not returned"}),e.jsx(Gt,{label:"Description",value:un(t.description)?t.description:"Not returned"}),e.jsx(Gt,{label:"Hours",value:t.regularHours?"Returned by Google":"Not returned"}),e.jsx(Gt,{label:"Service area",value:t.serviceArea?"Returned by Google":"Not returned"}),e.jsx(Gt,{label:"Phone",value:t.primaryPhone??"Not returned"}),e.jsx(Gt,{label:"Website",value:t.websiteUri??"Not returned"}),e.jsx(Gt,{label:"Open status",value:Gl(t.openStatus)}),e.jsx(Gt,{label:"Opening date",value:t.openingDate??"Not returned"})]}),e.jsx(xr,{title:"Hotel data · Lodging API",children:s?e.jsxs(e.Fragment,{children:[e.jsx(Gt,{label:"Last checked",value:no(s.syncedAt)}),e.jsx(Gt,{label:"Groups returned",value:String(s.populatedGroupCount)}),e.jsx(Gt,{label:"Populated groups",value:r.length>0?r.join(", "):"None returned"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Lodging API snapshot was stored for this location."})}),e.jsxs(xr,{title:"Public listing + CTAs",children:[n?e.jsxs(e.Fragment,{children:[e.jsx(Gt,{label:"Places tier",value:n.tier}),e.jsx(Gt,{label:"Last checked",value:no(n.syncedAt)}),e.jsx(Gt,{label:"Public signals",value:n.amenities.length>0?n.amenities.join(", "):"No supported signals detected"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Places Details snapshot was stored for this location."}),t.mapsUri&&e.jsx("a",{href:t.mapsUri,target:"_blank",rel:"noopener noreferrer",className:"inline-block text-muted hover:text-neutral",children:"View on Google Maps →"}),e.jsx("div",{className:"mt-3 border-t border-default pt-3",children:a.length===0?e.jsx("p",{className:"leading-5 text-muted",children:"No placeActionLinks returned."}):e.jsx("div",{className:"grid gap-2",children:a.map(o=>e.jsxs("div",{className:"grid gap-0.5",children:[e.jsxs("span",{className:"font-medium text-neutral",children:[Ba(o.placeActionType),o.isPreferred?" · preferred":""]}),e.jsxs("span",{className:"text-faint",children:[Ba(o.providerType),o.uri?` · ${Lx(o.uri)}`:""]})]},o.placeActionLinkName))})})]})]})}function xr({title:t,children:s}){return e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-[11px] font-semibold uppercase tracking-[0.14em] text-muted",children:t}),e.jsx("div",{className:"grid gap-2",children:s})]})}function Gt({label:t,value:s}){return e.jsxs("div",{className:"grid grid-cols-[7.25rem_minmax(0,1fr)] gap-3",children:[e.jsx("span",{className:"text-faint",children:t}),e.jsx("span",{className:"min-w-0 break-words text-secondary",children:s})]})}function Un(t,s,n){return t===s?"positive":t===0?n:"caution"}function $x(t){switch(t){case"positive":return"text-positive";case"caution":return"text-caution";case"negative":return"text-negative";case"neutral":return"text-neutral"}}function Mx(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function un(t){return typeof t=="string"&&t.trim().length>0}function Gl(t){return t?Ba(t):"Not returned"}function Ba(t){return t?t.toLowerCase().split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"Unknown"}function Lx(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function no(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function qx(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&Ex(n)).map(([s])=>Ba(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function Ex(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function Dx({performance:t,freshness:s,timeseries:n}){const a=t.totals,r=ed.filter(x=>(a[x]??0)>0),o=td.filter(x=>(a[x]??0)>0),i=Object.keys(a).filter(x=>(a[x]??0)>0&&sd(x)==="other").sort((x,g)=>(a[g]??0)-(a[x]??0)),c=Object.keys(a).filter(x=>(a[x]??0)===0).sort(),d=n.map(x=>{const g={date:x.date};for(const[f,S]of Object.entries(x.metrics))g[f]=S;return g}),h=n.find(x=>x.pending)?.date,m=n.length>0?n[n.length-1].date:void 0,u=d.length>0,b=s.dataThroughDate?`Data through ${Vt(s.dataThroughDate)}${s.pendingDays>0?` · ${s.pendingDays}d pending`:""}`:null,p=[...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"}),b&&e.jsx("span",{className:"text-[11px] text-muted",children:b})]}),!u||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(ao,{data:d,metrics:r,kind:"line",firstPending:h,lastDate:m}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-x-5 gap-y-1",children:p.map(x=>e.jsxs("span",{className:"text-sm text-secondary",children:[Fa(x)," ",e.jsx("span",{className:"font-mono text-heading",children:(a[x]??0).toLocaleString()})]},x))})]})]}),u&&o.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(ao,{data:d,metrics:o,kind:"area",firstPending:h,lastDate:m})]}),c.length>0&&e.jsxs("p",{className:"text-xs text-faint",children:["Not active: ",c.map(x=>Fa(x)).join(", ")]})]})}function ao({data:t,metrics:s,kind:n,firstPending:a,lastDate:r}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(Xs,{width:"100%",height:"100%",children:e.jsxs(Zs,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(na,{stroke:sa,vertical:!1}),e.jsx(en,{dataKey:"date",tick:Ft,tickLine:!1,axisLine:{stroke:ds},tickFormatter:yn,minTickGap:24}),e.jsx(tn,{tick:Ft,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(sn,{...ts,labelFormatter:Vt,formatter:(o,i)=>[typeof o=="number"?o.toLocaleString():String(o??0),Fa(String(i??""))]}),e.jsx(Ua,{wrapperStyle:{fontSize:11,color:us.text},formatter:o=>Fa(o)}),a&&r&&e.jsx(Kr,{x1:a,x2:r,fill:us.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:us.textDim,fontSize:10}}),s.map((o,i)=>n==="line"?e.jsx(Ms,{type:"monotone",dataKey:o,stroke:rt[i%rt.length],strokeWidth:2,dot:!1,isAnimationActive:!1},o):e.jsx(Bs,{type:"monotone",dataKey:o,stackId:"reach",stroke:rt[i%rt.length],fill:rt[i%rt.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},o))]})})})}function Ox(t){return Sl(Es(String(t)))}function Fx(t){return Ws(Es(String(t)))}function pr({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(Km,{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 wa=Rs;function Cn(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function gr(t){return t.toLocaleString()}function Kx(t){const s=Number(t);return Number.isFinite(s)?`${(s*100).toFixed(1)}%`:"—"}function Gx(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 _x(t){const s=t.filter(n=>n.kind===Ys["backlink-extract"]&&!cl(n.status));return s.length===0?null:s.reduce((n,a)=>n.createdAt>a.createdAt?n:a)}function Ux(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 Bx({projectName:t}){const[s,n]=l.useState(null),[a,r]=l.useState(null),[o,i]=l.useState([]),[c,d]=l.useState(null),[h,m]=l.useState(null),[u,b]=l.useState(null),[p,x]=l.useState(Date.now()),[g,f]=l.useState(0),[S,j]=l.useState(!0),[D,A]=l.useState(!1),[y,w]=l.useState(null),N=l.useCallback(async()=>{j(!0),w(null);try{const[q,se,V,B,E]=await Promise.all([nd().catch(()=>null),ad(t,{excludeCrawlers:!0}).catch(()=>null),rd(t,{limit:wa,offset:g,excludeCrawlers:!0}).catch(oe=>{if(oe instanceof pn&&oe.code==="NOT_FOUND")return null;throw oe}),id(t).catch(()=>[]),od(t).catch(()=>[])]);d(q),n(se),r(V),i(B);const R=_x(E);m(R)}catch(q){w(q instanceof Error?q.message:"Failed to load backlinks")}finally{j(!1)}},[t,g]);l.useEffect(()=>{N()},[N]),l.useEffect(()=>{if(!h)return;const q=h.id;let se=!1;const V=async()=>{try{const E=await Fr(q);if(se)return;cl(E.status)?(m(null),b(E),await N()):m(R=>R?.id===E.id?{...R,...E}:R)}catch{}},B=window.setInterval(()=>{V()},3e3);return()=>{se=!0,window.clearInterval(B)}},[h,N]),l.useEffect(()=>{if(!h)return;const q=window.setInterval(()=>x(Date.now()),1e3);return()=>window.clearInterval(q)},[h]),l.useEffect(()=>{if(!u||u.status==="failed")return;const q=window.setTimeout(()=>b(null),1e4);return()=>window.clearTimeout(q)},[u]);async function M(){A(!0),w(null);try{const q=await cd(t);m(q)}catch(q){q instanceof pn&&q.code==="MISSING_DEPENDENCY"?w("DuckDB is not installed. Visit the Backlinks admin page to install it."):w(q instanceof Error?q.message:"Failed to trigger extract")}finally{A(!1)}}const L=l.useMemo(()=>o.slice().sort((q,se)=>q.queriedAt.localeCompare(se.queriedAt)).map(q=>({date:q.queriedAt,linkingDomains:q.totalLinkingDomains})),[o]),F=a?.rows??[],H=a?.total??0,O=s?.excludedLinkingDomains??0,J=Math.floor(g/wa)+1;return l.useEffect(()=>{g>0&&g>=H&&f(0)},[g,H]),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"})]})}),y&&e.jsx(ye,{className:"surface-card p-4 mb-4 border-negative-800/60",children:e.jsx("p",{className:"text-sm text-negative",children:y})}),h&&e.jsx(ye,{className:"surface-card p-4 mb-4 border-info-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Dm,{className:"h-5 w-5 text-info-400 animate-spin shrink-0 mt-0.5","aria-hidden":!0}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"Extract running"}),e.jsx(ue,{tone:"neutral",children:h.status}),e.jsxs("span",{className:"text-sm text-secondary tabular-nums",children:[Ux(h.startedAt??null,h.createdAt)," elapsed · refreshing every 3s"]}),e.jsxs("span",{className:"sr-only",children:["now=",p]})]}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Refreshing this project from the current Common Crawl release."})]})]})}),u&&!h&&e.jsx(ye,{className:`surface-card p-4 mb-4 ${u.status==="failed"?"border-negative-800/60":"border-positive-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[u.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(Om,{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 ${u.status==="failed"?"text-negative":"text-positive"}`,children:u.status==="failed"?"Extract failed":"Extract complete"}),u.error?e.jsx("p",{className:"text-sm text-secondary mt-1",children:ld(u.error)}):u.status!=="failed"?e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),G()]});function G(){return S?e.jsx(ye,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading backlinks…"})}):C()}function C(){const q=s!==null&&s.totalLinkingDomains>0,se=u?.status==="failed",V=s!==null&&s.totalLinkingDomains===0&&!se,B=c?.status==="ready",E=c?.status==="failed",R=c&&(c.status==="downloading"||c.status==="querying"||c.status==="queued");return q?ae(e.jsxs(e.Fragment,{children:[!ie()&&e.jsxs(e.Fragment,{children:[e.jsxs(P,{type:"button",variant:"outline",size:"sm",disabled:D||h!==null,onClick:Ye(M),children:[e.jsx(bl,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":D?"Queuing…":"Re-run extract"]}),e.jsx(pr,{label:"About re-running",children:"Re-queries the current release for this project without downloading it again."})]}),!ie()&&e.jsx(P,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Cn("/backlinks"),children:"Open admin"})})]})):e.jsx(ye,{className:"surface-card p-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-bg-elevated text-secondary",children:e.jsx(Fm,{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."}),!ie()&&e.jsx("div",{className:"mt-4",children:e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Cn("/backlinks"),children:"Set up backlinks"})})})]}),R&&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."]}),!ie()&&e.jsx("div",{className:"mt-4",children:e.jsx(P,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Cn("/backlinks"),children:"View sync status"})})})]}),E&&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."}),!ie()&&e.jsx("div",{className:"mt-4",children:e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Cn("/backlinks"),children:"Go to Backlinks admin"})})})]}),B&&!R&&!V&&!se&&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."]}),!ie()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(P,{type:"button",size:"sm",disabled:D||h!==null,onClick:Ye(M),children:[e.jsx(_a,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":D?"Queuing…":"Run extract"]}),e.jsx(pr,{label:"About extraction",children:"Queries the current release for this project without downloading it again."})]})]}),se&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Last extract failed"}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"See the error above, then check the workspace source before retrying."}),!ie()&&e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Cn("/backlinks"),children:"Go to Backlinks admin"})})})]}),V&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No referring domains found"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["The latest release found no referring domains for ",s.targetDomain,". Try a newer release or re-run this extract."]}),!ie()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Cn("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(P,{type:"button",variant:"outline",size:"sm",disabled:D||h!==null,onClick:Ye(M),children:[e.jsx(_a,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":D?"Queuing…":"Re-run extract"]}),e.jsxs(pr,{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 ae(q){if(!s)return null;const se="Linking hosts",V="linking hosts",B="release";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"gauge-row",children:[e.jsxs("div",{className:"metric-card",children:[e.jsx("p",{className:"metric-card-eyebrow",children:"Referring domains"}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:gr(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 ",V]}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:gr(s.totalHosts)})}),e.jsxs("p",{className:"metric-card-sub",children:["aggregate ",V," 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:Kx(s.top10HostsShare)})}),e.jsxs("p",{className:"metric-card-sub",children:["share of ",V," from the 10 largest linking domains"]})]})]}),e.jsxs("p",{className:"text-xs text-muted mt-2",children:[e.jsx("span",{className:"text-secondary",children:"Common Crawl"})," · ",B," ",e.jsx("code",{className:"text-secondary",children:s.release})," · queried ",Gx(s.queriedAt),O>0&&e.jsxs(e.Fragment,{children:[" · ",O," excluded domain",O===1?"":"s"]})]}),L.length>=2&&e.jsxs(ye,{className:"surface-card p-4 mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Referring domains over time"}),e.jsx("div",{className:"h-40 mt-2",children:e.jsx(Xs,{width:"100%",height:"100%",children:e.jsxs(Zs,{data:L,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:rt[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:rt[0],stopOpacity:0})]})}),e.jsx(en,{dataKey:"date",tick:Ft,stroke:ds,tickFormatter:Ox}),e.jsx(tn,{tick:Ft,stroke:ds,allowDecimals:!1}),e.jsx(sn,{contentStyle:ts.contentStyle,labelStyle:ts.labelStyle,itemStyle:ts.itemStyle,labelFormatter:Fx}),e.jsx(Bs,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:rt[0],fill:"url(#bl-gradient)",strokeWidth:2})]})})})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Top referring domains"}),e.jsx(ye,{className:"surface-card overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base text-left text-xs uppercase tracking-wide text-faint",children:[e.jsx("th",{className:"px-4 py-2 font-medium",children:"Domain"}),e.jsx("th",{className:"px-4 py-2 text-right font-medium",children:se})]})}),e.jsxs("tbody",{children:[F.map(E=>e.jsxs("tr",{className:"border-b border-mono-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-strong",children:E.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-secondary tabular-nums",children:gr(E.numHosts)})]},E.linkingDomain)),F.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-muted",colSpan:2,children:O>0&&H===0?`Every referring domain in this ${B} was a crawler/proxy host (${O} hidden).`:`No referring domains in this ${B}.`})})]})]})}),e.jsx(Ls,{page:J,pageSize:wa,visibleRows:F.length,totalRows:H,onPageChange:E=>f((E-1)*wa)})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:q})]})}}function Vx({projectName:t}){const s=Te({...dd({client:Y,path:{name:t}}),staleTime:ri}),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:ea(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:Bt()?"text-sm text-secondary":"text-sm text-muted",children:n.reason==="no-queries"?"Add queries to start tracking AI citations.":Bt()?Js:"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(Ve,{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(Ve,{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(Qx,{data:n}),e.jsx(zx,{data:n}),n.competitorGaps.length>0&&e.jsx(Jx,{data:n})]})}function Qx({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(Sa,{label:"Cited + mentioned",value:`${n} / ${s}`,helper:"In sources AND named in answer",tone:n>0?"positive":"neutral"}),e.jsx(Sa,{label:"Cited only",value:`${a} / ${s}`,helper:"In sources, not named in answer",tone:a>0?"positive-dim":"neutral"}),e.jsx(Sa,{label:"Mentioned only",value:`${r} / ${s}`,helper:"Named in answer, no source link",tone:r>0?"caution":"neutral"}),e.jsx(Sa,{label:"Invisible",value:`${o} / ${s}`,helper:"No engine cites or mentions",tone:o>0?"negative":"neutral"})]})}function Sa({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 zx({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(Wx,{}),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(Ln,{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(vl,{className:"inline h-3.5 w-3.5 text-mono-700","aria-label":"no data"}):e.jsx(Hx,{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 Wx(){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(Rn,{active:!0,tone:"cited"}),e.jsx("span",{children:"cited (in sources)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Rn,{active:!0,tone:"mentioned"}),e.jsx("span",{children:"mentioned (in answer)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Rn,{active:!1,tone:"cited"}),e.jsx(Rn,{active:!1,tone:"mentioned"}),e.jsx("span",{children:"neither"})]})]})}function Hx({provider:t}){const s=Yx(t);return e.jsxs("span",{className:"inline-flex items-center justify-center gap-1",title:s,children:[e.jsx(Rn,{active:t.cited,tone:"cited"}),e.jsx(Rn,{active:t.mentioned,tone:"mentioned"})]})}function Yx(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 Rn({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 Jx({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(Ve,{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(Ln,{provider:s.provider})}),e.jsx("td",{className:"text-neutral",children:s.citingCompetitors.join(", ")})]},`${s.queryId}::${s.provider}`))})]})})]})}const ro="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",fr="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",Bn=t=>t.kind==="project"?"Whole site":t.label,Vn={allMarkets:"All markets",browse:t=>`Browse ${t}`,select:t=>`Select ${t}`,browseAll:"Browse all properties"},Xx=t=>t?.kind==="group"&&t.marketKeys?.length===1?t.marketKeys[0]:void 0,io=t=>`${t} ${t===1?"property":"properties"}`;function _l({options:t,selected:s,onSelect:n,marketKey:a,label:r="Measurement scope",allowGroupSelect:o=!0}){const i=[...t].sort((T,ee)=>T.label.localeCompare(ee.label,void 0,{numeric:!0})||T.id.localeCompare(ee.id)),[c,d]=l.useState(""),[h,m]=l.useState([]),[u,b]=l.useState(!1),p=l.useRef(null),x=l.useRef(null),g=l.useId(),f=i.filter(T=>T.kind==="group"),S=new Map(f.map(T=>[T.id,T])),j=S.get(h.at(-1)??""),D=S.get(h.at(-2)??""),A=c.trim().toLocaleLowerCase(),y=f.filter(T=>!T.parentGroupIds?.some(ee=>S.has(ee))),w=i.filter(T=>T.kind==="property"),N=T=>(T.parentGroupIds??[]).map(ee=>S.get(ee)?.label).filter(Boolean).join(" · "),M=T=>`${Bn(T)} ${N(T)}`.toLocaleLowerCase().includes(A),L=T=>{const ee=[...T.parentGroupIds??[]],Z=new Set;for(;ee.length;){const ge=ee.pop();if(ge===j?.id)return!0;Z.has(ge)||(Z.add(ge),ee.push(...S.get(ge)?.parentGroupIds??[]))}return!1},F=(u?[]:j?f.filter(T=>A?L(T):T.parentGroupIds?.includes(j.id)):A?f:y).filter(M),H=i.find(T=>T.kind==="market"&&T.id===(a??(s.kind==="market"?s.id:void 0))),O=j&&H&&(j.marketKeys?.includes(H.id)||H.parentGroupIds?.includes(j.id))?H.id:void 0,J=o?O??Xx(j):void 0,G=(j?w.filter(T=>T.parentGroupIds?.includes(j.id)&&(!J||T.marketKeys?.includes(J))):A||u||f.length===0?w:[]).filter(M),C=i.filter(T=>T.kind!=="market"||u||!o&&!j&&!A&&f.length>0||o&&j?.marketKeys?.length===1&&!A?!1:(j?A?L(T):T.parentGroupIds?.includes(j.id):A||!T.parentGroupIds?.some(Z=>S.has(Z)))&&M(T)),ae=j||u?[]:i.filter(T=>T.kind==="project"&&M(T));l.useEffect(()=>{const T=ee=>{p.current?.open&&ee.target instanceof Node&&!p.current.contains(ee.target)&&(p.current.open=!1)};return document.addEventListener("pointerdown",T),()=>document.removeEventListener("pointerdown",T)},[]);const q=T=>{p.current&&(p.current.open=!1,p.current.querySelector("summary")?.focus());const ee=o?T.kind==="property"?J:T.kind==="group"&&T.id===j?.id?O:void 0:void 0;ee?n(T,ee):n(T)},se=T=>{const ee=[];let Z=S.get(T.parentGroupIds?.[0]??"");for(;Z&&!ee.includes(Z.id)&&Z.id!==T.id;)ee.unshift(Z.id),Z=S.get(Z.parentGroupIds?.[0]??"");return[...ee,T.id]},V=()=>{const T=s.kind==="group"?S.get(s.id):void 0,ee=S.get(H?.parentGroupIds?.[0]??""),Z=(s.parentGroupIds??[]).flatMap(de=>{const xe=S.get(de);return xe?[se(xe)]:[]}),ge=Z.find(de=>de.at(-1)===j?.id)??Z.sort((de,xe)=>xe.length-de.length)[0]??[],X=ee?se(ee):s.marketKeys?.length?[]:ge;m(T?se(T):X),b(s.kind==="property"&&X.length===0&&f.length>0),d("")},B=T=>{m(se(T)),b(!1),d(""),x.current?.focus()},E=(T,ee=Bn(T))=>e.jsxs("div",{className:"flex items-stretch",children:[e.jsxs("button",{type:"button",className:fr,"aria-label":T.kind==="group"&&!o?Vn.browse(Bn(T)):Vn.select(Bn(T)),"aria-current":s.kind===T.kind&&s.id===T.id?"true":void 0,onClick:()=>T.kind==="group"&&!o?B(T):q(T),children:[e.jsxs("span",{className:"min-w-0 break-words",children:[ee,A&&N(T)?e.jsx("span",{className:"block text-[13px] text-secondary",children:N(T)}):null]}),e.jsx("span",{className:"shrink-0 text-right text-[13px] text-secondary",children:T.kind==="market"?o?"Query context":"Market":T.kind==="property"?"Property":io(T.targetCount)})]}),o&&T.kind==="group"&&T.id!==j?.id&&i.some(Z=>Z.parentGroupIds?.includes(T.id))?e.jsx("button",{type:"button","aria-label":Vn.browse(T.label),title:`Browse ${T.label}`,className:"flex min-h-11 min-w-11 items-center justify-center rounded text-secondary hover:bg-surface-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>B(T),children:e.jsx(Ga,{size:18,"aria-hidden":"true"})}):null]},`${T.kind}:${T.id}`),R=(T,ee)=>ee.length>0?e.jsxs("section",{"aria-label":T,className:"mt-2",children:[e.jsx("h3",{className:"px-2 py-2 text-[13px] font-medium text-secondary",children:T}),ee.map(Z=>E(Z))]}):null,oe=(T,ee,Z)=>ee.length>0?e.jsxs("details",{open:Z,className:"mt-2 border-y border-default",children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer px-2 py-3 text-sm text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",children:[T," (",ee.length,")"]}),ee.map(ge=>E(ge))]},`${j?.id??"root"}:${T}`):null;return e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{id:`${g}-label`,className:"mb-1 block text-sm font-medium text-heading",children:r}),e.jsxs("details",{ref:p,className:"relative",onToggle:T=>{T.target===T.currentTarget&&T.currentTarget.open&&x.current?.focus()},onKeyDown:T=>{T.key==="Escape"&&(T.preventDefault(),T.currentTarget.open=!1,T.currentTarget.querySelector("summary")?.focus())},children:[e.jsxs("summary",{id:`${g}-value`,"aria-labelledby":`${g}-label ${g}-value`,className:`${ro} visibility-scope-trigger`,onClick:()=>{p.current?.open||V()},children:[`${Bn(s)}${s.kind==="group"?` · ${io(s.targetCount)}`:s.kind==="property"?` · ${i.find(T=>T.kind==="market"&&T.id===a)?.label??(s.marketKeys?.length?Vn.allMarkets:"Property")}`:s.kind==="market"?" · Market":""}`,e.jsx(gn,{size:16,"aria-hidden":"true",className:"shrink-0 text-secondary"})]}),e.jsxs("div",{className:"visibility-scope-menu",children:[j||u?e.jsxs("div",{className:"mb-2 border-b border-default pb-2",children:[e.jsx("button",{type:"button",className:fr,"aria-label":`Back to ${D?.label??"all groups"}`,onClick:()=>{m(h.slice(0,-1)),b(!1),d(""),x.current?.focus()},children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Gm,{size:16,"aria-hidden":"true"}),D?.label??"All groups"]})}),e.jsx("p",{className:"px-2 py-1 text-sm font-medium text-heading","aria-live":"polite",children:j?.label??"All properties"})]}):null,e.jsx("input",{ref:x,type:"search","aria-label":"Search scopes",className:ro,placeholder:j?"Search within this group":u?"Search properties":"Search groups or properties",value:c,onChange:T=>d(T.target.value)}),e.jsxs("div",{className:"mt-2 max-h-80 overflow-y-auto",children:[o&&j&&!A?E(j,"All properties in this group"):null,ae.map(T=>E(T)),j&&!A?oe("Subgroups",F,!0):R(j?"Subgroups":"Groups",F),A?R("Properties",G):oe(j&&F.length>0?"All properties":"Properties",G,!j||F.length===0),R("Markets",C),!j&&!u&&!A&&f.length>0&&w.length>0?e.jsxs("button",{type:"button",className:`${fr} mt-2 border-t border-default`,"aria-label":Vn.browseAll,onClick:()=>{b(!0),x.current?.focus()},children:[e.jsx("span",{children:"All properties"}),e.jsx(Ga,{size:18,"aria-hidden":"true"})]}):null,A&&F.length+G.length+C.length+ae.length===0?e.jsx("p",{className:"py-3 text-sm text-secondary",children:"No matching scopes."}):null]})]})]})]})}const ia="__cited__",oa="__mentioned__",cs="__mentionShare__";function Ul(t){const s=t,{dataStartDate:n,dataEndDate:a}=s;return typeof n!="string"||typeof a!="string"?null:{start:Es(n),end:Es(a),sweepCount:s.sweepCount??1}}function Va(t){const s=Ul(t);if(!s)return"Sweep date unavailable";const n=Ws(s.start),a=Ws(s.end);return n===a?n:`${n} – ${a} · ${s.sweepCount} sweeps combined`}function Zx(t){const s=Ul(t);return s?Sl(s.start):""}function En(t){return t.trim().toLowerCase()}function Qr(t){return Math.round(t*1e3)/10}function zr(t){return t.byProvider??{}}function ep(t,s,n){const a=t.buckets.length>0,r=t.buckets.length===1;if(n==="overall"){const d=s==="cited"?ia:oa,h=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(u=>({date:u.startDate,[d]:Qr(u[h])})),series:[d],hasData:a,singleBucket:r}}const o=s==="mentioned"?"mentionRate":"citationRate",i=[...new Set(t.buckets.flatMap(d=>Object.keys(zr(d))))].sort();return{rows:t.buckets.map(d=>{const h={date:d.startDate},m=zr(d);for(const u of i){const b=m[u];h[u]=b?Qr(b[o]):null}return h}),series:i,hasData:a,singleBucket:r}}function Bl(t){const s=t;return Object.hasOwn(s,"modelEvidenceByProvider")?s.modelEvidenceByProvider??{}:null}function tp(t){const s=t;return Object.hasOwn(s,"modelAttribution")?s.modelAttribution??{}:null}function sp(t){return t.servedModelAttribution??{}}function np(t){return t.modelServiceMismatch??{}}function ap(t){return t.modelPointerChanges??{}}function rp(t){return t.length>0?t.join(", "):null}function oo(t,s){const n=En(s);return Object.entries(t).find(([a])=>En(a)===n)?.[1]}function Is(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 ip(t,s){for(let n=t.length-1;n>=0;n-=1){const a=t[n];if(!oo(zr(a),s))continue;const r=Bl(a);return r?oo(r,s)??null:null}return null}function op(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 lp(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:op(s),beforeWindow:n.sort((a,r)=>a.event.observedAt.localeCompare(r.event.observedAt)||a.provider.localeCompare(r.provider))}}function cp(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 dp(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 up(t){const s=t.buckets.map(a=>{const r=a.mentionShare;return{date:a.startDate,[cs]:r?.rate==null?null:Qr(r.rate)}}),n=s.map(a=>a[cs]).filter(a=>typeof a=="number"&&Number.isFinite(a));return{rows:s,series:[cs],hasData:n.length>0,singleBucket:n.length===1}}function mp(t,s,n){return s==="mentionShare"?up(t):ep(t,s,n)}function lo(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 co(t){const[,s,n]=t.slice(0,10).split("-");return!s||!n?t:`${s}/${n}`}function uo(t){return t>0?`+${t}`:`${t}`}function hp(t){if(t.length===0)return null;if(t.length<=2)return`Query set changed: ${t.map(n=>`${uo(n.delta)} on ${co(n.date)}`).join(", ")}`;const s=[...t].sort((n,a)=>a.date.localeCompare(n.date))[0];return`Query set changed ${t.length} times (latest ${uo(s.delta)} on ${co(s.date)})`}const xp=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],mo="Measured answers",pp="Close answers",Ts={"non-brand":"Non-brand queries",branded:"Branded queries",unknown:"Unclassified queries"},In="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",Wr=new Intl.NumberFormat("en",{style:"percent",maximumFractionDigits:1});function gp(t){return t.kind==="project"?"Whole site":t.kind==="group"?`${t.label} · Group`:t.kind==="market"?`${t.label} · Market`:t.label}function Cs({value:t,unit:s}){return t.rate===null?e.jsx("span",{className:"text-sm text-secondary",children:t.reason==="identity-ambiguous"?Et.ambiguous: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:Wr.format(t.rate)}),e.jsxs("span",{className:"text-sm tabular-nums text-secondary",children:[t.numerator," of ",t.denominator,s?` ${s}`:""]})]})}const fp={otherQueries:"Other queries"};function yp(t,s){const n=new Map;for(const r of t){const o=n.get(r.queryKey);o?o.rows.push(r):n.set(r.queryKey,{queryKey:r.queryKey,query:r.query,rows:[r]})}const a=[...n.values()];if(!s||!t.some(r=>r.marketKeys?.length))return a;for(const r of a){const o=[...new Set(r.rows.flatMap(i=>i.marketKeys??[]))].sort();r.marketLabel=o.map(i=>s.get(i)??i).join(" · ")||fp.otherQueries}return a.sort((r,o)=>r.marketLabel.localeCompare(o.marketLabel)||r.query.localeCompare(o.query))}function ho({value:t,singleAnswer:s}){if(s&&t.denominator===1&&(t.rate===0||t.rate===1)){const n=t.rate===1;return e.jsxs("span",{className:`inline-flex items-center gap-2 text-sm ${n?"text-positive":"text-secondary"}`,children:[n?e.jsx(_m,{size:16,"aria-hidden":"true"}):e.jsx(vl,{size:16,"aria-hidden":"true"}),n?"Yes":"No"]})}return e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Cs,{value:t}),t.reason==="evidence-incomplete"?e.jsx(Ve,{text:"The saved evidence is incomplete, so this result cannot be measured. It does not mean the answer had no citation."}):null]})}function xo({targetKeys:t,labels:s}){return t.length===0?e.jsx("span",{children:"No assigned properties"}):t.length===1?e.jsx("span",{children:s.get(t[0])??t[0]}):e.jsxs("details",{children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-3 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",children:[t.length," properties"]}),e.jsx("ul",{className:"max-h-48 space-y-2 overflow-y-auto pb-3",children:t.map(n=>e.jsx("li",{children:s.get(n)??n},n))})]})}function bp({group:t,advanced:s,targetLabels:n,marketHeading:a,onViewAnswers:r}){const o=t.rows[0],i=m=>JSON.stringify([...m.targetKeys].sort()),c=t.rows.every(m=>i(m)===i(o)),d=t.rows.every(m=>m.location===o.location),h=m=>m===null?"No location targeting":`Search location: ${m}`;return e.jsxs("tbody",{"data-query-key":t.queryKey,children:[a?e.jsx("tr",{children:e.jsx("th",{colSpan:4,className:"border-t border-default py-4 text-left",children:e.jsx("h3",{className:"text-base font-semibold text-heading",children:a})})}):null,e.jsx("tr",{className:"measurement-result-heading",children:e.jsxs("th",{scope:"rowgroup",colSpan:4,children:[e.jsx("h3",{className:"break-words text-base font-medium text-heading",children:t.query}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 text-sm font-normal text-secondary",children:[s&&c?e.jsx(xo,{targetKeys:o.targetKeys,labels:n}):null,d?e.jsx("span",{children:h(o.location)}):null]})]})}),t.rows.map(m=>e.jsxs("tr",{className:"measurement-engine-result",children:[e.jsxs("td",{className:"measurement-result-engine",children:[e.jsx("span",{className:"font-medium text-heading",children:ks(m.provider)}),e.jsx("span",{className:"block break-words text-sm text-secondary",children:m.model??"Model not recorded"}),s&&!c?e.jsx("div",{className:"mt-1 text-sm text-secondary",children:e.jsx(xo,{targetKeys:m.targetKeys,labels:n})}):null,d?null:e.jsx("span",{className:"mt-1 block text-sm text-secondary",children:h(m.location)})]}),e.jsxs("td",{children:[e.jsx("span",{className:"measurement-result-mobile-label","aria-hidden":"true",children:"Mentioned"}),e.jsx(ho,{value:m.mentionCoverage,singleAnswer:m.answerCount===1})]}),e.jsxs("td",{children:[e.jsx("span",{className:"measurement-result-mobile-label","aria-hidden":"true",children:"Cited"}),e.jsx(ho,{value:m.citationCoverage,singleAnswer:m.answerCount===1})]}),e.jsx("td",{className:"measurement-result-action",children:e.jsxs(P,{variant:"ghost",className:"min-h-11","aria-label":`View answers for ${m.query} · ${m.provider}`,onClick:u=>r(m,u.currentTarget),children:[m.answerCount===1?"View answer":"View answers",e.jsx(Ga,{size:16,"aria-hidden":"true"})]})})]},JSON.stringify([m.provider,m.model,m.location])))]})}function vp({population:t}){const s=l.useId();let n=0;const a=t.trend.map((d,h)=>(h>0&&d.continuity.state!=="comparable"&&(n+=1),{createdAt:Date.parse(d.createdAt),[`mentioned-${n}`]:d.mentionCoverage.rate,[`cited-${n}`]:d.citationCoverage.rate})),r=Array.from({length:n+1},(d,h)=>h),o=new Set(t.trend.slice(1).map(d=>d.continuity.state)),i=[...a.length===1?["First measurement. A trend appears after another comparable run."]:[],...o.has("definition-changed")?["Gaps mark changes to what was measured."]:[],...o.has("model-changed")?["Gaps mark changes to answer engines or models."]:[],...o.has("legacy-unknown")?["Older runs lack the details needed for comparison."]:[],...t.trend.some(d=>d.citationCoverage.reason==="evidence-incomplete")?["Missing citation results mean the saved evidence is incomplete."]:[]];if(a.length===0)return e.jsx("p",{className:"py-6 text-sm text-secondary",children:"No measured trend for this selection."});const c=t.trend.some(d=>d.mentionCoverage.rate!==null||d.citationCoverage.rate!==null);return e.jsxs(e.Fragment,{children:[c?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:rt[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:qs.positive}}),"Cited"]})]}),i.length>0&&e.jsx("p",{id:s,className:"pb-3 text-sm text-secondary",children:i.join(" ")}),e.jsx("div",{className:"visibility-trend-chart",role:"img","aria-describedby":i.length>0?s:void 0,"aria-label":`${Ts[t.queryClass]} mention and citation trend`,children:e.jsx(Xs,{width:"100%",height:"100%",children:e.jsxs(Zs,{data:a,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(na,{stroke:sa,vertical:!1}),e.jsx(en,{dataKey:"createdAt",type:"number",scale:"time",domain:["dataMin","dataMax"],tick:Ft,tickLine:!1,axisLine:{stroke:ds},tickFormatter:d=>new Date(Number(d)).toLocaleDateString(void 0,{month:"short",day:"numeric"}),minTickGap:24}),e.jsx(tn,{domain:[0,1],tick:Ft,tickLine:!1,axisLine:!1,width:48,tickFormatter:d=>Wr.format(Number(d))}),e.jsx(sn,{...ts,formatter:d=>typeof d=="number"?Wr.format(d):"Not measured",labelFormatter:d=>new Date(Number(d)).toLocaleDateString()}),r.map(d=>e.jsxs(l.Fragment,{children:[e.jsx(Ms,{type:"linear",dataKey:`mentioned-${d}`,name:"Mentioned",stroke:rt[1],strokeWidth:2,connectNulls:!1,isAnimationActive:!1,dot:{r:3}}),e.jsx(Ms,{type:"linear",dataKey:`cited-${d}`,name:"Cited",stroke:qs.positive,strokeWidth:2,connectNulls:!1,isAnimationActive:!1,dot:{r:3}})]},d))]})})})]}):e.jsx("p",{className:"py-6 text-sm text-secondary",children:"No measured trend for this selection."}),e.jsx("div",{className:c?"sr-only":"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table","aria-label":`${Ts[t.queryClass]} trend data`,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(d=>e.jsxs("tr",{children:[e.jsx("td",{children:new Date(d.createdAt).toLocaleDateString()}),e.jsx("td",{children:e.jsx(Cs,{value:d.mentionCoverage})}),e.jsx("td",{children:e.jsx(Cs,{value:d.citationCoverage})}),e.jsx("td",{children:d.continuity.state.replaceAll("-"," ")})]},d.runId))})]})})]})}function Hr(t,s){return s?t?.populations.find(n=>[...n.queries.items,...n.evidence.items].some(a=>a.queryKey===s)):void 0}function li(t,s,n,a){const r=t.selection.queryClass==="all"?n?.queryClass:t.selection.queryClass,o=t.populations.find(h=>h.queryClass===r);if(o)return o;const i=Hr(a,s)??Hr(t,s),c=t.populations.find(h=>h.queryClass===i?.queryClass);if(c)return c;const d=["non-brand","branded","unknown"].map(h=>t.populations.find(m=>m.queryClass===h));return d.find(h=>h&&(h.summary.queryCount>0||h.trend.some(m=>m.queryCount>0)))??d.find(h=>h!==void 0)??t.populations[0]}function jp({report:t,onSelectionChange:s,queryClass:n=li(t).queryClass}){const{selection:a,scopeOptions:r,filterOptions:o}=t,i=(c,d,h,m)=>e.jsxs("label",{className:"min-w-0",children:[e.jsx("span",{className:"mb-1 block text-sm font-medium text-heading",children:c}),e.jsx("select",{"aria-label":c,className:In,value:h,onChange:u=>s({[d]:u.target.value||void 0,measurementQueryKey:void 0}),children:m.map(u=>e.jsx("option",{value:u.value,children:u.label},u.value))})]});return e.jsx("div",{className:"visibility-filter-container",children:e.jsxs("div",{className:"visibility-report-filters","data-has-scope":r.length>1,role:"group","aria-label":"Visibility filters",children:[r.length>1?e.jsx(_l,{options:r,selected:a.scope,marketKey:a.market?.id,onSelect:(c,d)=>{s({measurementScope:c.kind,measurementScopeKey:c.kind==="project"?void 0:c.id,measurementMarketKey:d})}}):null,i("Query type","queryClass",n,[{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"},{value:"unknown",label:"Unclassified"}]),i("Answer engine","measurementProvider",a.provider??"",[{value:"",label:"All engines"},...o.providers.map(c=>({value:c,label:c}))]),i("Search location","measurementLocation",a.location.kind==="exact"?a.location.value:a.location.kind==="none"?"none":"",[{value:"",label:"All locations"},...o.locations.filter(c=>c.kind!=="all").map(c=>({value:c.kind==="exact"?c.value:"none",label:c.kind==="exact"?c.value:"No location"}))])]})})}function Np({report:t,isRefreshing:s=!1,onSelectionChange:n,onManageQueries:a,onPage:r,onSearch:o,search:i="",queryKey:c,answerSelection:d,evidenceReport:h,isEvidenceLoading:m=!1,evidenceError:u,onRetryEvidence:b,onEvidencePage:p}){const x=l.useRef(null),g=l.useRef(void 0),f=l.useRef(null),S=li(t,c,d,h),j=h??t,D=j.populations.filter(C=>[...C.queries.items,...C.evidence.items].some(ae=>ae.queryKey===c)),A=d?[d.queryClass]:(D.length?D:m?[]:[S]).map(C=>C.queryClass),y=c?JSON.stringify([d??c,A]):void 0,w=l.useId();l.useEffect(()=>{if(!y){s||(g.current=void 0);return}if(g.current===y)return;const C=x.current?.querySelectorAll(`[aria-label="${mo}"]`);if(C?.length){for(const ae of C){const q=ae.closest("details[data-query-results]");q&&(q.open=!0)}C[0].focus({preventScroll:!0}),C[0].scrollIntoView?.({block:"start"}),g.current=y}},[y,s]);const{selection:N,filterOptions:M}=t,L=N.measurement,F=gp(N.scope),H=new Map(t.scopeOptions.filter(C=>C.kind==="property").map(C=>[C.id,C.label])),O=C=>{const ae=j.populations.find(q=>q.queryClass===C.queryClass)?.evidence;return{items:ae?.items.filter(q=>q.queryKey===c&&(!d||q.provider===d.provider&&q.model===d.model&&q.location===d.location&&(d.runId===null||q.runId===d.runId)))??[],nextCursor:ae?.nextCursor}},J=()=>{g.current=void 0;const C=f.current;C!==null&&C.row.queryKey===c&&(!d||C.row.provider===d.provider&&C.row.model===d.model&&C.row.location===d.location)&&C?.element.isConnected?C.element.focus():x.current?.querySelector(`details[data-query-results="${S.queryClass}"] > summary`)?.focus(),n({measurementQueryKey:void 0,measurementAnswer:void 0})},G=(C,ae,q,se,V)=>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:`${w}-${ae}`,className:"text-sm font-medium text-heading",children:C}),e.jsx(Ve,{text:V})]}),e.jsx("select",{id:`${w}-${ae}`,className:In,value:q,onChange:B=>n({[ae]:B.target.value||void 0,measurementQueryKey:void 0}),children:se.map(B=>e.jsx("option",{value:B.value,children:B.label},B.value))})]});return e.jsxs("section",{ref:x,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(ue,{tone:L.state==="measured"?"positive":"neutral",children:L.state==="measured"?"Complete":L.state==="partial"?"Partial":"Not measured"}),L.completedAt?e.jsx("span",{className:"text-sm text-secondary",children:new Date(L.completedAt).toLocaleDateString()}):null]}),a?e.jsx(P,{variant:"outline",onClick:a,children:"Manage queries"}):null]}),N.provenance.kind==="legacy-simple"&&N.queryClass!=="unknown"&&N.queryClass!=="all"?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:"These saved results aren't separated by query type."}),e.jsx(P,{variant:"outline",onClick:()=>n({queryClass:"all",measurementQueryKey:void 0}),children:"View all saved results"})]}):null,e.jsx(jp,{report:t,queryClass:S.queryClass,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:In,value:N.time.from?.slice(0,10)??"",onChange:C=>n({measurementFrom:C.target.value?`${C.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:In,value:N.time.to?.slice(0,10)??"",onChange:C=>n({measurementTo:C.target.value?`${C.target.value}T23:59:59.999Z`:void 0})})]}),G("AI model","measurementModel",N.model??"",[{value:"",label:"All models"},...Array.from(new Set(M.models.filter(C=>!N.provider||C.provider===N.provider).map(C=>C.model))).map(C=>({value:C,label:C}))],"Filter by the AI model recorded with each answer. This does not change the model used by future sweeps."),G("Results from","measurementRunId",N.run.explicit?N.run.id??"":"",[{value:"",label:"Latest saved sweep"},...[...S.trend].reverse().map(C=>({value:C.runId,label:new Date(C.createdAt).toLocaleString()}))],"Choose a saved AI sweep to view its results. No new sweep starts.")]})]}),[S].map(C=>{const ae=yp(C.queries.items,N.scope.kind==="property"&&!N.market&&C.queryClass==="non-brand"?new Map(t.scopeOptions.filter(V=>V.kind==="market").map(V=>[V.id,V.label])):void 0),q=O(C),se=q.items[0]?.query??C.queries.items.find(V=>V.queryKey===c)?.query;return e.jsxs("section",{"aria-label":Ts[C.queryClass],className:"py-4",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("h2",{children:Ts[C.queryClass]}),e.jsx(Ve,{text:C.queryClass==="non-brand"?"Queries that do not name the measured identity. Geography alone is not a brand.":C.queryClass==="branded"?"Queries that name the measured identity.":"These queries were not labeled as branded or non-brand when measured. Their saved results remain available here, separate from branded and 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:N.mode==="advanced"&&N.scope.kind!=="property"?"Answers mentioning a property":"Mentioned answers"}),N.mode==="advanced"?e.jsx(Ve,{text:"An answer counts when it mentions any assigned property. This does not mean every property was mentioned."}):null]}),e.jsx(Cs,{value:C.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:N.mode==="advanced"&&N.scope.kind!=="property"?"Answers citing a property":"Cited answers"}),N.mode==="advanced"?e.jsx(Ve,{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(Cs,{value:C.summary.citationCoverage,unit:"answers"})]}),N.mode==="advanced"&&N.scope.kind!=="property"?e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-sm text-secondary",children:"Properties mentioned"}),e.jsx(Cs,{value:C.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:C.summary.queryCount})]})]}),e.jsx(vp,{population:C}),N.mode==="advanced"?e.jsxs("details",{className:"border-t border-default text-sm text-secondary","aria-label":`${Ts[C.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(([V,B])=>e.jsxs("div",{children:[e.jsx("strong",{className:"block tabular-nums text-heading",children:C.summary.outcomes[V]}),e.jsx("span",{className:"text-sm text-secondary",children:B}),V==="notMeasured"?e.jsx(Ve,{text:"No eligible completed measurement for this selection. This is not the same as a measured answer with neither signal."}):null]},V))})]}):null,N.mode==="advanced"&&N.scope.kind!=="property"&&(C.breakdown.groups.length>0||C.breakdown.properties.length>0)?e.jsx(wp,{population:C,scope:N.scope,scopeOptions:t.scopeOptions,marketKey:N.market?.id,onSelectionChange:n},`${N.scope.kind}:${N.scope.id}`):null,e.jsxs("details",{className:"border-t border-default","data-query-results":C.queryClass,"aria-label":`${Ts[C.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:[C.queries.total," ",C.queries.total===1?"result":"results"," · ",F]})]}),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 ${Ts[C.queryClass]}`,placeholder:"Search queries",className:`${In} max-w-sm`,value:i,onChange:V=>o(V.target.value)}):null,e.jsx(Ve,{text:N.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 measurement-results-table","aria-label":`${Ts[C.queryClass]} engine results`,children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Answer engine"}),e.jsx("th",{scope:"col",children:"Mentioned"}),e.jsx("th",{scope:"col",children:"Cited"}),e.jsx("th",{scope:"col",children:e.jsx("span",{className:"sr-only",children:"Evidence"})})]})}),ae.map((V,B)=>e.jsx(bp,{group:V,marketHeading:V.marketLabel!==ae[B-1]?.marketLabel?V.marketLabel:void 0,advanced:N.mode==="advanced",targetLabels:H,onViewAnswers:(E,R)=>{f.current={row:E,element:R},n({measurementQueryKey:E.queryKey,measurementAnswer:JSON.stringify({queryKey:E.queryKey,queryClass:C.queryClass,provider:E.provider,model:E.model,location:E.location,runId:N.run.id,revision:N.revision})})}},V.queryKey))]})}),C.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:[ae.length," ",ae.length===1?"query":"queries"," · ",C.queries.items.length," ",C.queries.items.length===1?"engine result":"engine results"," shown of ",C.queries.total," results"]}),C.queries.nextCursor&&r?e.jsx(P,{variant:"outline",onClick:()=>r(C.queries.nextCursor),children:"Next queries"}):null,c&&A.includes(C.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":mo,"aria-busy":m,children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsx("h3",{className:"min-w-0 flex-1 text-base font-semibold text-heading [overflow-wrap:anywhere]",children:se??"Answers"}),e.jsx(P,{variant:"ghost",className:"min-h-11",onClick:J,children:pp})]}),m?e.jsx("p",{role:"status",className:"py-4 text-sm text-secondary",children:"Loading saved answers…"}):u?e.jsxs("div",{role:"alert",className:"py-4 text-sm text-secondary",children:[e.jsxs("p",{children:["Saved answers unavailable: ",u]}),b?e.jsx(P,{variant:"outline",onClick:b,children:"Retry answers"}):null]}):e.jsxs(e.Fragment,{children:[q.items.map(V=>e.jsxs("article",{className:"border-b border-default py-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-2",children:[e.jsx("strong",{className:"text-sm text-heading",children:V.provider}),V.model?e.jsx("span",{className:"text-[13px] text-secondary",children:V.model}):null,e.jsx("span",{className:"text-[13px] text-secondary",children:V.location??"No location"}),e.jsx("span",{className:"text-[13px] text-secondary",children:new Date(V.createdAt).toLocaleDateString()}),e.jsx(ue,{tone:"neutral",children:V.mentioned===null?V.mentionUnavailableReason==="identity-ambiguous"?Et.ambiguous:"Mention not checked":V.mentioned?"Mentioned":"Not mentioned"}),e.jsx(ue,{tone:"neutral",children:V.cited===null?"Citation not checked":V.cited?"Cited":"Not cited"})]}),e.jsx("div",{className:"mt-4",children:e.jsx(Cl,{headingLevel:4,copyable:!!V.answerText?.trim(),children:V.answerText??"Answer text unavailable."})}),V.sources.length>0?e.jsxs("details",{className:"mt-2","data-answer-sources":!0,children:[e.jsxs("summary",{className:"min-h-11 cursor-pointer py-3 text-sm text-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",children:[th," (",V.sources.length,")"]}),e.jsx("ul",{className:"space-y-2 pb-3",children:V.sources.map(B=>{const E=_s(B);return e.jsx("li",{className:"break-all text-sm",children:E?e.jsx("a",{href:E,target:"_blank",rel:"noopener noreferrer",className:"text-link underline",children:B}):e.jsx("span",{className:"text-secondary",children:B})},B)})})]}):null]},V.answerId)),O(C).items.length===0?e.jsx("p",{className:"py-4 text-sm text-secondary",children:O(C).nextCursor?"No matching answers on this page. Continue to the next answers.":"No matching saved answers on this page."}):null,O(C).nextCursor&&p?e.jsx(P,{variant:"outline",onClick:()=>p(O(C).nextCursor),children:"Next answers"}):null]})]}):null]})]}),e.jsxs("details",{className:"border-t border-default","aria-label":`${Ts[C.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:C.competitorAvailability.state==="unavailable"?"Not available":`${C.competitors.length} measured`})]}),e.jsxs("div",{className:"pb-5",children:[C.competitorAvailability.state==="unavailable"?e.jsx("p",{className:"text-sm text-secondary",children:"Competitor rates unavailable for this historical definition."}):C.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:C.competitors.map(V=>e.jsxs("tr",{children:[e.jsx("td",{children:V.domain}),e.jsx("td",{children:e.jsx(Cs,{value:V.mentionCoverage})}),e.jsx("td",{children:e.jsx(Cs,{value:V.citationCoverage})})]},V.domain))})]})}),C.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:C.observedCompetitors.map(V=>e.jsxs("li",{className:"flex items-center justify-between gap-4 py-3",children:[e.jsx("span",{children:V.name}),e.jsxs("span",{className:"tabular-nums text-secondary",children:[V.answerCount," ",V.answerCount===1?"answer":"answers"]})]},V.name))}),e.jsx("p",{className:"py-2 text-secondary",children:"Observed names, not additions to your tracked competitors."})]}):null]})]})]},C.queryClass)})]})}function wp({population:t,scope:s,scopeOptions:n,marketKey:a,onSelectionChange:r}){const o=new Map(n.filter(u=>u.kind==="group").map(u=>[u.id,u])),i=[...o.values()].some(u=>u.parentGroupIds?.length),c=t.breakdown.groups.filter(u=>{const b=o.get(u.id)?.parentGroupIds??[];return s.kind==="project"?b.length===0:s.kind==="group"&&i?b.includes(s.id):!0}),[d,h]=l.useState(()=>s.kind==="project"&&c.length>0?"groups":"properties"),m=fn({rows:d==="groups"?c:t.breakdown.properties,getSearchText:u=>u.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(u=>e.jsx(P,{variant:d===u?"secondary":"ghost",onClick:()=>{h(u),m.setPage(1)},children:u==="groups"?"Groups":"Properties"},u))}),e.jsx("input",{type:"search","aria-label":"Search breakdown",placeholder:"Search",value:m.query,onChange:u=>m.setQuery(u.target.value),className:`${In} 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:d==="groups"?"Group":"Property"}),e.jsx("th",{children:"Queries"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"})]})}),e.jsx("tbody",{children:m.rows.map(u=>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:()=>r({measurementScope:d==="groups"?"group":"property",measurementScopeKey:u.id,measurementMarketKey:a}),children:u.label})}),e.jsx("td",{children:u.queryCount}),e.jsx("td",{children:e.jsx(Cs,{value:u.mentionCoverage})}),e.jsx("td",{children:e.jsx(Cs,{value:u.citationCoverage})})]},u.id))})]})}),m.rows.length===0?e.jsxs("p",{className:"py-3 text-sm text-secondary",children:["No ",d," match this search."]}):null,e.jsx(Ls,{page:m.page,pageSize:m.pageSize,visibleRows:m.rows.length,totalRows:m.totalRows,itemLabel:d,onPageChange:m.setPage})]})}function Sp({projectName:t,selection:s,onSelectionChange:n,onManageQueries:a,fallback:r,showUnmeasuredFallback:o=!1}){const[i,c]=l.useState(),[d,h]=l.useState(""),[m,u]=l.useState(),b=ms(),p=l.useMemo(()=>({scope:s.measurementScope,scopeKey:s.measurementScopeKey,marketKey:s.marketKey,queryClass:s.queryClass,provider:s.provider,model:s.model,location:s.location,from:s.from,to:s.to,revision:s.revision,runId:s.measurementRunId}),[s.measurementScope,s.measurementScopeKey,s.marketKey,s.queryClass,s.provider,s.model,s.location,s.from,s.to,s.revision,s.measurementRunId]),x=Te({...tr({client:Y,path:{name:t},query:{...p,limit:25,cursor:i,search:d||void 0}}),staleTime:hd,retry:!1,placeholderData:ni}),g={...p,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??x.data?.selection.run.id??s.measurementRunId,revision:s.answer?.revision??x.data?.selection.revision??s.revision,limit:50},f=JSON.stringify(g),S=Te({...tr({client:Y,path:{name:t},query:{...g,cursor:m?.selection===f?m.cursor:void 0}}),enabled:!!s.queryKey&&!!x.data&&!x.isPlaceholderData,retry:!1});if(l.useEffect(()=>{if(s.queryClass!=="all"||!x.data||x.isPlaceholderData||x.isFetching||x.isError||x.data.selection.availability.state==="unsupported"||x.data.populations.length===0||s.queryKey&&!s.answer&&!Hr(x.data,s.queryKey)&&!S.data)return;const j=li(x.data,s.queryKey,s.answer,S.data);if(!i&&!d){const{queryKey:D}=tr({client:Y,path:{name:t},query:{...p,queryClass:j.queryClass,limit:25}});b.setQueryData(D,{...x.data,selection:{...x.data.selection,queryClass:j.queryClass},populations:[j]},{updatedAt:x.dataUpdatedAt})}n({queryClass:j.queryClass,...s.queryKey?{measurementQueryKey:s.queryKey,measurementAnswer:s.answer?JSON.stringify(s.answer):void 0}:{}})},[s.queryClass,s.queryKey,s.answer,x.data,x.dataUpdatedAt,x.isPlaceholderData,x.isFetching,x.isError,S.data,n,b,t,p,i,d]),x.data?.selection.availability.state==="unsupported")return e.jsx(e.Fragment,{children:r});if(o&&x.data?.selection.mode==="simple"&&x.data.selection.measurement.state==="not-measured")return e.jsx(e.Fragment,{children:r});if(x.error){const j=ea(x.error),D=s.measurementScope!=="project"&&j.includes("scope")&&j.includes("is not in this frozen definition.");return 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:D?"This saved group or property filter is unavailable for this measurement. Show the whole site to choose another.":j}),D?e.jsx(P,{variant:"outline",onClick:()=>{c(void 0),n({measurementScope:"project",measurementScopeKey:void 0})},children:"Show whole site"}):e.jsx(P,{variant:"outline",onClick:()=>{c(void 0),x.refetch()},children:"Retry"})]})}return x.data?e.jsx("div",{"aria-busy":x.isFetching,children:e.jsx(Np,{report:x.data,isRefreshing:x.isFetching,queryKey:s.queryKey,answerSelection:s.answer,evidenceReport:S.data,isEvidenceLoading:S.isFetching||!!s.queryKey&&S.isPending,evidenceError:S.error?ea(S.error):void 0,onRetryEvidence:()=>{S.refetch()},onEvidencePage:S.isFetching?void 0:j=>u({selection:f,cursor:j}),search:d,onSearch:j=>{h(j),c(void 0)},onPage:x.isFetching?void 0:c,onSelectionChange:j=>{(!("measurementQueryKey"in j)||Object.keys(j).some(D=>D!=="measurementQueryKey"&&D!=="measurementAnswer"))&&c(void 0),u(void 0),n(j)},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 Cp=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],kp=[{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."}],ci=rt[2],Ap="var(--chart-tooltip-bg)",Pp={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",local:"Local"};function ks(t){const s=En(t);return Pp[s]??t.charAt(0).toUpperCase()+t.slice(1)}function Vs(t){return Math.round(t*10)/10}function Rp(t){return t===ia||t===oa||t===cs}function Vl(t){return t===ia?"Cited":t===oa?"Mentioned":t===cs?"Mention share":ks(t)}function Wn(t,s){return t===ia?qs.positive:t===oa?rt[1]:t===cs?ci:Wm(En(t),s)}function Ip(t,s){for(const n of t){const a=n[s];if(typeof a=="number"&&Number.isFinite(a))return a}return null}function Tp(t){return t.map(s=>s.trim().toLowerCase()).filter(Boolean).sort().join(`
2
2
  `)}function Ya(t){return t==="non-brand"?"non-brand queries":"pooled queries · classification unavailable"}function Ea(t,s){return t==="cited"?"Cited":t==="mentionShare"?s?`Mention share · ${Ya(s)}`:"Mention share":"Mentioned"}function aa(t){return t==="cited"?"citationRate":"mentionRate"}function Ql(t,s){return s==="cited"?t.cited:t.mentionedCount}function zl(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 Wl(t,s){if(s===void 0)return null;const n=String(s);return t.find(a=>a.startDate===n)??null}function Yr(t){const s=Bl(t);if(s===null)return"Model attribution unavailable for this bucket.";const n=Object.entries(s).sort(([a],[r])=>En(a).localeCompare(En(r))).map(([a,r])=>`${ks(a)}: ${Is(r)}`);return n.length>0?`Model evidence: ${n.join("; ")}`:"No model evidence in this bucket."}function $p(t){return t.some(({event:s})=>s.to.status==="mixed")?qs.caution:t.some(({event:s})=>s.to.status==="unknown")?qs.negative:t.every(({event:s})=>s.from.status==="known"&&s.to.status==="known")?rt[4]:qs.positive}function Mp(t,s,n){const a=Wl(t,s);return a?Va(a):Ws(Es(n))}function Lp({partition:t,available:s,counts:n,truncated:a,incompleteHistory:r,served:o,mismatch:i,buckets:c}){const d=l.useId(),h=Object.entries(o).sort(([u],[b])=>u.localeCompare(b)),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":d,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:d,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:u,events:b})=>b.map(({provider:p,event:x})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:Mp(c,u,x.observedAt)}),e.jsxs("span",{children:[ks(p),": ",Is(x.from)," → ",Is(x.to)]})]},`${p}-${x.observedAt}-${x.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:u,event:b})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsxs("span",{className:"trend-model-evidence-date",children:["on or before ",Ws(Es(b.observedAt))]}),e.jsxs("span",{children:[ks(u),": ",Is(b.from)," → ",Is(b.to),b.anchorObservedAt?` (last seen ${Is(b.from)} on ${Ws(Es(b.anchorObservedAt))})`:""]})]},`before-${u}-${b.observedAt}`))})]}),a.map(u=>e.jsxs("p",{className:"trend-model-evidence-note",children:[ks(u.provider),": showing the most recent ",u.shown," of ",u.total," changes."]},`truncated-${u.provider}`)),r.map(u=>e.jsxs("p",{className:"trend-model-evidence-note",children:["We did not look far enough back to be sure this is every ",ks(u)," change."]},`incomplete-${u}`)),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(([u,b])=>{const p=rp(b.latestServedModelIds),x=i[u];return e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:Ws(Es(b.latestObservation.observedAt))}),e.jsxs("span",{children:[ks(u),": ",p??Is(b.latestObservation.state),x?` — not the ${Is(x.configured)} you selected`:""]})]},`served-${u}`)})})]})]})}function po(t){return t===null?"no data":`${t}%`}function yr(t){return t==null?"undefined":`${Vs(t*100)}%`}function qp({active:t,label:s,payload:n,metric:a,mode:r,buckets:o}){if(!t)return null;const i=Wl(o,s);if(!i)return null;if(a==="mentionShare"){const d=i.mentionShare.projectMentionSnapshots,h=i.mentionShare.competitorMentionSnapshots,m=d+h,u=i.mentionShare.rate==null?null:Vs(i.mentionShare.rate*100);return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:Va(i)}),e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch trend-tooltip-swatch-ring",style:{borderColor:ci},"aria-hidden":"true"}),e.jsxs("span",{className:"trend-tooltip-name",children:["Mention share · ",Ya(i.mentionShare.scope)]}),e.jsx("span",{className:"trend-tooltip-value",children:po(u)})]}),m>0?e.jsxs("p",{className:"trend-tooltip-detail",children:["You ",d," / ",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:Yr(i)})]})}const c=r==="byProvider"?(n??[]).filter(d=>d.dataKey!==void 0):[{dataKey:a==="cited"?ia:oa,value:Vs(i[aa(a)]*100)}];return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:Va(i)}),c.map((d,h)=>{const m=String(d.dataKey??d.name??""),u=r==="byProvider"?zl(i,m,a):null,b=u?.count??Ql(i,a),p=u?.total??i.total,x=typeof d.value=="number"?d.value:Vs(u?u.rate*100:i[aa(a)]*100),g=d.color??Wn(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:g},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:Vl(m)}),e.jsx("span",{className:"trend-tooltip-value",children:po(x)})]}),e.jsxs("p",{className:"trend-tooltip-detail",children:[b," / ",p," snapshots, ",a==="cited"?"source links":"answer text"]})]},`${m}-${h}`)}),e.jsx("p",{className:"trend-tooltip-detail",children:Yr(i)})]})}function Ep({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:[Ea(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,d=o.mentionShare.competitorMentionSnapshots,h=c+d,m=Ya(o.mentionShare.scope);i=h>0?`${yr(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 d=zl(o,c,s);return d?`${ks(c)} ${yr(d.rate)} ${Ea(s).toLowerCase()}, ${d.count} of ${d.total} snapshots`:`${ks(c)} no data`}).join("; "):i=`${yr(o[aa(s)])} ${Ea(s).toLowerCase()}, ${Ql(o,s)} of ${o.total} snapshots`;return i+=`; ${Yr(o)}`,e.jsxs("tr",{children:[e.jsx("th",{scope:"row",children:Va(o)}),e.jsx("td",{children:i})]},o.startDate)})})]})}function br({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,d=i.description?`${o}-${i.value}-description`:void 0;return e.jsxs(l.Fragment,{children:[e.jsx("button",{type:"button","aria-pressed":c,"aria-describedby":d,className:`segmented-option ${c?"segmented-option-active":""}`,onClick:()=>n(i.value),children:i.label}),i.description&&e.jsx("span",{id:d,className:"sr-only",children:i.description})]},i.value)})})}function Dp({projectName:t,competitorDomains:s=[],analyticsRevision:n="none"}){const[a,r]=l.useState("all"),[o,i]=l.useState("mentioned"),[c,d]=l.useState("byProvider"),h=l.useMemo(()=>Tp(s),[s]),m=Te({queryKey:["analytics-metrics",t,a,h,n],queryFn:()=>ud(t,a),staleTime:ri}),u=m.data??null,b=m.error,p=o==="mentionShare"?"overall":c,x=l.useMemo(()=>u?mp(u,o,p):null,[u,o,p]),g=u?tp(u):null,f=l.useMemo(()=>lp(g??{}),[g]),S=l.useMemo(()=>cp(g??{}),[g]),j=l.useMemo(()=>dp(g??{}),[g]),D=l.useMemo(()=>Object.entries(g??{}).filter(([,E])=>E.anchorUnavailable).map(([E])=>E).sort(),[g]),A=l.useMemo(()=>u?sp(u):{},[u]),y=l.useMemo(()=>u?np(u):{},[u]),w=l.useMemo(()=>u?md(ap(u)):null,[u]),N=o!=="mentionShare"&&p==="byProvider",M=u?.buckets??[],L=M[M.length-1]?.mentionShare.scope??u?.mentionShareScope??"pooled",F=Ea(o,L),H=o==="cited"?qs.positive:o==="mentionShare"?ci:rt[1],O=N?us.textDim:H,J=l.useMemo(()=>{const E=new Map(M.map(R=>[R.startDate,Zx(R)]));return R=>E.get(String(R))??""},[M]),G=o==="mentionShare"?x?lo(x.rows,cs):null:M.length>0?Vs(M[M.length-1][aa(o)]*100):null,C=o==="mentionShare"?x?Ip(x.rows,cs):null:M.length>0?Vs(M[0][aa(o)]*100):null,ae=o==="mentionShare"?x?.rows.filter(E=>typeof E[cs]=="number").length??0:M.length,q=G!==null&&C!==null&&ae>1?Vs(G-C):null,se=s.length,V=e.jsxs(e.Fragment,{children:[w?.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:w.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(Ve,{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."})]})]}),G!==null&&e.jsxs("div",{className:"visibility-trend-current",children:[e.jsx("span",{className:"visibility-trend-current-dot",style:{backgroundColor:O},"aria-hidden":"true"}),e.jsx("span",{className:"visibility-trend-current-label",children:F}),N&&e.jsx("span",{className:"visibility-trend-current-qualifier",children:"avg"}),e.jsxs("span",{className:"visibility-trend-current-value",children:[G,"%"]}),q!==null&&e.jsxs("span",{className:`visibility-trend-current-delta ${q>0?"text-positive-400":q<0?"text-negative-400":"text-muted"}`,children:[q>0?"+":"",q.toFixed(1)," pts"]})]})]}),e.jsxs("div",{className:"visibility-trend-controls",children:[e.jsx(br,{options:kp,value:o,onChange:i,ariaLabel:"Metric",className:"visibility-trend-metric-control"}),o!=="mentionShare"&&e.jsx(br,{options:Cp,value:c,onChange:d,ariaLabel:"Series"}),e.jsx(br,{options:xp,value:a,onChange:r,ariaLabel:"Time window",className:"sm:ml-auto"})]})]});let B;if(b)B=e.jsx("p",{className:"text-sm text-negative-400",children:ea(b)});else if(m.isLoading&&!u)B=e.jsx("div",{className:"visibility-trend-chart animate-pulse rounded-lg bg-bg-elevated/40","aria-hidden":"true"});else if(o==="mentionShare"&&se===0)B=e.jsx("p",{className:"text-sm text-secondary",children:"Add tracked competitors to measure mention share over time."});else if(!u||!x)B=null;else{const{rows:E,series:R,hasData:oe}=x,T=hp(u.queryChanges);if(!oe)B=e.jsx("p",{className:"text-sm text-secondary",children:o==="mentionShare"?`No answer-text brand mentions for you or tracked competitors on ${Ya(L)} in this window yet.`:Bt()?Js:"Run a sweep to start tracking citations and mentions over time."});else if(N&&R.length===0)B=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 ee=`${F} rate across ${E.length} ${E.length===1?"sweep":"sweeps"}. Latest ${G}%${q!==null?`, ${q>=0?"up":"down"} ${Math.abs(q).toFixed(1)} points over the period`:""}.`;B=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"sr-only",children:ee}),e.jsx(Ep,{buckets:M,metric:o,mode:p,series:R}),N&&R.length>0&&e.jsx("ul",{className:"trend-legend","aria-label":"Engines",children:R.map((Z,ge)=>{const X=lo(E,Z),de=ip(M,Z),xe=g===null?"Attribution unavailable":de?Is(de):"No observed model evidence";return e.jsxs("li",{className:"trend-legend-item",children:[e.jsx("span",{className:"trend-legend-swatch",style:{backgroundColor:Wn(Z,ge)},"aria-hidden":"true"}),e.jsxs("span",{className:"trend-legend-label",children:[e.jsx("span",{className:"trend-legend-name",children:Vl(Z)}),e.jsxs("span",{className:"trend-legend-model",children:[e.jsx("span",{"aria-hidden":"true",children:"· "}),xe]})]}),X!==null&&e.jsxs("span",{className:"trend-legend-value",children:[X,"%"]})]},Z)})}),e.jsx("div",{className:"visibility-trend-chart",role:"img","aria-label":`${F} trend chart over ${E.length} ${E.length===1?"bucket":"buckets"}`,children:e.jsx(Xs,{width:"100%",height:"100%",children:e.jsxs(Zs,{data:E,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(na,{stroke:sa,vertical:!1}),e.jsx(en,{dataKey:"date",tick:Ft,tickLine:!1,axisLine:{stroke:ds},tickFormatter:J,minTickGap:24}),e.jsx(tn,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:Z=>`${Z}%`,tick:Ft,tickLine:!1,axisLine:!1,width:40}),e.jsx(sn,{cursor:{stroke:ds,strokeWidth:1},content:e.jsx(qp,{metric:o,mode:p,buckets:M})}),f.buckets.map(({bucketStartDate:Z,events:ge})=>e.jsx(eh,{x:Z,stroke:$p(ge),strokeDasharray:"4 4",strokeWidth:1.5,ifOverflow:"extendDomain"},`model-evidence-${Z}`)),R.map((Z,ge)=>e.jsx(Ms,{type:"monotone",dataKey:Z,name:Z,stroke:Wn(Z,ge),strokeDasharray:Z===cs?"5 4":void 0,strokeWidth:Rp(Z)?2.5:2,dot:Z===cs?{r:2.75,fill:"var(--chart-tooltip-bg)",stroke:Wn(Z,ge),strokeWidth:1.5}:{r:2.5,fill:Wn(Z,ge),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:Ap},connectNulls:Z!==cs,isAnimationActive:!1},Z))]})})}),e.jsx(Lp,{partition:f,available:g!==null,counts:S,truncated:j,incompleteHistory:D,served:A,mismatch:y,buckets:M}),T&&e.jsx("p",{className:"visibility-trend-note",children:T})]})}}return e.jsxs("section",{className:"visibility-trend",children:[V,B]})}const go=new Set([Xn.queued,Xn.running]),Ot={queryPlaceholder:"Write one research query per line",runAction:"Run queries",historyTitle:"Research history",historyMore:"Load older runs",historyLoading:"Loading older runs…",historyMoreError:"Could not load older research. Try again.",resultsTitle:"Research results",emptyHistory:"No saved research.",resultsEmpty:"Choose a saved run.",methodologySummary:"How matching works",methodology:"Brand-name matches use configured project names or domains in answer text. Project-domain citations use source links. Neither verifies property identity.",refreshPreview:"Regenerate preview",templateProvenance:"Query pattern details",brandedQuery:"Branded",discoveryQuery:"Discovery",unclassifiedQuery:"Unclassified"};function fo({projectName:t,onReviewForTracking:s,scopeOptions:n,planRevision:a,selectedScope:r,scopePending:o,scopeError:i,onRetryScope:c,templates:d=[],viewerResearchConfig:h=null}){const m=ms(),{account:u,canWrite:b}=bn(),p=u?.role==="viewer"&&h!==null,x=!b,[g,f]=l.useState(""),[S,j]=l.useState(""),[D,A]=l.useState(null),[y,w]=l.useState([]),N=l.useRef(null),M=l.useRef(!1),[L,F]=l.useState(0),H=Te({...xd({client:Y,path:{name:t}}),staleTime:6e4}),O=Te({...pd({client:Y}),enabled:!x,staleTime:6e4}),J={client:Y,path:{name:t},query:{limit:20}},G=Zo({...gd(J),initialData:void 0,initialPageParam:J,getNextPageParam:Q=>Q.nextCursor?{path:J.path,query:{...J.query,cursor:Q.nextCursor}}:void 0,refetchInterval:Q=>Q.state.data?.pages.some(re=>re.runs.some(Ee=>go.has(Ee.status)))?3e3:!1}),C=G.isError&&!G.isFetchNextPageError,ae=G.data?.pages.at(-1),q=C?[]:[...new Map((G.data?.pages.flatMap(Q=>Q.runs)??[]).map(Q=>[Q.id,Q])).values()],se=ae?.access?.canRun??(b||p),V=ae?.access?ae.access.dailyRunLimit:p?h.viewerDailyRunLimit:null;l.useEffect(()=>{!D&&q[0]&&A(q[0].id)},[q,D]);const B=q.find(Q=>Q.id===D)??null,E=Te({...fd({client:Y,path:{name:t,runId:D??""}}),enabled:!C&&!!D,refetchInterval:B&&go.has(B.status)?3e3:!1}),R=C||E.isError?null:E.data??null,oe=H.data?.locations??[],T=l.useMemo(()=>{if(x)return(ae?.providers??[]).map(re=>({...re,catalog:re}));const Q=new Map((O.data?.providerCatalog??[]).map(re=>[re.name,re]));return(O.data?.providers??[]).filter(re=>re.configured&&Q.get(re.name)?.mode==="api").map(re=>({...re,catalog:{...Q.get(re.name),defaultModel:re.model||Q.get(re.name).defaultModel}}))},[x,ae?.providers,O.data]),ee=!(x?G.isPending:O.isPending)&&T.length===0,Z=T.find(Q=>Q.name===g)??null;l.useEffect(()=>{if(!g&&H.data&&!H.isError&&!O.isError){const Q=H.data.providers.find(re=>T.some(Ee=>Ee.name===re));f(Q??T[0]?.name??"")}},[g,T,H.data,H.isError,O.isError]);const ge=Z?.catalog.modelConfigurable??!1,X=x?Z?.catalog.defaultModel:(Z?H.data?.providerModels[Z.name]:"")||Z?.catalog.defaultModel,de=(ge?S.trim():"")||X,xe=Z?[...new Map([{id:Z.catalog.defaultModel,displayName:Z.catalog.defaultModel},...S.trim()?[{id:S.trim(),displayName:S.trim()}]:[],...Z.catalog.knownModels].map(Q=>[Q.id,Q])).values()]:[],ne=Tt({...yd(),onSuccess:async Q=>{N.current=null,F(re=>re+1),w(Q.runs),A(Q.runs[0]?.id??null),await zp(m),$e({title:"Research batch saved",detail:`${Q.runs.length} ${Q.runs.length===1?"run is":"runs are"} in research history. Nothing was added to tracked queries.`,tone:"positive",dedupeKey:`research:start:${Q.runs.map(re=>re.id).join(":")}`,dedupeMode:"replace"})},onError:Q=>{$e({title:"Could not start research",detail:Q instanceof Error?Q.message:"Check the provider, model, and location, then try again.",tone:"negative"})},onSettled:()=>{M.current=!1}});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx(Op,{projectName:t,canWrite:b,researchAllowed:se&&!C,limitedAccess:x,isEmbed:ie(),scopeOptions:n??[],planRevision:a??r?.planRevision??null,initialScope:r,scopePending:o,scopeError:i,onRetryScope:c,templates:d,locations:oe,defaultLocation:H.data?.defaultLocation??null,providerOptions:T,provider:g,onProviderChange:Q=>{f(Q),j("")},resolvedModel:de,visibilityModel:X,configurableModel:ge,model:S,onModelChange:j,modelOptions:xe,settingsReady:x?!G.isPending&&!C:!O.isPending&&!O.isError&&!O.isFetching,projectReady:!H.isPending&&!H.isError&&!H.isFetching,isPending:ne.isPending,errorMessage:ne.isError?"The request could not be confirmed.":void 0,onSubmit:(Q,re)=>{!se||C||ie()||M.current||(N.current?.fingerprint!==re&&(N.current={fingerprint:re,key:crypto.randomUUID()}),M.current=!0,ne.mutate({client:Y,path:{name:t},body:{...Q,idempotencyKey:N.current.key}}))}},`${t}:${L}`),V!==null&&e.jsxs("p",{className:"text-sm text-secondary",children:["Up to ",V," destination runs per project per day."]}),!x&&O.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load API providers."}),e.jsx(P,{variant:"outline",onClick:()=>{O.refetch()},children:"Retry providers"})]}):null,H.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load project locations."}),e.jsx(P,{variant:"outline",onClick:()=>{H.refetch()},children:"Retry locations"})]}):null,!(x?C:O.isError)&&ee&&e.jsx("p",{className:"rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2 text-sm text-caution",children:x?"No research engines are available. Ask your Canonry team to configure one.":"Configure an API provider in Settings before starting research. Browser engines are not available for this workflow."}),y.length>0&&e.jsxs("p",{role:"status",className:"text-sm text-secondary",children:["Saved runs: ",y.map((Q,re)=>e.jsxs("span",{children:[re>0?", ":"",e.jsxs("a",{href:`#research-run-${Q.id}`,className:"text-link underline",onClick:()=>A(Q.id),children:[Q.scope?.label??"Whole site",Q.location?`, ${Q.location.label}`:", No location"]})]},Q.id))]}),e.jsxs(ye,{className:"surface-card min-w-0",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsx("div",{children:e.jsx("h3",{children:Ot.historyTitle})}),G.isFetching&&e.jsx(ue,{tone:"neutral",children:"Loading"})]}),C?e.jsxs("div",{role:"alert",className:"mt-4 text-sm text-negative",children:[e.jsx("p",{children:"Could not load research history."}),e.jsx(P,{variant:"outline",onClick:()=>{G.refetch()},children:"Retry history"})]}):G.isPending?e.jsx("p",{role:"status",children:"Loading research history…"}):q.length===0?e.jsx("p",{className:"mt-4 text-sm text-muted",children:Ot.emptyHistory}):e.jsx("div",{className:"mt-4 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[760px] [overflow-wrap:anywhere]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Run"}),e.jsx("th",{children:"Model"}),e.jsx("th",{children:"Destination"}),e.jsx("th",{children:"Location"}),e.jsx("th",{children:"Progress"}),e.jsx("th",{children:"Status"})]})}),e.jsx("tbody",{children:q.map(Q=>e.jsxs("tr",{className:D===Q.id?"bg-bg-elevated/40":void 0,children:[e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-left font-medium text-heading hover:text-link focus:outline-none focus:underline",onClick:()=>A(Q.id),children:Bp(Q.createdAt)})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:Q.provider}),e.jsx("span",{className:"font-mono text-[11px] text-muted",children:Q.requestedModel??Q.resolvedModel})]}),e.jsx("td",{className:"text-secondary",children:Q.scope?.label??"Whole site"}),e.jsx("td",{className:"text-secondary",children:Q.location?.label??"No location"}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[Q.completedQueries+Q.failedQueries,"/",Q.totalQueries]}),e.jsx("td",{children:e.jsx(ue,{tone:Hl(Q.status),children:Q.status})})]},Q.id))})]})}),G.isFetchNextPageError&&e.jsx("p",{role:"alert",className:"mt-3 text-sm text-negative",children:Ot.historyMoreError}),G.hasNextPage&&e.jsx(P,{className:"mt-3",variant:"outline",disabled:G.isFetching,onClick:()=>{G.fetchNextPage()},children:G.isFetchingNextPage?Ot.historyLoading:Ot.historyMore})]})]}),!C&&E.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load saved research results."}),e.jsx(P,{variant:"outline",onClick:()=>{E.refetch()},children:"Retry results"})]}):C?null:e.jsx(_p,{detail:R,isLoading:E.isFetching,onReviewForTracking:s})]})}const Ss="mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 disabled:opacity-50",Tn="__none__";function Op(t){const{projectName:s,locations:n,provider:a,resolvedModel:r,planRevision:o}=t,i=ms(),[c,d]=l.useState("once"),[h,m]=l.useState(""),[u,b]=l.useState(""),[p,x]=l.useState(t.initialScope?`${t.initialScope.kind}:${t.initialScope.key}`:"project"),[g,f]=l.useState(null),[S,j]=l.useState([]),[D,A]=l.useState(""),[y,w]=l.useState({}),[N,M]=l.useState(null),[L,F]=l.useState([]),[H,O]=l.useState(null),[J,G]=l.useState(!1),[C,ae]=l.useState(!1),[q,se]=l.useState(""),[V,B]=l.useState(""),E=l.useRef(null),R=l.useRef(!1),oe=l.useRef(null),T=t.initialScope?`${t.initialScope.kind}:${t.initialScope.key}`:"project";l.useEffect(()=>{x(T),M(null)},[T]);const ee=t.scopeOptions.filter(k=>k.kind==="market"||k.kind==="property"),Z=c==="markets"?"market":"property",ge=ee.filter(k=>k.kind===Z),X=k=>({kind:k.kind,key:k.id,label:k.label,planRevision:o??t.initialScope?.planRevision??0}),de=k=>k===Tn?null:n.find(Ae=>Ae.label===k),xe=g??t.defaultLocation??Tn,ne=ee.find(k=>`${k.kind}:${k.id}`===p),Q=ne?X(ne):null,re=c==="once"?[{scope:Q,location:de(xe)}]:c==="locations"?S.map(k=>({scope:null,location:de(k)})):S.map(k=>ge.find(Ae=>`${Ae.kind}:${Ae.id}`===k)).map(k=>k?{scope:X(k),location:de(y[`${k.kind}:${k.id}`]??Tn)}:null),Ee=[...new Map([...L,...t.templates].map(k=>[k.id,k])).values()],we=N?Ee.find(k=>k.id===N.id):null,Se=N!==null&&we?.version!==N.version,et=c==="once"?h:u,Ke=et.split(/\r?\n/).filter(k=>k.trim()),Qe=ki(Ke),We=[...new Set([...u.matchAll(/\{([^{}]+)\}/g)].map(k=>k[1]))],Ge=/[{}]/.test(u.replace(/\{(?:market|submarket|property|propertyBrand|location)\}/g,"")),_=[];Ke.length||_.push(c==="once"?"Enter at least one query.":"Enter at least one query pattern."),Ke.some(k=>k.length>4e3)&&_.push("Keep each query under 4,001 characters."),c!=="once"&&Ge&&_.push("Use the name buttons to insert a supported variable. Remove unknown or incomplete braces."),re.length||_.push(c==="locations"?"Select at least one location.":"Select at least one destination."),re.some(k=>!k||k.location===void 0)&&_.push("A selected destination or location is no longer available. Update your selection.");const U=c==="once"&&p!=="project"||c==="markets"||c==="properties";U&&(t.scopePending||t.scopeError||!o||re.some(k=>!k?.scope))&&_.push("Load the current published markets and properties before running scoped research.");const W=(c==="once"?Qe.length:Ke.length)*re.length;if(re.length>ya&&_.push(`Select at most ${ya} destinations.`),W>nr&&_.push(`${W} queries selected. Reduce the selection to ${nr} or fewer.`),Se&&_.push("This saved pattern changed. Select its current version from Saved patterns."),c!=="once"&&!Ge){for(const k of re)if(!(!k||k.location===void 0))try{sr(N??{pattern:u,variables:We},k.scope,k.location)}catch{_.push(`Choose a location for {location}, or use only variables available for ${c==="markets"?"markets":c==="properties"?"properties":"locations"}.`);break}}const Re=JSON.stringify({mode:c,source:et,contexts:re,provider:a,resolvedModel:r,template:N,...U?{planRevision:o}:{}}),_e=H!==null&&H.signature!==Re,Ue=c==="once"?Qe.map((k,Ae)=>({id:String(Ae),query:k,scope:Q,location:re[0]?.location??null})):H?.rows??[],le=Gp(Ue),pt=[];c!=="once"&&H&&(_e&&pt.push("Setup changed. Your edited queries are preserved. Regenerate the preview to use the new setup."),Ue.some(k=>!k.query.trim()||k.query.length>4e3||/\{(?:market|submarket|property|propertyBrand|location)\}/.test(k.query))&&pt.push("Every preview row needs a complete query of 1 to 4,000 characters, with no unresolved variables."),Ue.some(k=>k.location&&!n.some(Ae=>JSON.stringify(Ae)===JSON.stringify(k.location)))&&pt.push("A preview location changed. Regenerate the preview."),le.some(k=>ki(k.queries).length!==k.queries.length)&&pt.push("Remove duplicate queries within each destination and location."),le.length>ya&&pt.push(`The preview exceeds ${ya} runs.`));const ut=t.researchAllowed&&!t.isEmbed&&!t.isPending&&t.settingsReady&&t.projectReady&&!!(a&&r)&&!_.length&&!pt.length&&(c==="once"||H!==null),ze=()=>({runs:le.map(k=>({queries:k.queries,provider:a,model:r,location:k.location,...k.scope?{scope:{kind:k.scope.kind,key:k.scope.key,expectedPlanRevision:k.scope.planRevision}}:{},...k.template?{template:k.template}:{}}))}),Fe=()=>{if(G(!0),_.length)return;const k=re.flatMap((Ae,ve)=>Ke.map((He,vt)=>({id:`${ve}:${vt}`,scope:Ae.scope,location:Ae.location,...N?{template:{templateId:N.id,templateVersion:N.version,bindingLocation:Ae.location}}:{},query:sr({pattern:He,variables:[...new Set([...He.matchAll(/\{([^{}]+)\}/g)].map(st=>st[1]))]},Ae.scope,Ae.location).output})));O({signature:Re,rows:k})},wt=k=>{d(k),j([]),M(null),A(""),G(!1)},Be=k=>{if(B(""),c==="once")try{m(sr(k,Q,de(xe)).output)}catch{B("Select a matching market, property, or location before using this pattern.");return}else b(k.pattern);M(k)},Me=k=>{const Ae=oe.current,ve=Ae?.selectionStart??u.length,He=Ae?.selectionEnd??ve;b(`${u.slice(0,ve)}{${k}}${u.slice(He)}`),M(null),requestAnimationFrame(()=>{Ae?.focus(),Ae?.setSelectionRange(ve+k.length+2,ve+k.length+2)})},tt=Tt({...vd(),onSuccess:async k=>{const Ae={id:k.id,version:k.updatedAt,label:k.name,pattern:k.pattern,variables:k.variables};F(ve=>[...ve.filter(He=>He.id!==k.id),Ae]),M(Ae),ae(!1),se(""),B(""),E.current=null,await i.invalidateQueries({queryKey:bd({client:Y,path:{name:s}})}),$e({title:"Pattern saved",detail:"Available in Saved patterns. Tracking was not changed.",tone:"positive"})},onError:()=>B("Could not save the pattern. Your text is preserved. Retry to save the same pattern."),onSettled:()=>{R.current=!1}}),$t=()=>{if(!t.canWrite||t.isEmbed||R.current)return;const k=c==="once"?h:u,Ae=c==="once"?[]:We;if(!q.trim()||!k.trim()||k.length>4e3||c!=="once"&&Ge){B("Enter a name and a valid pattern of 1 to 4,000 characters.");return}const ve={name:q.trim(),pattern:k,variables:Ae},He=JSON.stringify(ve);E.current?.fingerprint!==He&&(E.current={fingerprint:He,id:crypto.randomUUID()}),R.current=!0,tt.mutate({client:Y,path:{name:s,templateId:E.current.id},body:ve})},Mt=[...new Set([...J||et.trim()?_:[],...pt])],De=Ee.filter(k=>{const Ae=c==="once"?Ai(Q,de(xe)):Ai(c==="markets"?{kind:"market",label:"Market"}:c==="properties"?{kind:"property",label:"Property"}:null,{label:"Location"});return k.variables.every(ve=>Ae[ve]!==void 0)});return e.jsxs(ye,{className:"surface-card min-w-0",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{children:"Test queries"}),e.jsx("p",{className:"mt-1 max-w-prose text-sm text-secondary",children:"See how an answer engine responds. Results are saved separately from tracked queries and AI Visibility metrics."})]})}),e.jsxs("fieldset",{"aria-label":"Research setup",className:"mt-5 min-w-0 space-y-5",disabled:t.isPending||tt.isPending,children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Run mode"}),e.jsxs("select",{className:Ss,value:c,disabled:t.isPending,onChange:k=>wt(k.target.value),children:[e.jsx("option",{value:"once",children:"Run once"}),e.jsx("option",{value:"markets",disabled:!ee.some(k=>k.kind==="market"),children:"Repeat across markets"}),e.jsx("option",{value:"properties",disabled:!ee.some(k=>k.kind==="property"),children:"Repeat across properties"}),e.jsx("option",{value:"locations",disabled:!n.length,children:"Repeat across locations"})]})]}),c==="once"&&e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[(ee.length>0||p!=="project")&&e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Save results under"}),e.jsxs("select",{className:Ss,value:p,onChange:k=>{x(k.target.value),M(null)},children:[e.jsx("option",{value:"project",children:"Whole site"}),p!=="project"&&!ne&&e.jsx("option",{value:p,disabled:!0,children:"Selected destination unavailable"}),ee.map(k=>e.jsxs("option",{value:`${k.kind}:${k.id}`,children:[k.label," (",k.kind,")"]},`${k.kind}:${k.id}`))]})]}),e.jsx(Jr,{label:"Answer engine location",value:xe,locations:n,onChange:k=>{f(k),M(null)}})]}),c!=="once"&&e.jsxs("fieldset",{className:"space-y-3",children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:c==="locations"?"Select locations":`Select ${c}`}),e.jsx("p",{className:"text-sm text-secondary",children:"Choose each destination explicitly. Each selected destination gets its own saved research run."}),e.jsx("input",{type:"search","aria-label":"Search destinations",className:Ss,placeholder:`Search ${c}`,value:D,onChange:k=>A(k.target.value)}),e.jsx("div",{className:"max-h-72 space-y-2 overflow-y-auto pr-1",children:(c==="locations"?n.map(k=>({key:k.label,label:k.label})):ge.map(k=>({key:`${k.kind}:${k.id}`,label:k.label}))).filter(k=>k.label.toLocaleLowerCase().includes(D.toLocaleLowerCase())).map(k=>{const Ae=S.includes(k.key);return e.jsxs("div",{className:"grid items-center gap-2 border-b border-default pb-2 sm:grid-cols-[minmax(0,1fr)_16rem]",children:[e.jsxs("label",{className:"flex min-h-11 items-center gap-3 text-sm text-heading",children:[e.jsx("input",{type:"checkbox",checked:Ae,onChange:()=>j(ve=>Ae?ve.filter(He=>He!==k.key):[...ve,k.key])}),k.label]}),Ae&&c!=="locations"&&e.jsx(Jr,{label:`Answer engine location for ${k.label}`,value:y[k.key]??Tn,locations:n,onChange:ve=>w(He=>({...He,[k.key]:ve}))})]},k.key)})}),e.jsxs("p",{className:"text-sm text-secondary",children:[S.length," selected. A market or property name changes query text, not the answer engine's location."]})]}),t.scopeError&&e.jsxs("p",{className:"text-sm text-caution",children:["Markets and properties could not load. Whole-site and location research remain available. ",e.jsx(P,{variant:"outline",onClick:t.onRetryScope,children:"Retry destinations"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block",htmlFor:"research-query-editor",children:e.jsx("span",{className:"text-sm font-medium text-heading",children:c==="once"?"Queries":"Query pattern"})}),e.jsx("p",{id:"research-query-guidance",className:"mt-1 text-sm text-secondary",children:c==="once"?"Enter one query per line. The answer engine receives exactly this text.":`Use {${c==="markets"?"market":c==="properties"?"property":"location"}} where each name belongs. Preview the resolved queries before running.`}),e.jsx("textarea",{id:"research-query-editor",ref:oe,className:`${Ss} min-h-32`,"aria-describedby":"research-query-guidance research-query-count",value:et,placeholder:c==="once"?Ot.queryPlaceholder:c==="markets"?"Best apartments in {market}":c==="properties"?"What amenities does {property} offer?":"Best apartments in {location}",onChange:k=>{c==="once"?m(k.target.value):(b(k.target.value),M(null))}}),c!=="once"&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[e.jsxs(P,{size:"sm",variant:"outline",onClick:()=>Me(c==="markets"?"market":c==="properties"?"property":"location"),children:["Insert ",c==="markets"?"market":c==="properties"?"property":"location"," name"]}),e.jsx("span",{className:"self-center text-sm text-secondary",children:"One pattern per line."})]}),e.jsxs("p",{id:"research-query-count",className:"mt-2 text-sm text-secondary",children:[W," / ",nr," queries",c==="once"?"":` across ${re.length} destinations`]})]}),c!=="once"&&e.jsxs("details",{className:"border-t border-default pt-3",children:[e.jsxs("summary",{className:"cursor-pointer text-sm font-medium text-heading focus-visible:outline focus-visible:outline-2",children:["Saved patterns ",e.jsx("span",{className:"font-normal text-secondary",children:"(optional)"})]}),e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsx("p",{className:"text-sm text-secondary",children:"Reusable starting text, not active measurement templates. Saving a pattern does not run or track queries."}),De.length?e.jsx("div",{className:"flex flex-wrap gap-2",children:De.map(k=>e.jsx(P,{size:"sm",variant:"outline",onClick:()=>Be(k),children:k.label},k.id))}):e.jsx("p",{className:"text-sm text-secondary",children:"No saved patterns for this selection."}),N&&e.jsxs("p",{className:"text-sm text-secondary",children:["Using: ",N.label]}),t.canWrite&&!t.isEmbed&&e.jsxs(e.Fragment,{children:[e.jsx(P,{size:"sm",variant:"outline",onClick:()=>ae(!C),children:C?"Cancel save":"Save as a pattern"}),C&&e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("label",{className:"min-w-48 flex-1 text-sm text-heading",children:["Pattern name",e.jsx("input",{className:Ss,value:q,maxLength:120,onChange:k=>se(k.target.value)})]}),e.jsx(P,{size:"sm",disabled:tt.isPending||!q.trim()||!et.trim(),onClick:$t,children:tt.isPending?"Saving…":"Save pattern"})]})]}),V&&e.jsx("p",{role:"alert",className:"text-sm text-negative",children:V})]})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("label",{className:"block text-sm font-medium text-heading",children:["Answer engine",e.jsxs("select",{className:Ss,value:a,onChange:k=>t.onProviderChange(k.target.value),children:[e.jsx("option",{value:"",disabled:!0,children:"Choose an answer engine"}),t.providerOptions.map(k=>e.jsx("option",{value:k.name,children:k.displayName??k.name},k.name))]})]}),e.jsxs("label",{className:"block text-sm font-medium text-heading",children:["Model",t.limitedAccess?e.jsxs("select",{className:Ss,value:t.model,disabled:!a||!t.configurableModel,onChange:k=>t.onModelChange(k.target.value),children:[e.jsxs("option",{value:"",children:["Use AI Visibility model · ",t.visibilityModel]}),t.modelOptions.map(k=>e.jsx("option",{value:k.id,children:k.displayName},k.id))]}):e.jsxs(e.Fragment,{children:[e.jsx("input",{"aria-label":"Model",className:Ss,list:"research-known-models",placeholder:r??"Choose an answer engine",value:t.model,disabled:!a||!t.configurableModel,onChange:k=>t.onModelChange(k.target.value)}),e.jsx("datalist",{id:"research-known-models",children:t.modelOptions.map(k=>e.jsx("option",{value:k.id,children:k.displayName},k.id))})]})]})]}),Mt.length>0&&e.jsx(Kp,{errors:Mt}),c!=="once"&&e.jsxs("div",{className:"space-y-4 border-t border-default pt-4",children:[e.jsxs(P,{variant:"outline",size:"sm",disabled:t.isPending||!t.projectReady,onClick:Fe,children:[e.jsx(ta,{size:14}),H?Ot.refreshPreview:"Preview queries"]}),H&&e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"font-medium text-heading",children:"Queries to run"}),e.jsxs("p",{className:"text-sm text-secondary",children:[Ue.length," query executions in ",le.length," saved runs · ",a," · ",r,". Edit any query or location below."]}),e.jsx(Fp,{rows:Ue,locations:n,onChange:(k,Ae)=>O(ve=>ve&&{...ve,rows:ve.rows.map(He=>He.id===k?{...He,...Ae}:He)})})]})]}),t.errorMessage&&e.jsxs("p",{role:"alert",className:"text-sm text-negative",children:[t.errorMessage," Your entries are preserved. Retry unchanged entries to avoid duplicate work."]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 border-t border-default pt-4",children:[!t.isEmbed&&e.jsxs(P,{size:"sm",disabled:!ut,onClick:()=>{if(ut){const k=ze();t.onSubmit(k,JSON.stringify({projectName:s,...k}))}},children:[e.jsx(_a,{size:14}),t.isPending?"Starting…":Ot.runAction]}),e.jsxs("p",{className:"text-sm text-secondary",children:[c==="once"?`${Qe.length} queries`:`${Ue.length} reviewed queries`," · ",a||"Choose an engine"," · ",r||"Choose a model",". Uses your configured answer engine."]})]})]})]})}function Jr({label:t,value:s,locations:n,onChange:a}){return e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:t}),e.jsxs("select",{className:Ss,value:s,onChange:r=>a(r.target.value),children:[e.jsx("option",{value:Tn,children:"No location context"}),n.map(r=>e.jsx("option",{value:r.label,children:r.label},r.label))]})]})}function Fp({rows:t,locations:s,onChange:n}){return e.jsx("ol",{className:"divide-y divide-default",children:t.map((a,r)=>e.jsxs("li",{className:"grid gap-3 py-4 md:grid-cols-[10rem_minmax(0,1fr)_15rem]",children:[e.jsxs("div",{className:"text-sm",children:[e.jsxs("span",{className:"block text-secondary",children:["Query ",r+1]}),e.jsx("span",{className:"font-medium text-heading",children:a.scope?.label??a.location?.label??"Whole site"}),a.scope&&e.jsx("span",{className:"block text-secondary",children:a.scope.kind})]}),e.jsxs("label",{className:"block text-sm font-medium text-heading",children:["Query",e.jsx("textarea",{className:`${Ss} min-h-20`,"aria-label":`Query ${r+1} for ${a.scope?.label??a.location?.label??"Whole site"}`,value:a.query,onChange:o=>n(a.id,{query:o.target.value})})]}),e.jsx(Jr,{label:`Location for query ${r+1}`,value:a.location?.label??Tn,locations:s,onChange:o=>n(a.id,{location:s.find(i=>i.label===o)??null})})]},a.id))})}function Kp({errors:t}){return e.jsx("div",{role:"alert",className:"text-sm text-negative",children:e.jsx("ul",{className:"list-disc space-y-1 pl-5",children:t.map(s=>e.jsx("li",{children:s},s))})})}function Gp(t){const s=new Map;for(const n of t){const a=JSON.stringify({scope:n.scope,location:n.location,template:n.template}),r=s.get(a)??{scope:n.scope,location:n.location,queries:[],...n.template?{template:n.template}:{}};r.queries.push(n.query),s.set(a,r)}return[...s.values()]}function _p({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(ye,{id:t?`research-run-${t.id}`:void 0,className:"surface-card min-w-0",role:"region","aria-label":Ot.resultsTitle,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 ${Vp(t.id)}`:Ot.resultsEmpty})]}),t&&e.jsx(ue,{tone:Hl(t.status),children:t.status})]}),t&&e.jsxs("div",{className:"mt-3 space-y-3 text-sm text-secondary",children:[e.jsxs("dl",{className:"flex flex-wrap gap-x-6 gap-y-2 [overflow-wrap:anywhere]",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Answer engine"}),e.jsx("dd",{children:t.provider})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Requested model"}),e.jsx("dd",{className:"font-mono",children:t.requestedModel??t.resolvedModel})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Location"}),e.jsx("dd",{children:t.location?.label??"No location"})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Destination"}),e.jsx("dd",{children:t.scope?.label??"Whole site"})]})]}),t.template&&e.jsxs("details",{children:[e.jsx("summary",{className:"cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2",children:Ot.templateProvenance}),e.jsxs("dl",{className:"mt-2 space-y-2",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Saved pattern"}),e.jsx("dd",{className:"whitespace-pre-wrap",children:t.template.template})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Names used"}),e.jsx("dd",{children:Object.entries(t.template.bindings).map(([i,c])=>`${i}: ${c}`).join(" · ")||"No variables"})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"font-medium",children:"Original resolved text"}),e.jsx("dd",{className:"whitespace-pre-wrap",children:t.template.output})]})]}),e.jsx("p",{className:"mt-2",children:"The queries below are the final text sent to the answer engine, including any edits."}),e.jsxs("p",{className:"mt-2 font-mono text-xs",children:[t.template.templateId," · ",t.template.templateVersion]})]}),e.jsxs("details",{children:[e.jsx("summary",{className:"cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2",children:Ot.methodologySummary}),e.jsx("p",{className:"mt-2 max-w-prose leading-6",children:Ot.methodology})]})]}),t?e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[760px] [overflow-wrap:anywhere]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Class"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Brand-name match"}),e.jsx("th",{children:"Project domain 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(ue,{tone:i.queryClass==="branded"?"positive":i.queryClass==="non-brand"?"neutral":"caution",children:i.queryClass==="branded"?Ot.brandedQuery:i.queryClass==="non-brand"?Ot.discoveryQuery:Ot.unclassifiedQuery})}),e.jsx("td",{children:e.jsx(ue,{tone:Qp(i.status),children:i.status})}),e.jsx("td",{children:e.jsx(ue,{tone:i.answerMentioned===!0?"positive":i.answerMentioned===!1?"neutral":i.status===xn.failed?"negative":"caution",children:i.answerMentioned===null?i.status===xn.failed?"Unavailable":"Pending":i.answerMentioned?"Matched":"No match"})}),e.jsx("td",{children:e.jsx(ue,{tone:i.citationState==="cited"?"positive":i.citationState==="not-cited"?"neutral":i.status===xn.failed?"negative":"caution",children:i.citationState===null?i.status===xn.failed?"Unavailable":"Pending":i.citationState==="cited"?"Cited":"Not cited"})})]},i.id))})]})}),e.jsx(Up,{query:o,scope:t.scope??null,isLoading:s,onReviewForTracking:n})]}):e.jsx("p",{className:"mt-4 text-sm text-muted",children:"Select a saved run to inspect each answer and its source links."})]})}function Up({query:t,isLoading:s,scope:n,onReviewForTracking:a}){return t?e.jsxs("div",{className:"min-w-0 space-y-4 border-t border-default pt-4 [overflow-wrap:anywhere]",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})]}),!ie()&&a&&e.jsxs("div",{className:"rounded-md border border-default bg-surface-subtle px-3 py-3",children:[e.jsx(Je,{type:"button",size:"sm",onClick:()=>a({researchRunQueryId:t.id,scope:n}),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("div",{className:"mt-1",children:e.jsx(Cl,{headingLevel:4,copyable:!0,children:t.answerText})})]}):e.jsx("p",{className:"text-sm text-muted",children:t.status===xn.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(r=>e.jsx("span",{className:"mention-chip mention-chip--competitor",children:r},r))})]}),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(r=>e.jsx("span",{className:"mention-chip mention-chip--competitor",children:r.replace(/^www\./,"")},r))})]}),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((r,o)=>{const i=_s(r.uri),c=r.title||r.uri;return e.jsxs("li",{className:"flex min-w-0 items-start gap-1.5 text-sm",children:[i?e.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",className:"truncate text-secondary hover:text-link focus:outline-none focus:underline",children:c}):e.jsx("span",{className:"truncate text-secondary",children:c}),i&&e.jsx(Um,{className:"mt-0.5 size-3 shrink-0 text-muted","aria-hidden":"true"})]},`${r.uri}-${o}`)})})]})]}):e.jsx("p",{className:"text-sm text-muted",children:s?"Loading saved answers…":"Select a query to inspect its answer."})}function Bp(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 Vp(t){return t.length>8?t.slice(0,8):t}function Hl(t){return t===Xn.completed?"positive":t===Xn.partial?"caution":t===Xn.failed?"negative":"neutral"}function Qp(t){return t===xn.completed?"positive":t===xn.failed?"negative":"neutral"}async function zp(t){await Nt(t,"researchRuns")}const Xr=new Set(["queued","seeding","probing"]);function Wp({projectName:t,queryWorkspace:s,onQueryWorkspaceChange:n,researchMode:a,onResearchModeChange:r,selection:o={measurementScope:"project",queryClass:"all"},onSelectionChange:i,trackingQueryId:c,onTrackingQueryIdChange:d}){const{account:h}=bn(),[m,u]=l.useState("tracked"),[b,p]=l.useState("find"),[x,g]=l.useState(null),f=h?.role==="viewer"?jd():null,S=h?.role!=="viewer"||f!==null,j=s??m,D=j==="research"&&!S?"tracked":j,A=a??b,y=M=>{s===void 0&&u(M),n?.(M)},w=M=>{a===void 0&&p(M),r?.(M)},N=(M,L)=>{const F=L===void 0?{...o}:{...o,measurementScope:L?.kind??"project",measurementScopeKey:L?.key};g({...M,trackingSelection:F}),L!==void 0&&i?.({measurementScope:F.measurementScope,measurementScopeKey:F.measurementScopeKey}),y("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(Qa,{active:D==="tracked",label:"Tracked",onClick:()=>y("tracked")}),S?e.jsx(Qa,{active:D==="research",label:"Research",onClick:()=>y("research")}):null]}),e.jsx("div",{className:"mt-4",children:D==="tracked"?e.jsx(gg,{projectName:t,selection:o,onSelectionChange:i,trackingQueryId:c,onTrackingQueryIdChange:d,pendingTrackingSource:x,onPendingTrackingSourceHandled:()=>g(null)}):e.jsx(Hp,{projectName:t,selection:o,mode:A,onModeChange:w,onReviewSavedSource:N,onSelectionChange:i,viewerResearchConfig:f})})]})}function Qa({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 Hp({projectName:t,selection:s,mode:n,onModeChange:a,onReviewSavedSource:r,viewerResearchConfig:o}){const{canWrite:i}=bn(),c=!i||n==="test",d=Te({...dl({client:Y,path:{name:t}}),enabled:c,staleTime:6e4}),h=Te({...ul({client:Y,path:{name:t}}),enabled:c,staleTime:6e4}),m=l.useMemo(()=>{const p=d.data;if(!p)return[{id:"project",label:"Whole site",kind:"project",targetCount:0}];const x=new Map(p.targets.map(f=>[f.stableKey,[]]));for(const f of p.groups)for(const S of f.targetKeys)x.get(S)?.push(f.stableKey);const g=new Map(p.markets.map(f=>[f.stableKey,new Set]));for(const f of p.markets)for(const S of f.usageEdges)for(const j of x.get(S.targetKey)??[])g.get(f.stableKey)?.add(j);return[{id:"project",label:"Whole site",kind:"project",targetCount:p.targets.length},...p.groups.map(f=>({id:f.stableKey,label:f.label,kind:"group",targetCount:f.targetKeys.length,...f.parentGroupKey?{parentGroupIds:[f.parentGroupKey]}:{}})),...p.markets.map(f=>{const S=[...g.get(f.stableKey)??[]];return{id:f.stableKey,label:f.label,kind:"market",targetCount:0,...S.length?{parentGroupIds:S}:{}}}),...p.targets.map(f=>({id:f.stableKey,label:f.label,kind:"property",targetCount:1,...x.get(f.stableKey)?.length?{parentGroupIds:x.get(f.stableKey)}:{}}))]},[d.data]),u=l.useMemo(()=>(h.data?.templates??[]).map(p=>({id:p.id,version:p.updatedAt,label:p.name,pattern:p.pattern,variables:p.variables})),[h.data]),b={projectName:t,scopeOptions:m,planRevision:d.data?.active?.revision??null,selectedScope:(()=>{const p=m.find(g=>g.kind===s.measurementScope&&g.id===s.measurementScopeKey),x=d.data?.active?.revision;return p&&x&&(p.kind==="market"||p.kind==="property")?{kind:p.kind,key:p.id,label:p.label,planRevision:x,expectedPlanRevision:x}:(s.measurementScope==="market"||s.measurementScope==="property")&&s.measurementScopeKey?{kind:s.measurementScope,key:s.measurementScopeKey,label:s.measurementScopeKey,planRevision:x??0,expectedPlanRevision:x??0}:null})(),scopePending:d.isPending||d.isFetching,scopeError:d.isError,onRetryScope:()=>{d.refetch()},templates:u};return i?e.jsxs("div",{children:[e.jsxs("div",{className:"flex border-b border-default",role:"tablist","aria-label":"Research workspace",children:[e.jsx(Qa,{active:n==="find",label:"Find queries",onClick:()=>a("find")}),e.jsx(Qa,{active:n==="test",label:"Test queries",onClick:()=>a("test")})]}),e.jsx("div",{className:"mt-4",children:n==="find"?e.jsx(fg,{projectName:t,onReviewDiscoveryProbe:p=>r({source:"discovery",discoveryProbeId:p})}):e.jsx(fo,{...b,onReviewForTracking:({researchRunQueryId:p,scope:x})=>r({source:"research",researchRunQueryId:p},x??null)})})]}):e.jsx(fo,{...b,viewerResearchConfig:o})}function Yp({workspace:t,selection:s,onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:o,onPendingTrackingSourceHandled:i,templates:c,preview:d,isPreviewing:h,isCommitting:m,onPreview:u,onCommit:b}){const[p,x]=l.useState(null),[g,f]=l.useState(()=>Da(s)),[S,j]=l.useState(null),D=l.useRef(null),A=l.useRef(null),y=eg(t,s),w=l.useMemo(()=>tg(t.tracked,s,t.mode),[s,t.mode,t.tracked]),N=fn({rows:w,getSearchText:C=>`${C.queryText} ${C.provenance?.source??"legacy"} ${C.assignments.map(ae=>ae.queryClass??"unknown").join(" ")}`});l.useEffect(()=>{if(y)return;if(!a){A.current=null;return}const C=`${a}:${Nr(s)}`;if(A.current===C)return;const ae=t.tracked.find(q=>q.queryId===a);ae&&(A.current=C,x({kind:"edit",row:ae,audience:t.mode==="advanced"?vr(s):void 0,scopeLabel:jr(s,t)}),f(yo(ae,s)),j(null))},[s,a,y,t]),l.useEffect(()=>{if(y||!o)return;const C=Da(o.trackingSelection??s);x({kind:"add"}),f(o.source==="research"?{...C,source:"research",researchRunQueryId:o.researchRunQueryId}:{...C,source:"discovery",discoveryProbeId:o.discoveryProbeId}),j(null),i()},[i,o,s,y]),l.useEffect(()=>{y&&(x(null),j(null),a!==void 0&&r?.(void 0))},[r,a,y]),l.useEffect(()=>{if(!p||p.kind==="remove")return;const C=D.current;C&&(C.scrollIntoView?.({block:"start"}),C.focus({preventScroll:!0}))},[p]);function M(C="manual"){x({kind:"add"}),f({...Da(s),source:C}),j(null),r?.(void 0)}function L(C){A.current=`${C.queryId}:${Nr(s)}`,x({kind:"edit",row:C,audience:t.mode==="advanced"?vr(s):void 0,scopeLabel:jr(s,t)}),f(yo(C,s)),j(null),r?.(C.queryId)}function F(C){A.current=`${C.queryId}:${Nr(s)}`,x({kind:"remove",row:C,audience:t.mode==="advanced"?vr(s):void 0,scopeLabel:jr(s,t)}),j(null),r?.(C.queryId)}function H(){x(null),j(null),r?.(void 0)}const O=p?Jp(p,g,t.mode):null,J=p!==null&&p.kind==="add"&&t.mode==="advanced"&&!di(g),G=O!==null&&(!J||g.contexts.length>0)&&!h;return y?e.jsx("div",{className:"query-tracking-workspace space-y-4",children:e.jsxs("section",{"aria-label":"Tracked queries",className:"py-4 text-sm text-secondary",children:[e.jsxs("p",{children:["This saved ",s.measurementScope," filter is unavailable in the current measurement."]}),e.jsx(P,{type:"button",variant:"outline",className:"mt-3",onClick:()=>n?.({measurementScope:"project",measurementScopeKey:void 0}),children:"Show whole site"})]})}):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(ng,{workspace:t,selection:s,onSelectionChange:n}),t.mode==="advanced"?e.jsx(sg,{selection:s,onSelectionChange:n}):null,e.jsx(zs,{value:N.query,onChange:N.setQuery,label:"Filter tracked queries",placeholder:"Search tracked queries",className:"min-w-64 flex-[2]"}),!ie()&&e.jsxs(Je,{type:"button",size:"sm",onClick:()=>M(),children:[e.jsx(Bm,{"aria-hidden":"true",size:14}),"Add query"]})]}),e.jsxs("p",{className:"mt-2 text-xs leading-5 text-secondary",children:[N.totalRows.toLocaleString("en-US")," saved query ",N.totalRows===1?"record":"records"," in this view. Each record can have more than one property, group, or market assignment."]}),s.measurementScope==="group"?e.jsx("p",{className:"mt-1 text-xs leading-5 text-secondary",children:"Queries belong to properties, so a shared query can also cover other groups."}):null,t.active?null:e.jsx("p",{className:"mt-3 text-sm text-caution",children:"No published measurement yet."}),N.rows.length===0?e.jsx("p",{className:"mt-5 text-sm text-muted",children:N.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"}),t.mode==="advanced"?e.jsx("th",{children:"Class"}):null,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:N.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:e.jsx(rg,{row:C,workspace:t,selection:s})}),t.mode==="advanced"?e.jsx("td",{className:"whitespace-nowrap",children:e.jsx(og,{row:C})}):null,e.jsx("td",{className:"whitespace-nowrap text-secondary",children:ag(C)}),e.jsx("td",{className:"whitespace-nowrap",children:e.jsx(lg,{row:C,outsidePlan:t.mode==="advanced"&&C.assignments.length===0})}),e.jsx("td",{className:"measurement-table-actions whitespace-nowrap text-right",children:!ie()&&e.jsxs("div",{className:"tracking-row-actions flex min-w-max justify-end gap-2",children:[e.jsxs(Je,{type:"button",variant:"ghost",size:"sm","aria-label":`Edit ${C.queryText}`,onClick:()=>L(C),children:[e.jsx(Vm,{"aria-hidden":"true",size:13})," Edit"]}),e.jsxs(Je,{type:"button",variant:"ghost",size:"sm","aria-label":`Remove ${C.queryText}`,onClick:()=>F(C),children:[e.jsx(jl,{"aria-hidden":"true",size:13})," Remove"]})]})})]},C.queryId))})]})}),e.jsx(Ls,{page:N.page,pageSize:N.pageSize,visibleRows:N.rows.length,totalRows:N.totalRows,itemLabel:"queries",onPageChange:N.setPage})]}),p&&!ie()&&e.jsx(cg,{workspace:t,templates:c,action:p,draft:g,onDraftChange:C=>{f(C),j(null)},onClose:H,canReview:G,isPreviewing:h,editorHeadingRef:D,onReview:()=>{O&&(j(O),u(O))}}),d&&S&&p&&e.jsx(hg,{preview:d,workspace:t,isCommitting:m,onConfirm:()=>{b({...S,expectedWorkspaceVersion:d.workspaceVersion,previewToken:d.previewToken,reviewedAt:d.reviewedAt})}})]})}function Da(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 yo(t,s){return{...Da(s),text:t.queryText,queryClass:"keep"}}function Jp(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=Xp(s);if(!a||Zr(s)||!s.wholeSite&&s.targetKeys.length+s.groupKeys.length+s.marketKeys.length===0)return null;const r=Zp(s);return{additions:[{input:a,...r?{audience:r}:{},...n==="advanced"&&!di(s)&&s.contexts.length>0?{contexts:s.contexts}:{},...n==="advanced"&&s.queryClass!=="auto"&&s.queryClass!=="keep"?{queryClass:s.queryClass}:{}}],removals:[]}}function Xp(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 Zp(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 di(t){return t.marketKeys.length>0&&t.targetKeys.length===0&&t.groupKeys.length===0}function Zr(t){return t.source==="template"&&t.template.includes("{market}")&&(t.wholeSite||t.marketKeys.length===0)}function vr(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 eg(t,s){return s.measurementScope==="project"?!1:s.measurementScopeKey?!(s.measurementScope==="group"?t.groups:s.measurementScope==="property"?t.targets:t.markets).some(a=>a.stableKey===s.measurementScopeKey):!0}function jr(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 ui(t,s){return s.queryClass!=="all"&&(t.queryClass??"unknown")!==s.queryClass?!1:s.measurementScope==="project"||!s.measurementScopeKey?!0:s.measurementScope==="property"?t.targetKey===s.measurementScopeKey:s.measurementScope==="group"?t.groupKeys.includes(s.measurementScopeKey):t.marketKeys.includes(s.measurementScopeKey)}function tg(t,s,n){return n==="simple"?[...t]:t.filter(a=>a.assignments.length===0?s.measurementScope==="project"&&(s.queryClass==="all"||s.queryClass==="unknown"):a.assignments.some(r=>ui(r,s)))}function sg({selection:t,onSelectionChange:s}){return e.jsxs("label",{className:"min-w-40 flex-1",children:[e.jsx("span",{className:"mb-1 block text-xs font-medium text-secondary",children:"Query type"}),e.jsxs("select",{"aria-label":"Query type",className:"h-11 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:t.queryClass,onChange:n=>s?.({queryClass:n.target.value}),children:[e.jsx("option",{value:"all",children:"All query types"}),e.jsx("option",{value:"non-brand",children:"Non-brand"}),e.jsx("option",{value:"branded",children:"Branded"}),e.jsx("option",{value:"unknown",children:"Unclassified"})]})]})}function Nr(t){return t.measurementScopeKey&&t.measurementScope!=="project"?`${t.measurementScope}:${t.measurementScopeKey}`:"project"}function ng({workspace:t,selection:s,onSelectionChange:n}){const a=l.useMemo(()=>{const o=new Map(t.targets.map(i=>[i.stableKey,[]]));for(const i of t.groups)for(const c of i.targetKeys)o.get(c)?.push(i.stableKey);return[{id:"project",label:"Whole site",kind:"project",targetCount:t.targets.length},...t.groups.map(i=>({id:i.stableKey,label:i.label,kind:"group",targetCount:i.targetKeys.length,...i.parentGroupKey?{parentGroupIds:[i.parentGroupKey]}:{}})),...t.markets.map(i=>({id:i.stableKey,label:i.label,kind:"market",targetCount:new Set(i.usageEdges.map(c=>c.targetKey)).size,...i.groupKey?{parentGroupIds:[i.groupKey]}:{}})),...t.targets.map(i=>({id:i.stableKey,label:i.label,kind:"property",targetCount:1,...o.get(i.stableKey)?.length?{parentGroupIds:o.get(i.stableKey)}:{}}))]},[t.groups,t.markets,t.targets]),r=a.find(o=>o.kind===s.measurementScope&&(o.kind==="project"||o.id===s.measurementScopeKey))??a[0];return e.jsx(_l,{options:a,selected:r,onSelect:o=>{n?.({measurementScope:o.kind,measurementScopeKey:o.kind==="project"?void 0:o.id})}})}function ag(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 Yl(t,s,n){const a=new Map(s.targets.map(g=>[g.stableKey,g.label])),r=new Map(s.groups.map(g=>[g.stableKey,g.label])),o=new Map(s.markets.map(g=>[g.stableKey,g.label])),i=new Set(t.assignments.map(g=>g.targetKey));if(i.size===0)return"Whole site";const c=n?t.assignments.filter(g=>ui(g,n)):t.assignments,d=new Set(c.map(g=>g.targetKey));if(n?.measurementScope==="group"){const g=d.size,f=Math.max(0,i.size-g);return[`${g} ${g===1?"property":"properties"} in this group`,...f?[`Shared with ${f} other ${f===1?"property":"properties"}`]:[]].join(" · ")}const h=new Set,m=new Set;for(const g of c)g.groupKeys.forEach(f=>h.add(f)),g.marketKeys.forEach(f=>m.add(f));const b=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"}`]:d.size===1?[a.get([...d][0])??[...d][0]]:[`${d.size} properties`],p=h.size===1?r.get([...h][0])??[...h][0]:null,x=m.size===1?o.get([...m][0])??[...m][0]:null;return p&&x&&p===x?b.push(`${p} (group and market)`):(p?b.push(`Group: ${p}`):h.size>1&&b.push(`${h.size} groups`),x?b.push(`Market: ${x}`):m.size>1&&b.push(`${m.size} markets`)),b.join(" · ")}function rg({row:t,workspace:s,selection:n}){const a=ig(t,s,n);return e.jsxs("details",{className:"group min-w-48",children:[e.jsx("summary",{className:"cursor-pointer rounded px-1 py-1 text-secondary hover:bg-surface-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500",children:Yl(t,s,n)}),e.jsxs("div",{className:"mt-2 rounded border border-default bg-surface p-2 text-xs leading-5 text-secondary",children:[e.jsx("p",{className:"font-medium text-strong",children:"Assigned relationships"}),e.jsx("ul",{className:"mt-1 list-disc space-y-1 pl-4",children:a.map(r=>e.jsx("li",{children:r},r))})]})]})}function ig(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])),c=t.assignments.filter(d=>ui(d,n)).map(d=>{const h=a.get(d.targetKey)??d.targetKey??"Whole site",m=n.measurementScope==="group"&&n.measurementScopeKey?d.groupKeys.filter(b=>b===n.measurementScopeKey).map(b=>r.get(b)??b):d.groupKeys.map(b=>r.get(b)??b),u=n.measurementScope==="market"&&n.measurementScopeKey?d.marketKeys.filter(b=>b===n.measurementScopeKey).map(b=>o.get(b)??b):d.marketKeys.map(b=>o.get(b)??b);return[h,m.length?`Groups: ${m.join(", ")}`:null,u.length?`Markets: ${u.join(", ")}`:null].filter(b=>b!==null).join(" · ")});return[...new Set(c)].length?[...new Set(c)]:["Whole site"]}function og({row:t}){const s=[...new Set(t.assignments.map(a=>a.queryClass??"unknown"))],n=s.join(", ");return e.jsx(ue,{tone:s.includes("unknown")?"caution":"neutral",children:n||"Unknown"})}function lg({row:t,outsidePlan:s=!1}){return s?e.jsx(ue,{tone:"neutral",children:"Not in current plan"}):t.state==="tracked"?e.jsx(ue,{tone:"positive",children:"Measured"}):e.jsx(ue,{tone:"caution",children:"Awaiting sweep"})}function cg({workspace:t,templates:s,action:n,draft:a,onDraftChange:r,onClose:o,canReview:i,isPreviewing:c,editorHeadingRef:d,onReview:h}){const m=s.length>0;return n.kind==="remove"?e.jsxs(ye,{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(wr,{canReview:i,isPreviewing:c,onCancel:o,onReview:h})]}):n.kind==="edit"?e.jsxs(ye,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline gap-4",children:[e.jsx("h3",{ref:d,tabIndex:-1,children:"Edit query"}),e.jsx(P,{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:u=>r({...a,text:u.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:u=>r({...a,queryClass:u.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(wr,{canReview:i,isPreviewing:c,onCancel:o,onReview:h})]}):e.jsxs(ye,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline gap-4",children:[e.jsx("h3",{ref:d,tabIndex:-1,children:"Add query"}),e.jsx(P,{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:u=>r({...a,text:u.target.value})})]}):null,a.source==="template"?e.jsx(dg,{templates:s,draft:a,onDraftChange:r}):null,a.source==="research"?e.jsx(bo,{id:"tracking-research-source",label:"Saved research query",value:a.researchRunQueryId,options:t.savedSources.research.map(u=>({id:u.researchRunQueryId,label:u.queryText,detail:u.researchRunId})),onChange:u=>r({...a,researchRunQueryId:u})}):null,a.source==="discovery"?e.jsx(bo,{id:"tracking-discovery-source",label:"Discovery query",value:a.discoveryProbeId,options:t.savedSources.discovery.map(u=>({id:u.discoveryProbeId,label:u.queryText,detail:u.discoverySessionId})),onChange:u=>r({...a,discoveryProbeId:u})}):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","aria-describedby":m?void 0:"tracking-query-source-no-templates",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:u=>r({...a,source:u.target.value}),children:[e.jsx("option",{value:"manual",children:"Write a question"}),m?e.jsx("option",{value:"template",children:"Saved template"}):null,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)":""]})]})]}),m?null:e.jsx("p",{id:"tracking-query-source-no-templates",className:"text-sm leading-6 text-secondary",children:"No saved templates are set up for this portfolio. Write a question, or use saved research or a discovery result."})]}),e.jsx(mg,{workspace:t,draft:a,onDraftChange:r})]}),t.mode==="advanced"&&!di(a)?e.jsx("div",{className:"mt-4",children:e.jsx(ug,{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:u=>r({...a,queryClass:u.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(wr,{canReview:i,isPreviewing:c,onCancel:o,onReview:h})]})}function dg({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":Zr(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]}),Zr(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 bo({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 mi(t){return{providers:[...t.providers],models:{...t.models},location:t.location?.label??null}}function Hn(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 Jl(t){return[...new Map(t.map(s=>[Hn(s),s])).values()]}function hi(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 ug({workspace:t,draft:s,onDraftChange:n}){const a=l.useMemo(()=>Jl([...t.defaultContexts.map(mi),...s.contexts]),[s.contexts,t.defaultContexts]),r=s.contexts.length===1?Hn(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(d=>Hn(d)===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:Hn(o),children:hi(o)},Hn(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 mg({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(p=>({kind:"target",key:p.stableKey,label:p.label,detail:"Property"})),...t.groups.map(p=>({kind:"group",key:p.stableKey,label:p.label,detail:"Group"})),...t.markets.map(p=>({kind:"market",key:p.stableKey,label:p.label,detail:"Market"}))],[t.groups,t.markets,t.targets]),d=a.trim().toLocaleLowerCase(),h=d?c.filter(p=>`${p.label} ${p.detail}`.toLocaleLowerCase().includes(d)):c,m=s.targetKeys.length+s.groupKeys.length+s.marketKeys.length>0;function u(p,x,g){const f=p==="target"?"targetKeys":p==="group"?"groupKeys":"marketKeys",S=s[f];n({...s,wholeSite:!1,[f]:g?[...S,x]:S.filter(j=>j!==x)})}function b(p,x){return(p==="target"?s.targetKeys:p==="group"?s.groupKeys:s.marketKeys).includes(x)}if(!o){const p=t.targets.find(x=>x.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: ",p?.label??s.targetKeys[0]]}),e.jsx(P,{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:p=>{n({...s,wholeSite:p.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(zs,{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(p=>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":`${p.label}, ${p.detail}`,checked:b(p.kind,p.key),onChange:x=>u(p.kind,p.key,x.target.checked)}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:p.label}),e.jsx("span",{className:"text-xs text-muted",children:p.detail})]},`${p.kind}:${p.key}`))})]})}function wr({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(Je,{type:"button",size:"sm",disabled:!t,onClick:a,children:s?"Reviewing…":"Review changes"}),e.jsx(P,{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 hg({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(ye,{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(ue,{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(vo,{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(vo,{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(Je,{type:"button",size:"sm",disabled:!o||n,onClick:a,children:n?"Confirming…":"Confirm changes"})})]})}function vo({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`:pg(r,a,n)}),t==="Added"||t==="Reused"?e.jsx(xg,{row:a.find(o=>o.queryId===r.queryId),workspace:n}):null]},`${t}:${r.queryId}`))})]})}function xg({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(d=>d.stableKey===a.targetKey)?.label??a.targetKey,i=a.queryClass==="branded"?"Branded":a.queryClass==="non-brand"?"Non-brand":"Unknown",c=a.contexts.map(d=>hi(mi(d))).join("; ");return e.jsx("li",{children:[o,i,c].filter(Boolean).join(" · ")},`${a.targetKey}:${r}`)})})]})}function pg(t,s,n){const a=s.find(i=>i.queryId===t.queryId);if(!a)return`${t.assignmentCount} ${t.assignmentCount===1?"assignment":"assignments"}`;const r=Jl(a.assignments.flatMap(i=>i.contexts).map(mi)),o=r.length===1?hi(r[0]):r.length>1?`${r.length} contexts`:null;return[Yl(a,n),o].filter(i=>i!==null).join(" · ")}function gg({projectName:t,selection:s={measurementScope:"project",queryClass:"all"},onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:o,onPendingTrackingSourceHandled:i}){const c=ms(),[d,h]=l.useState(null),m=Te({...dl({client:Y,path:{name:t}})}),u=Te({...ul({client:Y,path:{name:t}}),staleTime:6e4}),b=Tt({...wd(),onSuccess:x=>h(x),onError:async x=>{h(null),await c.invalidateQueries({queryKey:Nd({client:Y,path:{name:t}})}),$e({title:"Could not review tracking changes",detail:x instanceof Error?x.message:"Update the draft and review it again.",tone:"negative"})}}),p=Tt({...Sd(),onSuccess:async x=>{h(null),r?.(void 0),await Pi(c,t),$e({title:x.committed?"Tracked queries updated":"No tracked-query change",detail:x.active?`Measurement revision ${x.active.revision}.`:"No measurement revision is published yet.",tone:x.committed?"positive":"neutral",dedupeKey:`query-tracking:commit:${t}`,dedupeMode:"replace"})},onError:async x=>{h(null),await Pi(c,t),$e({title:"Could not confirm tracking changes",detail:x instanceof Error?x.message:"The review may be stale. Review the changes again.",tone:"negative"})}});return m.isLoading?e.jsx(ye,{className:"surface-card",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading tracked queries…"})}):m.isError||!m.data?e.jsxs(ye,{className:"surface-card",children:[e.jsx("p",{className:"text-sm text-negative",children:"Could not load tracked queries."}),e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:()=>{m.refetch()},children:"Try again"})]}):e.jsx(Yp,{workspace:m.data,selection:s,onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:o,onPendingTrackingSourceHandled:i,templates:u.data?.templates??[],preview:d,isPreviewing:b.isPending,isCommitting:p.isPending,onPreview:x=>{h(null),b.mutate({client:Y,path:{name:t},body:{...x,expectedWorkspaceVersion:m.data.workspaceVersion}})},onCommit:x=>p.mutate({client:Y,path:{name:t},body:x})})}function fg({projectName:t,onReviewDiscoveryProbe:s}){const n=ms(),[a,r]=l.useState(null),[o,i]=l.useState(""),[c,d]=l.useState("100"),h=Te({...Cd({client:Y,path:{name:t},query:{limit:"10"}}),refetchInterval:j=>j.state.data?.some(A=>Xr.has(A.status))?3e3:!1}),m=h.data??[];l.useEffect(()=>{!a&&m[0]&&r(m[0].id)},[a,m]);const u=m.find(j=>j.id===a)??null,b=Te({...kd({client:Y,path:{name:t,id:a??""}}),enabled:!!a,refetchInterval:u&&Xr.has(u.status)?3e3:!1}),p=b.data??null,x=Tt({mutationFn:()=>{const j={},D=o.trim();D&&(j.icpDescription=D);const A=Number.parseInt(c,10);return Number.isFinite(A)&&A>0&&(j.maxProbes=A),Ad(t,j)},onSuccess:async j=>{r(j.sessionId),i(""),await jg(n,t,j.sessionId),$e({title:"Discovery started",detail:`Run ${Sr(j.sessionId)} is testing questions your customers might ask.`,tone:"neutral",dedupeKey:`discovery:start:${j.sessionId}`,dedupeMode:"replace"})},onError:j=>{$e({title:"Discovery failed to start",detail:j instanceof Error?j.message:"Could not start discovery.",tone:"negative"})}}),g=p??u,f=l.useMemo(()=>(p?.probes??[]).slice(0,30),[p?.probes]);async function S(){try{const j=await h.refetch();if(j.error)throw j.error;const D=j.data?.length??0;$e({title:"Discovery sessions refreshed",detail:`${D} recent session${D===1?"":"s"} loaded.`,tone:"positive",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}catch(j){$e({title:"Discovery refresh failed",detail:j instanceof Error?j.message:"Could not reload discovery sessions.",tone:"negative",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}}return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 1"}),e.jsx("h2",{children:"Generate and check questions"}),e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-secondary",children:ie()?"Generate customer questions and check whether your site is already visible.":"Generate customer questions, check current visibility, then choose what to track."})]}),e.jsxs(P,{type:"button",variant:"outline",size:"sm",disabled:h.isFetching,onClick:()=>{S()},children:[e.jsx(ta,{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(ye,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 1"}),e.jsx("h3",{children:"Describe your customer"})]}),e.jsx(ue,{tone:"neutral",children:"Runs on Gemini"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm text-secondary",children:"Who is your ideal customer?"}),e.jsx("textarea",{className:"mt-1 min-h-24 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:"e.g. Small e-commerce stores that want AI-powered customer support. Leave blank to use the customer profile saved on this project.",value:o,onChange:j=>i(j.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:j=>d(j.target.value)}),e.jsx("span",{className:"mt-1 block text-sm text-secondary",children:"More questions means broader coverage but a longer run. 100 is a good default."})]}),!ie()&&e.jsxs(Je,{type:"button",size:"sm",disabled:x.isPending,onClick:()=>x.mutate(),children:[e.jsx(_a,{size:14}),x.isPending?"Starting…":"Find queries"]})]})]}),e.jsxs(ye,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Recent runs"})]}),h.isFetching&&e.jsx(ue,{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(j=>e.jsxs("button",{type:"button",className:`w-full rounded-md border px-3 py-2 text-left transition-colors ${a===j.id?"border-mono-600 bg-bg-elevated/70":"border-default bg-bg/40 hover:border-strong hover:bg-bg-elevated/40"}`,onClick:()=>r(j.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:Sr(j.id)}),e.jsx(ue,{tone:jo(j.status),children:j.status})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-sm text-secondary",children:[e.jsxs("span",{children:["Cited queries ",j.citedCount??0]}),e.jsxs("span",{children:["Worth tracking ",j.aspirationalCount??0]}),e.jsxs("span",{children:["Skip ",j.wastedCount??0]})]})]},j.id))})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(ye,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Run detail"}),e.jsx("h3",{children:g?Sr(g.id):"No run selected"})]}),g&&e.jsx(ue,{tone:jo(g.status),children:g.status})]}),g?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(Ca,{label:"Questions tested",value:g.probeCount??0}),e.jsx(Ca,{label:"Cited queries",value:g.citedCount??0,tone:"positive"}),e.jsx(Ca,{label:"Worth tracking",value:g.aspirationalCount??0,tone:"caution"}),e.jsx(Ca,{label:"Skip",value:g.wastedCount??0,tone:"negative"})]}),g.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:g.error}),g.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:g.warning}),g.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:g.icpDescription})]}),g.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:g.competitorMap.slice(0,8).map(j=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[j.domain," ",e.jsx("span",{className:"text-muted",children:j.hits})]},j.domain))})]})]}):e.jsx("p",{className:"text-sm text-secondary",children:"Start a run above, or pick one from Recent runs to see its progress."})]}),g?.status==="completed"&&e.jsxs(ye,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"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(ye,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"All results"}),e.jsx("h3",{children:"Every question we tested"})]}),b.isFetching&&e.jsx(ue,{tone:"neutral",children:"Loading"})]}),f.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:f.map(j=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:j.query}),e.jsx("td",{children:e.jsx(ue,{tone:yg(j.bucket),children:vg(j.bucket)})}),e.jsx("td",{className:"text-secondary",children:j.citedDomains.length>0?j.citedDomains.slice(0,3).join(", "):"-"}),e.jsx("td",{className:"whitespace-nowrap text-right",children:!ie()&&s&&(j.bucket==="cited"||j.bucket==="aspirational")&&e.jsx(Je,{type:"button",variant:"ghost",size:"sm",onClick:()=>s(j.id),children:"Review for tracking"})})]},j.id))})]})})]})]})]})]})}function Ca({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 jo(t){return t==="completed"?"positive":t==="failed"?"negative":Xr.has(t)?"caution":"neutral"}function yg(t){return t==="cited"?"positive":t==="aspirational"?"caution":t==="wasted-surface"?"negative":"neutral"}const bg={cited:"Cited queries",aspirational:"Worth tracking","wasted-surface":"Skip"};function vg(t){return t?bg[t]:"Not classified"}function Sr(t){return t.length>8?t.slice(0,8):t}async function jg(t,s,n){await Promise.all([Nt(t,"discovery"),t.invalidateQueries({queryKey:Pd({client:Y})})])}function No(t){return`${(t*100).toFixed(1)}%`}function Ng({projectName:t}){const[s,n]=l.useState("changes"),[a,r]=l.useState(null),[o,i]=l.useState(null),c=Te({...Rd({client:Y,path:{name:t},query:{limit:30}}),enabled:s==="health"}),d=Te({...Id({client:Y,path:{name:t},query:{kind:"answer-visibility",limit:100}}),enabled:s==="compare"}),h=(d.data??[]).filter(f=>(f.status==="completed"||f.status==="partial")&&f.trigger!=="probe").reverse(),m=o??h[0]?.id??"",u=a??h.find(f=>f.id!==m)?.id??"",b=!!(u&&m&&u!==m),p=Te({...Td({client:Y,path:{name:t},query:{run1:u,run2:m}}),enabled:s==="compare"&&b}),x=c.data??[],g=p.data?.diff.filter(f=>f.changed||f.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(([f,S])=>e.jsx("button",{type:"button",role:"tab","aria-selected":s===f,className:`filter-chip ${s===f?"filter-chip-active":""}`,onClick:()=>n(f),children:S},f))}),s==="changes"?e.jsx(ah,{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&&x.length===0?e.jsxs(ye,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No coverage history yet"}),e.jsx("p",{children:Bt()?Js:"Complete an answer visibility sweep to create the first snapshot."})]}):null,x.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:x.map(f=>e.jsxs("tr",{children:[e.jsx("td",{className:"whitespace-nowrap tabular-nums text-secondary",children:new Date(f.createdAt).toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[f.mentionedPairs,"/",f.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:No(f.overallMentionRate)}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[f.citedPairs,"/",f.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:No(f.overallCitedRate)})]},f.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:u,onChange:f=>r(f.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(f=>e.jsx("option",{value:f.id,children:new Date(f.createdAt).toLocaleString()},f.id))})]}),e.jsxs("label",{className:"text-xs text-muted",children:["Later run",e.jsx("select",{value:m,onChange:f=>i(f.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(f=>e.jsx("option",{value:f.id,children:new Date(f.createdAt).toLocaleString()},f.id))})]})]}),d.isLoading||p.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Comparing runs…"}):null,!d.isLoading&&h.length<2?e.jsxs(ye,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"Two completed sweeps are required"}),e.jsx("p",{children:Bt()?Js:"Run another answer visibility sweep before comparing historical evidence."})]}):null,p.data&&g.length===0?e.jsxs(ye,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No mention or citation changes"}),e.jsx("p",{children:"The selected sweeps have the same states for every comparable tracked query."})]}):null,g.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:g.map(f=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:f.query??"Archived query"}),e.jsx("td",{children:e.jsxs(ue,{tone:f.changed?"caution":"neutral",children:[f.run1State??"none"," → ",f.run2State??"none"]})}),e.jsx("td",{children:e.jsxs(ue,{tone:f.visibilityChanged?"caution":"neutral",children:[f.run1MentionState??"none"," → ",f.run2MentionState??"none"]})})]},f.queryId??f.query??"unknown"))})]})}):null]}):null]})}const wo={state:"not-connected",selection:null,snapshotCount:0,evidence:"No stored evidence yet.",lastSnapshotAt:null},wg={contract:null,assessment:null,googleAds:wo,gtm:wo,snapshots:[]};function Sg(t){return t.contractSelectionRequired?"contract-selection-required":t.assessmentState==="loading"?"assessment-loading":t.assessmentState==="unavailable"?"assessment-unavailable":Pg(t)?"static-mismatch":t.assessment?.status??(t.contract?"configured":"not-configured")}function Cg(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 kg(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 Ag(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 Xl(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"&&Rg(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 Pg(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome==="fail")}function Rg(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome!=="pass")}function Zl(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 Ig(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 Tg(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 on(t){return t.length<=12?t:`…${t.slice(-10)}`}function $g(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 Mg(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 Cr={"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 So(t){return t.outcome==="pass"?{label:Cr[t.code],tone:"positive",outcome:"Pass"}:t.outcome==="fail"?{label:Cr[t.code],tone:"negative",outcome:"Fail"}:{label:Cr[t.code],tone:"caution",outcome:"Unknown"}}function Lg(t){return t.runtime.productionHosts.length>0?t.runtime.productionHosts.join(", "):"the declared production site"}function qg(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 Eg(t){return t.provider==="google-ads"?"Google Ads":"Tag Manager"}function Co({label:t,connection:s,changeSelectionLabel:n,onChangeSelection:a,actionPending:r}){const o=Zl(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(ue,{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 ${Ht(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(Je,{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 Dg="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.",Og="Available once Google Ads and Tag Manager are connected.",Fg="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 Kg({workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:n,onChangeGtmSelection:a,actionPending:r,actionError:o}){const i=t.googleAds.state==="connected",c=t.gtm.state==="connected",d=t.googleAds.state==="unavailable",h=t.gtm.state==="unavailable",m=d||h||t.gtm.state==="unavailable",u={id:"retry-connection-status",label:"Retry connection status",detail:"Retry the stored connection reads before starting another provider action."},b=!i&&!c,p=[{title:"Google Ads",state:t.googleAds.state,ready:i,summary:t.googleAds.selection,changeLabel:"Change Google Ads account",onChange:n,action:d?u:kg(t)},{title:"Tag Manager",state:t.gtm.state,ready:c,summary:t.gtm.selection,changeLabel:"Change Tag Manager container",onChange:a,action:h?u:Ag(t)}],x=i&&c&&!m?Xl(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(Ve,{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."})]}),b?e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-secondary",children:Fg}):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(Ve,{text:Dg})]}),x&&s?e.jsx(Je,{type:"button",disabled:r,onClick:()=>s(x.id),children:r?"Working…":x.label}):e.jsx("p",{className:"text-sm text-secondary",children:Og})]}),e.jsx("ul",{className:"flex flex-wrap items-center gap-x-6 gap-y-2 border-b border-default py-3",children:p.map(g=>{const f=g.ready?{label:"Ready",tone:"positive"}:Zl(g.state),S=g.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:g.title}),e.jsx(ue,{tone:f.tone,children:f.label}),g.summary?e.jsx("span",{className:"min-w-0 truncate text-secondary",children:g.summary}):null,S&&s?S.id==="retry-connection-status"?e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(S.id),children:r?"Working…":S.label}):e.jsx(Je,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(S.id),children:r?"Working…":S.label}):null,g.summary&&g.onChange?e.jsx(Je,{type:"button",variant:"ghost",size:"sm","aria-label":g.changeLabel,disabled:r,onClick:g.onChange,children:"Change"}):null]},g.title)})}),o?e.jsx("p",{role:"alert",className:"mt-3 text-sm text-negative",children:o}):null]})]})}function Gg({workspace:t=wg,onPrimaryAction:s,actionPending:n=!1,actionError:a=null,contracts:r=[],selectedContractId:o=null,onSelectContract:i,contractError:c=null,onRetryContracts:d,onRetryEvidence:h,onChangeGoogleAdsSelection:m,onChangeGtmSelection:u,onAddContract:b}){const p=Sg(t),x=Cg(p),g=Xl(t),f=t.assessment?.findings??[],S=f.filter(y=>y.outcome!=="pass"),j=f.filter(y=>y.outcome==="pass"),D=S.some(y=>y.outcome==="fail")?"negative":"caution";return r.length===0&&t.contract===null&&!t.contractSelectionRequired&&c===null?e.jsx(Kg,{workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:m,onChangeGtmSelection:u,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(ue,{tone:x.tone,children:x.label}),t.assessment?.evaluatedAt?e.jsxs("span",{className:"text-[11px] text-muted",children:["Assessed ",Ht(t.assessment.evaluatedAt)]}):null]}),e.jsx("p",{className:"supporting-copy mt-2 max-w-2xl",children:x.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(y=>e.jsxs("li",{className:"break-words",children:[Eg(y)," ",y.kind,", captured ",Ht(y.capturedAt),e.jsxs("span",{className:"ml-1 font-mono text-[11px] text-muted",children:["(",y.id,")"]})]},y.id))})]}):null]}),e.jsxs("div",{className:"shrink-0 lg:max-w-xs",children:[s?g.id==="review-findings"||g.id==="review-runtime-verification"||g.id==="retry-connection-status"||g.id==="select-contract"||g.id==="retry-integrity"||g.id==="waiting-for-integrity"?e.jsx(P,{type:"button",disabled:n||g.id==="waiting-for-integrity",onClick:()=>s(g.id),children:n?"Working…":g.label}):e.jsx(Je,{type:"button",disabled:n,onClick:()=>s(g.id),children:n?"Working…":g.label}):g.id==="review-findings"?e.jsx(P,{asChild:!0,type:"button",children:e.jsx("a",{href:"#conversion-integrity-findings",children:"Review findings"})}):p==="runtime-unverified"?e.jsx(P,{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:g.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&&b?e.jsx(Je,{type:"button",variant:"outline",size:"sm",disabled:n,onClick:b,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:y=>i?.(y.target.value),children:[e.jsx("option",{value:"",children:"Choose a declared conversion"}),r.map(y=>e.jsx("option",{value:y.id,children:y.name},y.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:$g(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:Mg(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:on(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:on(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:on(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:on(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}),d?e.jsx(P,{type:"button",variant:"outline",onClick:d,children:"Retry contracts"}):null]}):null,t.assessmentError?e.jsx("p",{role:"alert",className:"mt-4 text-sm text-negative",children:t.assessmentError}):null]}),S.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(ue,{tone:D,children:[S.length," ",S.length===1?"check":"checks"]})]}),e.jsx("ul",{className:"divide-y divide-default border-y border-default",children:S.map(y=>{const w=So(y);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:w.label}),e.jsx(ue,{tone:w.tone,children:w.outcome})]}),e.jsxs("p",{className:"mt-1 break-words text-sm text-secondary",children:["Related item: ",y.subject]}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",y.code]}),y.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",y.evidenceIds.join(", ")]}):null]},`${y.code}:${y.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(Ve,{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(y=>{const w=Ig(y.key,p);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 ${w==="positive"?"bg-positive-fill":w==="caution"?"bg-caution-fill":w==="negative"?"bg-negative-fill":"bg-neutral-fill"}`}),e.jsx("span",{className:"text-sm font-medium text-heading",children:y.title})]}),e.jsx("p",{className:"text-sm text-secondary",children:y.detail}),e.jsx(ue,{tone:w,children:Tg(y.key,p)})]},y.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:[Co({label:"Google Ads",connection:t.googleAds,...t.googleAds.state==="connected"||t.googleAds.state==="stale"?{changeSelectionLabel:"Change Google Ads account",onChangeSelection:m}:{},actionPending:n}),Co({label:"Google Tag Manager",connection:t.gtm,...t.gtm.state==="connected"||t.gtm.state==="stale"?{changeSelectionLabel:"Change Tag Manager container",onChangeSelection:u}:{},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(P,{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(y=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:y.provider==="google-ads"?"Google Ads":"Google Tag Manager"}),e.jsx("td",{className:"text-secondary",children:y.kind}),e.jsx("td",{className:"text-secondary",children:Ht(y.capturedAt)}),e.jsx("td",{className:"font-mono text-[11px] text-muted",children:on(y.id)})]},y.id))})]})})]}):null,j.length>0?e.jsxs("details",{className:"inline-disclosure mt-8",children:[e.jsxs("summary",{children:[j.length," ",j.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:j.map(y=>{const w=So(y);return e.jsxs("tr",{children:[e.jsxs("td",{className:"text-secondary",children:[e.jsx("p",{children:w.label}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",y.code]}),y.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",y.evidenceIds.join(", ")]}):null]}),e.jsx("td",{children:e.jsx(ue,{tone:w.tone,children:w.outcome})}),e.jsx("td",{className:"break-words text-secondary",children:y.subject})]},`${y.code}:${y.subject}`)})})]})})]}):null,p==="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 ",Lg(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:on(t.contract.gtm.tagId)})," fires with ",qg(t.contract),"."]}),e.jsxs("li",{children:["Confirm Google Ads records the matching conversion action ",e.jsx("span",{className:"font-mono text-heading",children:on(t.contract.googleAds.conversionActionId)}),". Do not change the account or publish a Tag Manager version just to verify it."]})]})]}):null]})}const ln=3e4,ko={name:"",eventName:"",conversionActionId:"",conversionId:"",conversionLabel:"",campaignIds:"",tagId:"",triggerIds:"",variableIds:"",productionHosts:"",requireBiddableGoal:!0,requirePrimaryAction:!0,verificationRequired:!0,requireTransactionId:!0,requireValue:!0,requireCurrency:!0},Dt="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",ls="text-sm font-medium text-secondary";function Ao(t,s,n,a){return n?{snapshotCount:t,snapshotState:"unavailable",snapshotError:ft(a)}:s?{snapshotCount:t,snapshotState:"loading"}:{snapshotCount:t}}function ka(t){return[...new Set(t.split(/[\n,]/).map(s=>s.trim()).filter(Boolean))]}function _g(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 Ug(t,s,n){const a=[`Container ${t}`,`account ${s}`];return n&&a.push(`workspace ${n}`),a.join(" · ")}function Bg(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:Ug(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 Vg(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:ka(t.campaignIds),requireBiddableGoal:t.requireBiddableGoal,requirePrimaryAction:t.requirePrimaryAction},gtm:{accountId:n.accountId,containerId:n.containerId,tagId:t.tagId.trim(),triggerIds:ka(t.triggerIds),variableIds:ka(t.variableIds)},runtime:{verificationRequired:t.verificationRequired,requireTransactionId:t.requireTransactionId,requireValue:t.requireValue,requireCurrency:t.requireCurrency,productionHosts:ka(t.productionHosts)}}}function Po(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 Aa(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 Pa(t,s,n){return t?"no longer accessible":n?"access not verified":s?"not in the current result":"checking access"}function Ra({id:t,label:s,value:n,onChange:a,children:r,disabled:o=!1}){return e.jsxs("label",{htmlFor:t,className:ls,children:[s,e.jsx("select",{id:t,className:Dt,value:n,onChange:i=>a(i.target.value),disabled:o,children:r})]})}function kn({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 Ro({providerLabel:t,disabled:s,onDisconnect:n}){const[a,r]=l.useState(!1),[o,i]=l.useState(!1),[c,d]=l.useState(null),h=l.useRef(null),m=l.useRef(null),u=l.useRef(!1);l.useEffect(()=>{const g=u.current;u.current=a,a?m.current?.focus():g&&h.current?.querySelector("button")?.focus()},[a]);function b(){d(null),r(!0)}function p(){d(null),r(!1)}async function x(){i(!0),d(null);try{await n()}catch(g){d(ft(g)),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(P,{ref:m,type:"button",variant:"outline",size:"sm",className:"min-h-11",disabled:o,onClick:p,children:"Keep connected"}),e.jsx(Je,{type:"button",variant:"destructive",size:"sm",className:"min-h-11",disabled:s||o,onClick:()=>{x()},children:o?"Disconnecting…":`Disconnect ${t}`})]}),c?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:c}):null]}):e.jsxs(Je,{type:"button",variant:"ghost",size:"sm",className:"min-h-11 text-negative hover:text-negative",disabled:s,onClick:b,children:["Disconnect ",t]})})}function Io({id:t,label:s,options:n,synced:a,loading:r,failed:o,onRetry:i,emptyHint:c,value:d,onChange:h}){const m=n.some(g=>g.id===d),[u,b]=l.useState(!1),p=u||d!==""&&!m&&n.length>0,x=e.jsx("label",{htmlFor:t,className:ls,children:s});return r?e.jsxs("div",{children:[x,e.jsx("select",{id:t,className:Dt,disabled:!0,children:e.jsx("option",{children:"Loading…"})})]}):o?e.jsxs("div",{children:[x,e.jsx("input",{id:t,required:!0,className:Dt,value:d,onChange:g=>h(g.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:[x,e.jsx("input",{id:t,required:!0,className:Dt,value:d,onChange:g=>h(g.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:[x,p?e.jsx("input",{id:t,required:!0,className:Dt,value:d,onChange:g=>h(g.target.value)}):e.jsxs("select",{id:t,required:!0,className:Dt,value:d,onChange:g=>h(g.target.value),children:[e.jsxs("option",{value:"",children:["Select ",s.toLowerCase()]}),n.map(g=>e.jsxs("option",{value:g.id,children:[g.name,g.detail?` (${g.detail})`:"",g.active?"":" — inactive"]},g.id))]}),e.jsx("button",{type:"button",className:"mt-1 text-xs text-link",onClick:()=>{b(!p),h("")},children:p?"Choose from synced list":"Enter an ID manually"})]})}function Qg({projectId:t,projectName:s}){const n=bn(),[a,r]=l.useState(null),[o,i]=l.useState(null),[c,d]=l.useState(!1),[h,m]=l.useState(""),[u,b]=l.useState(null),[p,x]=l.useState(!1),[g,f]=l.useState(!1),[S,j]=l.useState(""),[D,A]=l.useState(""),[y,w]=l.useState(""),[N,M]=l.useState(""),[L,F]=l.useState(""),[H,O]=l.useState(!1),[J,G]=l.useState(ko),[C,ae]=l.useState(null),q=l.useRef(null),se=Te({...$d({client:Y,path:{name:s}}),staleTime:ln}),V=Te({...Md({client:Y,path:{name:s}}),staleTime:ln}),B=Te({...Ld({client:Y,path:{name:s}}),staleTime:ln}),E=Te({...qd({client:Y,path:{name:s}}),staleTime:ln}),R=E.data,oe=Te({...Ed({client:Y,path:{name:s},query:{limit:5}}),staleTime:ln}),T=Te({...Dd({client:Y,path:{name:s},query:{limit:5}}),staleTime:ln}),ee=B.data??[],ge=(C?ee.find($=>$.id===C)??null:null)??(ee.length===1?ee[0]??null:null),X=ee.length>1&&!ge,de=Te({...Od({client:Y,path:{name:s,contractId:ge?.id??""}}),enabled:!!ge,staleTime:ln}),xe=Te({...Fd({client:Y,path:{name:s}}),enabled:u==="google-ads"&&se.data?.connected===!0,staleTime:0}),ne=Te({...Kd({client:Y,path:{name:s}}),enabled:u==="gtm"&&V.data?.connected===!0,staleTime:0}),Q=Te({...Gd({client:Y,path:{name:s,accountId:y}}),enabled:u==="gtm"&&!!y,staleTime:0}),re=Te({..._d({client:Y,path:{name:s,accountId:y,containerId:N}}),enabled:u==="gtm"&&!!y&&!!N,staleTime:0}),Ee=Tt(Ud({client:Y})),we=Tt(Bd({client:Y})),Se=Tt(Vd({client:Y})),et=Tt(Qd({client:Y})),Ke=Tt(zd({client:Y})),Qe=Tt(Wd({client:Y})),We=Tt(Hd({client:Y})),Ge=Tt(Yd({client:Y})),_=Tt(Jd({client:Y}));l.useEffect(()=>{if(u!=="google-ads"||p||!se.isSuccess)return;const $=se.data.connection?.selection;j($?.customerId??""),A($?.loginCustomerId??""),x(!0)},[p,se.data,se.isSuccess,u]),l.useEffect(()=>{if(u!=="gtm"||g||!V.isSuccess)return;const $=V.data.selection;w($?.accountId??""),M($?.containerId??""),F($?.workspaceId??""),f(!0)},[g,V.data,V.isSuccess,u]),l.useEffect(()=>{!C||!B.data||B.data.some($=>$.id===C)||ae(null)},[B.data,C]);const U=l.useMemo(()=>{const $=oe.data?.snapshots??[],pe=T.data?.snapshots??[],it=[...$.map(Pt=>({id:Pt.id,provider:"google-ads",kind:Pt.kind,capturedAt:Pt.capturedAt})),...pe.map(Pt=>({id:Pt.id,provider:"gtm",kind:Pt.kind,capturedAt:Pt.capturedAt}))].sort((Pt,vn)=>vn.capturedAt.localeCompare(Pt.capturedAt)).slice(0,5),At=[],Oe=de.data?.googleAdsSnapshot,Kt=de.data?.gtmSnapshot;return Oe&&At.push({id:Oe.id,provider:"google-ads",kind:Oe.kind,capturedAt:Oe.capturedAt}),Kt&&At.push({id:Kt.id,provider:"gtm",kind:Kt.kind,capturedAt:Kt.capturedAt}),{contract:de.data?.assessment.contract??ge,assessment:de.data?.assessment??null,contractSelectionRequired:X,assessmentState:ge?de.isError?"unavailable":de.isLoading?"loading":void 0:void 0,assessmentError:de.isError?ft(de.error):null,googleAds:_g(se.data,Ao(oe.data?.total??0,oe.isLoading,oe.isError,oe.error),se.isError),gtm:Bg(V.data,Ao(T.data?.total??0,T.isLoading,T.isError,T.error),V.isError),snapshots:it,assessmentEvidenceSnapshots:At}},[ge,X,oe.data,oe.error,oe.isError,oe.isLoading,se.data,se.isError,T.data,T.error,T.isError,T.isLoading,V.data,V.isError,de.data,de.error,de.isError,de.isLoading]),W=l.useSyncExternalStore(ll,Oa,Oa),Re=Object.values(W.runs).some($=>$.projectId===t&&($.kind===Ys["google-ads-sync"]||$.kind===Ys["gtm-sync"])),_e=Ee.isPending||we.isPending||Se.isPending||et.isPending||Ke.isPending||Qe.isPending||We.isPending||Ge.isPending||_.isPending||Re;async function Ue(){await Promise.all([se.refetch(),V.refetch(),B.refetch(),oe.refetch(),T.refetch(),E.refetch(),ge?de.refetch():Promise.resolve()])}async function le($){await Ue();for(let pe=0;pe<10&&!$();pe+=1)await new Promise(it=>setTimeout(it,1500)),await Ue()}function pt(){const $=document.activeElement;q.current=$ instanceof HTMLElement?$:null}function ut($){if(typeof window<"u"&&typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame($);return}globalThis.setTimeout($,0)}function ze(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Fe($){if(!$)return;!$.matches('a[href], button, input, select, textarea, [contenteditable="true"]')&&!$.hasAttribute("tabindex")&&($.tabIndex=-1),$.focus({preventScroll:!0})}function wt($,pe=$){const it=document.getElementById($);it instanceof HTMLDetailsElement&&(it.open=!0);const At=it?.scrollIntoView;typeof At=="function"&&At.call(it,{behavior:ze()?"auto":"smooth",block:"start"}),Fe(document.getElementById(pe)??it)}function Be($,pe){pt(),ut(()=>wt($,pe))}function Me(){const $=q.current;q.current=null,$&&ut(()=>{$.isConnected&&$.focus({preventScroll:!0})})}function tt(){r(null),d(!1),Me()}function $t(){r(null),b(null),Me()}function Mt(){r(null),O(!1),Me()}function De(){r(null),b(null),d(!0),Be("google-ads-connect-panel","google-ads-connect-title")}function k(){r(null),j(""),A(""),x(!1),b("google-ads"),d(!1),Be("google-ads-selection-panel","google-ads-selection-title")}function Ae(){r(null),w(""),M(""),F(""),f(!1),b("gtm"),d(!1),Be("gtm-selection-panel","gtm-selection-title")}function ve(){r(null),O(!0),Be("conversion-integrity-contract-form","conversion-integrity-contract-form-title")}function He($,pe){ol({id:$.id,projectId:$.projectId,kind:$.kind,projectLabel:s,sourceAction:pe}),$e({title:pe==="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:${$.id}`,dedupeMode:"replace"})}async function vt(){Ns(n),r(null);try{const $=await Ee.mutateAsync({path:{name:s},body:{provider:"google-ads",...h.trim()?{developerToken:h.trim()}:{}}});m(""),d(!1),i("Finish the Google Ads consent flow in the new window. Canonry will refresh stored status after it closes."),Po($.authorizationUrl,()=>{Ue(),i(null),Me()})}catch($){r(ft($))}}async function st(){Ns(n),r(null);try{const $=await we.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."),Po($.authorizationUrl,()=>{Ue(),i(null),Me()})}catch($){r(ft($))}}async function Lt(){if(Ns(n),!S){r("Select a Google Ads customer before saving.");return}r(null);try{await Se.mutateAsync({path:{name:s},body:{customerId:S,...D.trim()?{loginCustomerId:D.trim()}:{}}}),b(null),Me(),await le(()=>se.data?.selectedCustomer!=null)}catch($){r(ft($))}}async function Xe(){if(Ns(n),!y||!N){r("Select a Tag Manager account and container before saving.");return}r(null);try{await et.mutateAsync({path:{name:s},body:{accountId:y,containerId:N,...L?{workspaceId:L}:{}}}),b(null),Me(),await le(()=>V.data?.status==="connected")}catch($){r(ft($))}}async function te(){Ns(n),r(null),await We.mutateAsync({path:{name:s}}),b(null),d(!1),j(""),A(""),x(!1),i(null),await Ue(),$e({title:"Google Ads disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`google-ads-disconnected:${t}`,dedupeMode:"replace"}),q.current=null,ut(()=>Fe(document.getElementById("conversion-integrity-title")))}async function qe(){Ns(n),r(null),await Ge.mutateAsync({path:{name:s}}),b(null),w(""),M(""),F(""),f(!1),i(null),await Ue(),$e({title:"Tag Manager disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`gtm-disconnected:${t}`,dedupeMode:"replace"}),q.current=null,ut(()=>Fe(document.getElementById("conversion-integrity-title")))}async function Ce(){Ns(n),r(null);try{const $=await Ke.mutateAsync({path:{name:s}});He($,"google-ads-sync")}catch($){r(ft($))}}async function Pe(){Ns(n),r(null);try{const $=await Qe.mutateAsync({path:{name:s}});He($,"gtm-sync")}catch($){r(ft($))}}async function Yt(){Ns(n),r(null);try{const $=await Promise.allSettled([Ke.mutateAsync({path:{name:s}}),Qe.mutateAsync({path:{name:s}})]),[pe,it]=$;pe.status==="fulfilled"&&He(pe.value,"google-ads-sync"),it.status==="fulfilled"&&He(it.value,"gtm-sync");const At=$.find(Oe=>Oe.status==="rejected");if(At?.status==="rejected")throw At.reason}catch($){r(ft($))}}async function Jt(){Ns(n);const $=se.data?.connection?.selection.customerId,pe=V.data?.selection;if(!$||!pe?.accountId||!pe.containerId){r("Select Google Ads and Tag Manager resources before declaring a conversion.");return}r(null);try{const it=await _.mutateAsync({path:{name:s},body:Vg(J,$,{accountId:pe.accountId,containerId:pe.containerId})});G(ko),O(!1),Me(),(await B.refetch()).data?.some(Oe=>Oe.id===it.id)&&ae(it.id)}catch(it){r(ft(it))}}function yt($){switch($){case"connect-google-ads":De();return;case"connect-gtm":pt(),st();return;case"select-google-ads":k();return;case"select-gtm":Ae();return;case"sync-google-ads":Ce();return;case"sync-gtm":Pe();return;case"sync-static-evidence":Yt();return;case"declare-contract":ve();return;case"review-findings":Be("conversion-integrity-findings","conversion-integrity-findings");return;case"review-runtime-verification":Be("conversion-integrity-runtime-guidance","conversion-integrity-runtime-title");return;case"retry-connection-status":Ue();return;case"select-contract":Be("conversion-integrity-contract-select","conversion-integrity-contract-select");return;case"retry-integrity":de.refetch();return;case"waiting-for-integrity":return}}const St=xe.data?.customers??[],mt=ne.data?.accounts??[],Xt=Q.data?.containers??[],Qt=re.data?.workspaces??[],ss=!!S&&!St.some($=>$.customerId===S),at=!!y&&!mt.some($=>$.id===y),fs=!!N&&!Xt.some($=>$.id===N),gt=!!L&&!Qt.some($=>$.id===L),dt=ss&&xe.isSuccess&&xe.data.truncated===!1,Ct=at&&ne.isSuccess&&ne.data.truncated===!1,ns=fs&&Q.isSuccess&&Q.data.truncated===!1,hs=gt&&re.isSuccess&&re.data.truncated===!1,qt=Ct||ns||hs,Ps=Ct?"The saved Tag Manager account is no longer accessible. Choose an available account before saving.":ns?"The saved Tag Manager container is no longer accessible. Choose an available container before saving.":hs?"The saved draft workspace is no longer accessible. Choose an available workspace or No draft workspace before saving.":null,zt=Pa(dt,xe.data,xe.isError),kt=Pa(Ct,ne.data,ne.isError),xs=Pa(ns,Q.data,Q.isError),ht=Pa(hs,re.data,re.isError),Zt=xe.isError?ft(xe.error):null,ys=ne.isError?ft(ne.error):Q.isError?ft(Q.error):re.isError?ft(re.error):null,ps=u==="google-ads"?Zt:u==="gtm"?ys:null,K=Aa("customer",xe.data,St.length),ce=Aa("account",ne.data,mt.length),Ne=Aa("container",Q.data,Xt.length),me=Aa("draft workspace",re.data,Qt.length),je=ne.isError||Q.isError||re.isError&&!!L,Ie=c||u!==null||H;function as(){xe.refetch()}function ot(){if(ne.isError){ne.refetch();return}if(Q.isError){Q.refetch();return}re.isError&&re.refetch()}return se.isLoading||V.isLoading||B.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($=>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"})]},$))}),e.jsx("p",{role:"status",className:"sr-only",children:"Loading conversion setup…"})]}):B.isError&&!B.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: ",ft(B.error)]}),e.jsx(P,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{B.refetch()},children:"Retry contracts"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Gg,{workspace:U,onPrimaryAction:yt,actionPending:_e,actionError:Ie?null:a,contracts:ee,selectedContractId:ge?.id??null,onSelectContract:$=>ae($||null),contractError:B.isError?ft(B.error):null,onRetryContracts:()=>{B.refetch()},onRetryEvidence:()=>{Promise.all([oe.refetch(),T.refetch()])},onChangeGoogleAdsSelection:k,onChangeGtmSelection:Ae,onAddContract:()=>yt("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:Ye(async $=>{$.preventDefault(),await vt()}),children:[e.jsxs("label",{htmlFor:"google-ads-developer-token",className:ls,children:["Developer token",e.jsx("input",{id:"google-ads-developer-token",type:"password",autoComplete:"off",value:h,onChange:$=>m($.target.value),className:Dt,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(Je,{type:"submit",disabled:Ee.isPending,children:Ee.isPending?"Starting…":"Continue to Google"}),e.jsx(P,{type:"button",variant:"outline",onClick:tt,children:"Cancel"})]})]})]}):null,u==="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"})]})}),ps?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:ps}),e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:as,children:"Retry customer list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,dt?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(Ra,{id:"google-ads-customer",label:"Customer account",value:S,onChange:$=>{x(!0),j($);const pe=St.find(it=>it.customerId===$);A(pe?.parentCustomerId??"")},disabled:xe.isLoading,children:[e.jsx("option",{value:"",children:xe.isLoading?"Loading accessible customers…":"Select a customer"}),ss?e.jsxs("option",{value:S,disabled:dt,children:["Saved customer ",S," (",zt,")"]}):null,St.map($=>e.jsx("option",{value:$.customerId,children:$.descriptiveName??`Customer ${$.customerId}`},$.customerId))]}),e.jsxs("label",{htmlFor:"google-ads-login-customer",className:ls,children:["Manager account ID (optional)",e.jsx("input",{id:"google-ads-login-customer",className:Dt,value:D,onChange:$=>{x(!0),A($.target.value)},placeholder:"Use only when a manager context is required"})]})]}),K?e.jsx("p",{role:"status",className:`mt-3 text-sm ${xe.data?.truncated?"text-caution":"text-secondary"}`,children:K}):null,e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Je,{type:"button",disabled:Se.isPending||xe.isLoading||xe.isError||dt||!S,onClick:Ye(Lt),children:Se.isPending?"Saving…":"Save customer selection"}),e.jsx(P,{type:"button",variant:"outline",onClick:$t,children:"Cancel"})]}),se.data?.connected?e.jsx(Ro,{providerLabel:"Google Ads",disabled:_e,onDisconnect:te}):null]}):null,u==="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"})]})}),ps?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:ps}),e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:ot,children:ne.isError?"Retry account list":Q.isError?"Retry container list":"Retry workspace list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,Ps?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:Ps}):null,e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-3",children:[e.jsxs(Ra,{id:"gtm-account",label:"Account",value:y,onChange:$=>{f(!0),$!==y&&(M(""),F("")),w($)},disabled:ne.isLoading,children:[e.jsx("option",{value:"",children:ne.isLoading?"Loading accounts…":"Select an account"}),at?e.jsxs("option",{value:y,disabled:Ct,children:["Saved account ",y," (",kt,")"]}):null,mt.map($=>e.jsx("option",{value:$.id,children:$.name},$.id))]}),e.jsxs(Ra,{id:"gtm-container",label:"Container",value:N,onChange:$=>{f(!0),$!==N&&F(""),M($)},disabled:!y||Q.isLoading,children:[e.jsx("option",{value:"",children:Q.isLoading?"Loading containers…":"Select a container"}),fs?e.jsxs("option",{value:N,disabled:ns,children:["Saved container ",N," (",xs,")"]}):null,Xt.map($=>e.jsx("option",{value:$.id,children:$.name},$.id))]}),e.jsxs(Ra,{id:"gtm-workspace",label:"Draft workspace (optional)",value:L,onChange:$=>{f(!0),F($)},disabled:!N||re.isLoading,children:[e.jsx("option",{value:"",children:re.isLoading?"Loading workspaces…":"No draft workspace"}),gt?e.jsxs("option",{value:L,disabled:hs,children:["Saved draft workspace ",L," (",ht,")"]}):null,Qt.map($=>e.jsx("option",{value:$.id,children:$.name},$.id))]})]}),e.jsxs("div",{className:"mt-3 grid max-w-3xl gap-2 text-sm sm:grid-cols-3",children:[ce?e.jsx("p",{role:"status",className:ne.data?.truncated?"text-caution":"text-secondary",children:ce}):null,Ne?e.jsx("p",{role:"status",className:Q.data?.truncated?"text-caution":"text-secondary",children:Ne}):null,me?e.jsx("p",{role:"status",className:re.data?.truncated?"text-caution":"text-secondary",children:me}):null]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Je,{type:"button",disabled:et.isPending||ne.isLoading||Q.isLoading||re.isLoading&&!!L||je||qt||!y||!N,onClick:Ye(Xe),children:et.isPending?"Saving…":"Save container selection"}),e.jsx(P,{type:"button",variant:"outline",onClick:$t,children:"Cancel"})]}),V.data?.connected?e.jsx(Ro,{providerLabel:"Tag Manager",disabled:_e,onDisconnect:qe}):null]}):null,H?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:Ye(async $=>{$.preventDefault(),await Jt()}),children:[e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-2",children:[e.jsxs("label",{htmlFor:"contract-name",className:ls,children:["Conversion name",e.jsx("input",{id:"contract-name",required:!0,maxLength:120,className:Dt,value:J.name,onChange:$=>G(pe=>({...pe,name:$.target.value})),placeholder:"Booking completed"})]}),e.jsxs("label",{htmlFor:"contract-event-name",className:ls,children:["Website event",e.jsx("input",{id:"contract-event-name",required:!0,className:Dt,value:J.eventName,onChange:$=>G(pe=>({...pe,eventName:$.target.value})),placeholder:"booking_complete"})]}),e.jsx(Io,{id:"contract-conversion-action",label:"Google Ads conversion action",options:R?.googleAds.conversionActions??[],synced:R?.googleAds.syncedAt!=null,loading:E.isLoading,failed:E.isError,onRetry:()=>{E.refetch()},emptyHint:"Run a Google Ads sync to list conversion actions.",value:J.conversionActionId,onChange:$=>G(pe=>({...pe,conversionActionId:$}))}),e.jsx(Io,{id:"contract-gtm-tag",label:"Tag Manager tag",options:R?.gtm.tags??[],synced:R?.gtm.syncedAt!=null,loading:E.isLoading,failed:E.isError,onRetry:()=>{E.refetch()},emptyHint:"Run a Tag Manager sync to list tags.",value:J.tagId,onChange:$=>G(pe=>({...pe,tagId:$}))})]}),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:ls,children:["Google conversion ID (optional)",e.jsx("input",{id:"contract-conversion-id",className:Dt,value:J.conversionId,onChange:$=>G(pe=>({...pe,conversionId:$.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-conversion-label",className:ls,children:["Google conversion label (optional)",e.jsx("input",{id:"contract-conversion-label",className:Dt,value:J.conversionLabel,onChange:$=>G(pe=>({...pe,conversionLabel:$.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-trigger-ids",className:ls,children:["Trigger IDs",e.jsx("input",{id:"contract-trigger-ids",className:Dt,value:J.triggerIds,onChange:$=>G(pe=>({...pe,triggerIds:$.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-variable-ids",className:ls,children:["Variable IDs",e.jsx("input",{id:"contract-variable-ids",className:Dt,value:J.variableIds,onChange:$=>G(pe=>({...pe,variableIds:$.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-campaign-ids",className:ls,children:["Campaign IDs",e.jsx("input",{id:"contract-campaign-ids",className:Dt,value:J.campaignIds,onChange:$=>G(pe=>({...pe,campaignIds:$.target.value})),placeholder:"Optional campaign-specific goal checks"})]}),e.jsxs("label",{htmlFor:"contract-production-hosts",className:ls,children:["Production hosts",e.jsx("input",{id:"contract-production-hosts",className:Dt,value:J.productionHosts,onChange:$=>G(pe=>({...pe,productionHosts:$.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(kn,{id:"contract-primary-action",checked:J.requirePrimaryAction,onChange:$=>G(pe=>({...pe,requirePrimaryAction:$})),children:"Google Ads action is primary"}),e.jsx(kn,{id:"contract-biddable-goal",checked:J.requireBiddableGoal,onChange:$=>G(pe=>({...pe,requireBiddableGoal:$})),children:"Google Ads goal is biddable"}),e.jsx(kn,{id:"contract-runtime-verification",checked:J.verificationRequired,onChange:$=>G(pe=>({...pe,verificationRequired:$})),children:"Runtime proof is required"}),e.jsx(kn,{id:"contract-transaction-id",checked:J.requireTransactionId,onChange:$=>G(pe=>({...pe,requireTransactionId:$})),children:"Transaction ID is required"}),e.jsx(kn,{id:"contract-value",checked:J.requireValue,onChange:$=>G(pe=>({...pe,requireValue:$})),children:"Conversion value is required"}),e.jsx(kn,{id:"contract-currency",checked:J.requireCurrency,onChange:$=>G(pe=>({...pe,requireCurrency:$})),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(Je,{type:"submit",disabled:_.isPending,children:_.isPending?"Saving…":"Save conversion contract"}),e.jsx(P,{type:"button",variant:"outline",onClick:Mt,children:"Cancel"})]})]})]}):null]})}const zg=6e4,Wg=["7d","14d","30d"],xi="not available",Hg='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%.',Yg="No Google Ads snapshot stored yet",Jg="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.",Xg="No closed days yet",Zg="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.",ef={"insufficient-history":"Period change is hidden: the stored snapshot does not cover a prior period of equal length yet."},Gs=new Intl.NumberFormat(void 0,{maximumFractionDigits:0}),kr=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}),ec=new Intl.NumberFormat(void 0,{maximumFractionDigits:1}),tf=new Intl.NumberFormat(void 0,{minimumFractionDigits:2,maximumFractionDigits:2});function An(t,s){return t===null||!Number.isFinite(t)?xi:s===null?tf.format(t/1e6):fh(t,s)}function Ar(t){if(t===null||!Number.isFinite(t))return xi;const s=t*100;return s>0&&s<.1?"<0.1%":`${ec.format(s)}%`}function sf(t,s){if(t===null||!Number.isFinite(t))return`${xi} 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%":`${ec.format(n)}%`;return`${t>0?"↑":"↓"} ${a} vs prior ${s}d`}function nf(t){return t==="enabled"?"positive":t==="paused"?"caution":"neutral"}function af(t){return t==="enabled"?"Enabled":t==="paused"?"Paused":t==="removed"?"Removed":"Unknown"}function rf(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 of({projectName:t}){const[s,n]=l.useState("14d"),[a,r]=l.useState(()=>new Set(["costMicros","conversions"])),o=Te({...Xd({client:Y,path:{name:t},query:{window:s}}),staleTime:zg}),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(Ve,{text:Hg})]}),i?.source?e.jsxs("p",{className:"text-xs text-muted",children:[Vt(i.startDate)," to ",Vt(i.endDate)," · ",i.days," closed ",i.days===1?"day":"days"]}):null]}),e.jsx(Ha,{windows:Wg,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(y=>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"})]},y))}),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: ",ft(o.error)]}),e.jsx(P,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{o.refetch()},children:"Retry performance"})]});const{totals:d,daily:h,campaigns:m,comparison:u,comparisonUnavailableReason:b,source:p}=i;if(!p){const y=b==="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:y?Xg:Yg}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-secondary",children:y?Zg:Jg})]})]})}const x=p.currencyCode,g=p.campaignsInInventory>0&&p.campaignsQueried<p.campaignsInInventory?{queried:p.campaignsQueried,inInventory:p.campaignsInInventory}:null,f=d.costMicros>0&&d.conversions===0,S=[{key:"spend",comparable:!0,label:"Spend",value:An(d.costMicros,x),change:u?.change.costMicros??null,direction:"none",seriesKey:"costMicros"},{key:"conversions",comparable:!0,label:"Conversions",value:kr.format(d.conversions),change:u?.change.conversions??null,direction:"up-good",seriesKey:"conversions"},{key:"cost-per-conversion",label:"Cost / conv.",value:f?"no conversions":An(d.costPerConversionMicros,x),change:null,comparable:!1,direction:"down-good",seriesKey:null},{key:"conversion-rate",comparable:!0,label:"Conv. rate",value:Ar(d.conversionRate),change:u?.change.conversionRate??null,direction:"up-good",seriesKey:null}],j=[{key:"clicks",label:"Clicks",value:Gs.format(d.clicks),seriesKey:"clicks"},{key:"impressions",label:"Impressions",value:Gs.format(d.impressions),seriesKey:"impressions"},{key:"ctr",label:"CTR",value:Ar(d.ctr),seriesKey:null},{key:"cpc",label:"CPC",value:An(d.cpcMicros,x),seriesKey:null}],D={costMicros:{label:"Spend",color:rt[1],axisId:"spend",formatValue:y=>An(y,x)},conversions:{label:"Conversions",color:rt[0],axisId:"conversions",formatValue:y=>kr.format(y)},clicks:{label:"Clicks",color:rt[2],axisId:"clicks",formatValue:y=>Gs.format(y)},impressions:{label:"Impressions",color:rt[3],axisId:"impressions",formatValue:y=>Gs.format(y)}},A=[...a].map(y=>({dataKey:y,...D[y]}));return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[c,g!==null?e.jsxs("p",{role:"status",className:"mt-3 text-sm text-caution",children:["Totals cover ",Gs.format(g.queried)," of"," ",Gs.format(g.inInventory)," campaigns, so they are a subset of the account."]}):null,p.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,!u&&b==="insufficient-history"?e.jsx("p",{className:"mt-3 text-sm text-secondary",children:ef["insufficient-history"]}):null,e.jsx("div",{className:"mt-4 grid grid-cols-2 gap-2 lg:grid-cols-4",children:S.map(y=>{const w=y.seriesKey!==null&&a.has(y.seriesKey),N=w&&a.size===1,M=e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[y.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:w?D[y.seriesKey].color:"var(--color-mono-600)"}}):null,y.label]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:y.value}),u&&y.comparable?e.jsx("span",{className:`block text-[11px] tabular-nums ${rf(y.change,y.direction)}`,children:sf(y.change,u.days)}):e.jsx("span",{className:"block text-[11px] text-muted",children:y.comparable?`no prior ${s} period stored`:" "})]});return y.seriesKey===null?e.jsx("div",{className:"rounded-md border border-subtle bg-surface-subtle px-3 py-2",children:M},y.key):e.jsx("button",{type:"button","aria-pressed":w,disabled:N,onClick:()=>r(L=>{const F=new Set(L);return F.has(y.seriesKey)?F.delete(y.seriesKey):F.add(y.seriesKey),F.size===0?L:F}),className:`rounded-md border px-3 py-2 text-left transition-colors ${w?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${N?"cursor-default":""}`,children:M},y.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:j.map(y=>{const w=y.seriesKey!==null&&a.has(y.seriesKey),N=w&&a.size===1,M=e.jsxs(e.Fragment,{children:[e.jsxs("dt",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[y.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:w?D[y.seriesKey].color:"var(--color-mono-600)"}}):null,y.label]}),e.jsx("dd",{className:"text-sm tabular-nums text-strong",children:y.value})]});return y.seriesKey===null?e.jsx("div",{className:"flex items-baseline gap-1.5",children:M},y.key):e.jsx("button",{type:"button","aria-pressed":w,disabled:N,onClick:()=>r(L=>{const F=new Set(L);return F.has(y.seriesKey)?F.delete(y.seriesKey):F.add(y.seriesKey),F.size===0?L:F}),className:`flex items-baseline gap-1.5 rounded px-1 -mx-1 ${N?"cursor-default":"hover:bg-surface-hover"}`,children:M},y.key)})}),e.jsxs("div",{className:"mt-4",children:[e.jsx(wl,{data:h,xKey:"date",series:A,xTickFormatter:yn,labelFormatter:Vt}),e.jsx("ul",{className:"sr-only",children:h.map(y=>e.jsxs("li",{children:[Vt(y.date),":"," ",A.map(w=>`${w.label} ${D[w.dataKey].formatValue(y[w.dataKey])}`).join(", "),y.origin==="filled"?", no delivery reported":""]},y.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(y=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs truncate text-strong",title:y.name??y.campaignId,children:y.name??e.jsx("span",{className:"font-mono text-secondary",children:y.campaignId})}),e.jsx("td",{children:e.jsx(ue,{tone:nf(y.status),children:af(y.status)})}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Gs.format(y.totals.impressions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Gs.format(y.totals.clicks)}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:An(y.totals.costMicros,x)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:kr.format(y.totals.conversions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Ar(y.totals.ctr)}),e.jsx("td",{className:"text-right tabular-nums",children:y.totals.costMicros>0&&y.totals.conversions===0?e.jsx(ue,{tone:"caution",children:"no conversions"}):e.jsx("span",{className:"text-secondary",children:An(y.totals.costPerConversionMicros,x)})})]},y.campaignId))})]})}),e.jsxs("p",{className:"mt-3 text-[11px] text-muted",children:["Snapshot ",Ws(Es(p.capturedAt))," · ","customer ",p.customerId," · ","latest closed day ",Vt(p.asOfDate),p.openDate?e.jsxs(e.Fragment,{children:[" · ",Vt(p.openDate)," still open, excluded"]}):null,p.timeZone?e.jsxs(e.Fragment,{children:[" · ","days close in ",p.timeZone]}):null]})]})]})}const Pr=20,$s=50,lf=50,cf=50;function pi(t){return t==="viewer"}function gi(t){return t?.status==="unavailable"}function tc(t,s,n){return n?t.includes(s)?[...t]:[...t,s]:t.filter(a=>a!==s)}function sc(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 Ia(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 df(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 Rr(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 To(t){return t==="matched"?"positive":t==="duplicate"?"neutral":t==="ambiguous"||t==="proposed"||t==="excluded"?"caution":"negative"}function $o(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 Ta(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 ei(t){return t.state==="missing"||t.source==="unavailable-tracked-query"||!t.source}function Ir(t){return ei(t)?"Unavailable tracked query":t.text?.trim()||"Unavailable tracked query"}function ti({properties:t,selectedPropertyIds:s,onSelectedPropertyIdsChange:n,legend:a,showBulkActions:r=!0}){const[o,i]=l.useState(""),[c,d]=l.useState(!1),h=o.trim().toLocaleLowerCase(),m=h?t.filter(x=>x.label.toLocaleLowerCase().includes(h)):t,u=c?m:m.slice(0,lf),b=u.length<m.length;function p(){const x=new Set([...s,...u.map(g=>g.id)]);n(t.filter(g=>x.has(g.id)).map(g=>g.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:x=>i(x.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(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:u.length===0,onClick:p,children:"Select all shown"}),e.jsx(P,{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 ",u.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:u.map(x=>{const g=s.includes(x.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 ${x.label}`,checked:g,type:"checkbox",onChange:f=>n(tc(s,x.id,f.currentTarget.checked))}),e.jsx("span",{children:x.label})]}),x.urlCount===void 0?null:e.jsxs("span",{className:"tabular-nums text-secondary",children:[x.urlCount," URLs"]})]},x.id)})}),b?e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",onClick:()=>d(!0),children:"Show all Properties"}):null]})]})}function fi(){return e.jsxs("div",{className:"flex items-center gap-2 text-sm text-secondary",children:[e.jsx(ue,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]})}function yi({message:t}){return e.jsxs("div",{role:"status",className:"border-y border-caution-800/40 bg-caution-950/20 py-4 text-sm text-caution",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ue,{tone:"caution",children:"Unavailable"}),e.jsx("h4",{className:"font-medium",children:"Measurement setup unavailable"})]}),e.jsx("p",{className:"mt-2 max-w-2xl text-secondary",children:t})]})}function uf({value:t}){const[s,n]=l.useState(0),[a,r]=l.useState(0),[o,i]=l.useState(null),c=t.preview,d=c?.counts.needsAttention??0,h=c?.rows.filter(N=>N.status==="matched")??[],m=c?.rows??[],u=m.filter(N=>N.status!=="matched"),b=Math.max(1,Math.ceil(m.length/$s)),p=Math.min(s,b-1),x=m.slice(p*$s,(p+1)*$s),g=Math.max(1,Math.ceil(u.length/$s)),f=Math.min(a,g-1),S=u.slice(f*$s,(f+1)*$s),j=t.csv.trim().length>0&&!t.isReviewing&&!t.isApplying,D=h.length>0&&!t.isApplying,A=c!==null&&o===c.previewChecksum,y=u.length>0&&f===g-1;l.useEffect(()=>{n(0),r(0),i(null)},[c?.previewChecksum]);async function w(N){if(N)try{t.onCsvChange(await N.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:N=>{w(N.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:N=>t.onCsvChange(N.currentTarget.value),placeholder:`property,group,url
3
3
  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(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!j,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",d>0?` · ${d} need${d===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(N=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:N.label}),e.jsx("td",{className:"text-secondary",children:N.action==="create"?"Create group":"Add to existing group"}),e.jsx("td",{className:"tabular-nums text-secondary",children:N.targetKeys.length}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[N.addedTargetKeys.length,N.unchangedTargetKeys.length>0?` · ${N.unchangedTargetKeys.length} already members`:""]})]},N.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:x.map(N=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:N.dataRow}),e.jsx("td",{className:"text-heading",children:N.property}),e.jsx("td",{className:"text-secondary",children:N.group}),e.jsxs("td",{children:[e.jsx(ue,{tone:To(N.status),children:$o(N.status)}),Ta(N)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:Ta(N)}):null]})]},N.dataRow))})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Page ",p+1," of ",b," · ",c.rows.length," rows"]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:p===0,onClick:()=>n(N=>Math.max(0,N-1)),children:"Previous 50 rows"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:p===b-1,onClick:()=>n(N=>Math.min(b-1,N+1)),children:"Next 50 rows"})]})]}):null,d>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 ",d," row",d===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:S.map(N=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:N.dataRow}),e.jsx("td",{className:"text-heading",children:N.property}),e.jsx("td",{className:"text-secondary",children:N.group}),e.jsxs("td",{children:[e.jsx(ue,{tone:To(N.status),children:$o(N.status)}),Ta(N)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:Ta(N)}):null]})]},N.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 ",f+1," of ",g]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:f===0,onClick:()=>r(N=>Math.max(0,N-1)),children:"Previous 50 exceptions"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:f===g-1,onClick:()=>r(N=>Math.min(g-1,N+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:A,disabled:t.isApplying||!y,onChange:N=>i(N.currentTarget.checked?c.previewChecksum:null),className:"size-4 rounded border-default"}),"I reviewed the exceptions and understand that ",d," row",d===1?"":"s"," will be skipped."]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",disabled:!D||!A,onClick:()=>{t.onApply(h.map(N=>N.dataRow))},children:t.isApplying?"Applying groups…":`Apply ${h.length} matched row${h.length===1?"":"s"}`})]}):e.jsx(P,{type:"button",className:"mt-3 min-h-11",disabled:!D,onClick:()=>{t.onApply(h.map(N=>N.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 mf="—";function hf({access:t,availability:s,properties:n,queries:a,selectedQueryIds:r,isApplying:o=!1,isBusy:i=!1,canContinue:c=!0,onSelectedQueryIdsChange:d,onApplySelectedQueries:h,onClearQueryAssignments:m,onRemoveQuery:u,onCreateQueries:b,onCreateAndPairQuestions:p,isCreatingQueries:x=!1,createQueriesError:g=null,onManageProjectQueries:f,groups:S,audience:j,onAudienceChange:D,assignmentImpact:A=null,isPreviewingAssignmentImpact:y=!1,assignmentImpactError:w=null,onRetryAssignmentImpact:N,assignmentNotice:M=null,onReplaceAssignments:L,isReplacingAssignments:F=!1,onBack:H,onContinue:O}){const[J,G]=l.useState(""),[C,ae]=l.useState(!1),[q,se]=l.useState(!1),[V,B]=l.useState(""),[E,R]=l.useState(""),[oe,T]=l.useState(null);if(gi(s))return e.jsx("section",{"aria-label":"Queries",children:e.jsx(yi,{message:s.message})});const ee=pi(t),Z=j,ge=D,X=Ia(Z,n,S),de=X.length,xe=de>0&&r.length>0&&!o&&!i&&!y&&A!==null&&w===null,ne=m??u,Q=J.trim().toLocaleLowerCase(),re=Q?a.filter(W=>Ir(W).toLocaleLowerCase().includes(Q)):a,Ee=re.filter(W=>(W.propertyIds?.length??0)===0),we=q?Ee:re,Se=C?we:we.slice(0,cf),et=Se.filter(W=>!ei(W)),Ke=[...new Set(V.split(`
4
4
  `).map(W=>W.trim()).filter(Boolean))],Qe=[...E.matchAll(/\{([a-z][\w-]*)\}/gi)].map(W=>W[1]),We=n.filter(W=>X.includes(W.id)),Ge=Qe.length===0||E.trim()===""?[]:We.map(W=>({propertyId:W.id,text:Qe.reduce((Re,_e)=>Re.replaceAll(`{${_e}}`,W.label),E.trim())})),_=[...new Set(Ge.map(W=>W.text))];function U(){const W=new Set([...r,...et.map(Re=>Re.id)]);d(a.filter(Re=>W.has(Re.id)).map(Re=>Re.id))}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-queries-title",className:"space-y-5",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{id:"advanced-measurement-queries-title",children:"Queries"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Choose queries, then apply them to Properties."})]})}),ee?e.jsx(fi,{}):null,ee?null:e.jsxs("fieldset",{className:"border-y border-default py-4",children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:"Apply to"}),e.jsx("div",{className:"mt-3 max-w-xl",children:e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"sr-only",children:"Apply to"}),e.jsxs("select",{"aria-label":"Apply to",value:Z.kind==="all"?"all":Z.kind==="specific"?"specific":`group:${Z.groupIds[0]??""}`,onChange:W=>{const Re=W.currentTarget.value;Re==="all"?ge({kind:"all"}):Re==="specific"?ge({kind:"specific",propertyIds:[]}):Re.startsWith("group:")&&ge({kind:"groups",groupIds:[Re.slice(6)]})},className:"block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-400",children:[e.jsxs("option",{value:"all",children:["All Properties · ",n.length]}),S.length>0?e.jsx("optgroup",{label:"Groups",children:S.map(W=>{const Re=Ia({kind:"groups",groupIds:[W.id]},n,S).length;return e.jsx("option",{value:`group:${W.id}`,disabled:Re===0,children:Rr(W,n)},W.id)})}):null,e.jsx("option",{value:"specific",children:"Specific Properties…"})]})]})}),Z.kind==="groups"?e.jsxs("div",{className:"mt-3 max-w-2xl space-y-3",children:[e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:Z.groupIds.map(W=>{const Re=S.find(_e=>_e.id===W);return Re?e.jsxs("span",{className:"inline-flex min-h-11 items-center gap-1 rounded-md border border-default bg-surface px-2 text-sm text-primary",children:[Rr(Re,n),e.jsx("button",{type:"button","aria-label":`Remove ${Re.name}`,className:"-my-px -mr-2 ml-1 inline-flex min-h-11 min-w-11 items-center justify-center rounded text-secondary outline-none hover:text-heading focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>{const _e=Z.groupIds.filter(Ue=>Ue!==Re.id);ge(_e.length>0?{kind:"groups",groupIds:_e}:{kind:"all"})},children:"×"})]},Re.id):null})}),S.some(W=>!Z.groupIds.includes(W.id)&&Ia({kind:"groups",groupIds:[W.id]},n,S).length>0)?e.jsxs("label",{className:"block max-w-sm",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Add another group"}),e.jsxs("select",{"aria-label":"Add another group",value:"",onChange:W=>{W.currentTarget.value&&ge({kind:"groups",groupIds:[...Z.groupIds,W.currentTarget.value]})},className:"mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-400",children:[e.jsx("option",{value:"",children:"Choose a group"}),S.filter(W=>!Z.groupIds.includes(W.id)).map(W=>{const Re=Ia({kind:"groups",groupIds:[W.id]},n,S).length;return e.jsx("option",{value:W.id,disabled:Re===0,children:Rr(W,n)},W.id)})]})]}):null,de===0?e.jsx("p",{role:"alert",className:"text-sm text-caution",children:"This group has no included Properties. Add Properties to the group, then try again."}):null]}):null,Z.kind==="specific"?e.jsx("div",{className:"mt-4",children:e.jsx(ti,{legend:"Specific Properties",properties:n,selectedPropertyIds:Z.propertyIds,showBulkActions:!1,onSelectedPropertyIdsChange:W=>{ge({kind:"specific",propertyIds:W})}})}):null,e.jsx("p",{className:"mt-3 max-w-2xl text-sm text-secondary",children:"Groups are shortcuts resolved when you assign. Changing membership later does not rewrite existing assignments, and a Property added later does not receive earlier group queries."})]}),ee||!b?null:e.jsxs("details",{open:a.length===0,className:"border-y border-default py-4",children:[e.jsx("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:"Add queries"}),e.jsxs("div",{className:"pt-3",children:[e.jsx("h4",{className:"m-0 text-sm font-medium text-heading",children:a.length===0?"Add the queries you want to track":"Add more queries"}),e.jsx("p",{className:"mt-1 mb-2 text-sm text-secondary",children:"One per line. Add them to the project, then apply them to Properties."}),e.jsx("textarea",{"aria-label":"New queries, one per line",className:"w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",rows:4,value:V,onChange:W=>B(W.currentTarget.value),placeholder:`best apartments in dallas