@ainyc/canonry 4.188.1 → 4.188.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.
- package/assets/assets/{AuditHistoryPanel-BCpFULQp.js → AuditHistoryPanel-BB7rr4vG.js} +1 -1
- package/assets/assets/{BacklinksPage-CFHiZFhZ.js → BacklinksPage-8dDuc28f.js} +1 -1
- package/assets/assets/{HistoryPage-THnDCEnv.js → HistoryPage-CCvbnLuu.js} +1 -1
- package/assets/assets/{MeasurementPropertyPage-DWWwA2kL.js → MeasurementPropertyPage-BrrQ6PvC.js} +1 -1
- package/assets/assets/ProjectPage-DNT9kgFA.js +9 -0
- package/assets/assets/{RunRow-CDWArf9X.js → RunRow-CmgxzVdi.js} +1 -1
- package/assets/assets/{RunsPage-Ctsw14Vg.js → RunsPage-C45l2Esz.js} +1 -1
- package/assets/assets/{SettingsPage-IHYGgD0e.js → SettingsPage-CpYnUN8n.js} +1 -1
- package/assets/assets/{SiteHealthSection-DjFHZqBF.js → SiteHealthSection-D0WRI8jf.js} +3 -3
- package/assets/assets/{TrafficPage-Cb1Zwgc5.js → TrafficPage-D632bq2a.js} +1 -1
- package/assets/assets/{TrafficSourceDetailPage-CRdjdiAa.js → TrafficSourceDetailPage-DPBUcLs4.js} +1 -1
- package/assets/assets/{extract-error-message-CNs6e1oz.js → extract-error-message-DFIwOwb8.js} +1 -1
- package/assets/assets/{index-DTblya6d.css → index-DLB5x_Yh.css} +1 -1
- package/assets/assets/{index-B64f9mVI.js → index-D_ut_IJW.js} +28 -28
- package/assets/assets/{react-sigma_core.esm.min-CzJ-HG1j.js → react-sigma_core.esm.min-BtdnOf_z.js} +1 -1
- package/assets/assets/{vendor-lucide-BovNTc41.js → vendor-lucide-dNHw1I5G.js} +1 -1
- package/assets/index.html +3 -3
- package/dist/{chunk-A47HAZDJ.js → chunk-5NAOIDJM.js} +2 -2
- package/dist/{chunk-HIIOVQSH.js → chunk-EBLUZCIX.js} +46 -1
- package/dist/{chunk-QPYMAXLJ.js → chunk-FUCEQ5C5.js} +1 -1
- package/dist/{chunk-6YJQGOR6.js → chunk-H25PK25P.js} +4 -4
- package/dist/{chunk-GPTEXYYL.js → chunk-HBXA2APL.js} +29 -11
- package/dist/cli.js +5 -5
- package/dist/index.js +4 -4
- package/dist/{intelligence-service-4KMWHEYP.js → intelligence-service-SLL5HWV6.js} +2 -2
- package/dist/mcp.js +3 -3
- package/package.json +9 -9
- package/assets/assets/ProjectPage-CP57_Lqf.js +0 -9
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import{j as e,r as l,u as we,L as js,h as Ns,o as Pt,B as Ir,C as Dl,k as Ol,l as Fl,D as Gl}from"./vendor-tanstack-CYBjbqVr.js";import{T as le,t as Kl,a as _l,M as No,I as Me,s as wo,B as A,b as Ul,u as So,C as Bl,P as Cn,h as Vl,c as zl,d as dn,g as Co,e as ko,f as xe,i as W,j as te,k as Nt,l as Ee,m as Ql,n as Hl,o as Wl,p as Ao,q as Yl,r as Jl,S as un,v as Xl,w as Zl,x as Os,y as Bt,z as ec,A as ti,D as Po,G as Dt,E as $r,F as tc,H as sc,J as nc,K as ac,L as si,N as Se,O as rc,Q as ic,R as qa,U as oc,V as lc,W as cc,X as dc,Y as uc,Z as mc,_ as hc,$ as xc,a0 as pc,a1 as gc,a2 as fc,a3 as yc,a4 as bc,a5 as vc,a6 as jc,a7 as Ro,a8 as Qs,a9 as Nc,aa as Io,ab as ba,ac as wc,ad as De,ae as Sc,af as Cc,ag as kc,ah as va,ai as Ac,aj as Pc,ak as Rc,al as hn,am as Ic,an as $c,ao as Tc,ap as $o,aq as hr,ar as Mc,as as To,at as Lc,au as _n,av as Hs,aw as Vt,ax as ni,ay as qc,az as Ec,aA as Hn,aB as Dc,aC as Oc,aD as Fc,aE as Gc,aF as Kc,aG as Gn,aH as mn,aI as _c,aJ as Mo,aK as Uc,aL as Bc,aM as Vc,aN as ai,aO as zc,aP as Qc,aQ as Hc,aR as Wc,aS as Yc,aT as Jc,aU as Xc,aV as Zc,aW as ed,aX as td,aY as sd,aZ as nd,a_ as ad,a$ as rd,b0 as id,b1 as od,b2 as ld,b3 as cd,b4 as dd,b5 as ud,b6 as md,b7 as hd,b8 as xd,b9 as pd,ba as gd,bb as fd,bc as yd,bd,be as fs,bf as vd,bg as lt,bh as jd,bi as Nd,bj as wd,bk as Sd,bl as Cd,bm as kd,bn as Ad,bo as Pd,bp as Rd,bq as Id,br as $d,bs as Td,bt as Md,bu as Ld,bv as qd,bw as Ed,bx as Dd,by as Od,bz as Fd,bA as Gd,bB as Kd,bC as _d,bD as Ud,bE as Bd,bF as Vd,bG as zd,bH as Qd,bI as Hd,bJ as Wd,bK as Yd,bL as Jd,bM as Xd,bN as Zd,bO as eu,bP as tu,bQ as su,bR as nu,bS as au,bT as ru,bU as Lo,bV as Ea,bW as iu,bX as ri,bY as ou,bZ as lu,b_ as cu,b$ as du,c0 as uu,c1 as mu,c2 as hu,c3 as qo,c4 as xu,c5 as pu,c6 as gu,c7 as fu,c8 as yu,c9 as bu,ca as vu,cb as ju,cc as ii,cd as Nu,ce as wu,cf as Su,cg as Cu,ch as ku,ci as Au,cj as Pu,ck as Ru,cl as Iu,cm as $u,cn as Tu,co as Mu,cp as Lu,cq as qu,cr as Eu,cs as ja,ct as Du,cu as Da,cv as Ou,cw as Fu,cx as Gu,cy as Ku,cz as _u,cA as Uu,cB as Bu,cC as Vu,cD as zu,cE as Qu,cF as Eo,cG as Hu,cH as Wu,cI as Yu,cJ as Ju,cK as Xu,cL as Zu,cM as Zn,cN as em,cO as tm,cP as sm,cQ as oi,cR as nm}from"./index-B64f9mVI.js";import{C as Ws,e as Do,q as Na,U as am,r as rm,L as im,s as om,i as lm,P as Un,D as Oo,t as cm,u as Fo,d as dm,E as um,p as mm,v as hm,w as Go}from"./vendor-lucide-BovNTc41.js";import{R as xm}from"./RunRow-CDWArf9X.js";import{u as xn,D as Bs,a as Rs,b as Ko,M as xa,c as Cs,S as pm}from"./SiteHealthSection-DjFHZqBF.js";import{C as Bn,f as pn,a as is,b as Rt,c as Ot,d as Xt,e as nt,g as os,h as Is,M as _o,i as Uo,o as $s,j as Vs,p as gm}from"./ChartPrimitives-DLEICrrL.js";import{u as fm,a as ym,b as bm,t as vm,e as jm,c as mt}from"./extract-error-message-CNs6e1oz.js";import{R as Ys,C as Js,a as Vn,X as Xs,Y as Zs,T as en,b as xr,L as wa,A as Gs,d as Ps,e as Nm}from"./vendor-recharts-FA0uySU7.js";import{A as wm}from"./AuditHistoryPanel-BCpFULQp.js";import{a as Sm,b as Cm}from"./v2-overview-adapter-COMP5UGt.js";import"./vendor-radix-BpmvLvpp.js";import"./vendor-markdown-9tTeP8v7.js";import"./vendor-yaml-GWJz5H2G.js";function zs(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 km(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=Am(r,1));return a}function Am(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 Pm(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 Rm(t,s){const n=Pm(t,s);return n===null?null:Math.round(n*100)}function Oa(t,s,n="vs prior 7 days"){return t.deltaPct===null?t.prior===0?"First baseline week":"":t.deltaPct>0?`Up ${t.deltaPct}% ${n} (${zs(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${zs(t.prior)} ${s})`:`Flat ${n} (${zs(t.prior)} ${s})`}const Bo=30;function li(t){return Math.round(t*10)/10}function Im(t){return t.prior>=Bo&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% vs prior`:`${t.deltaAbs>0?"+":""}${li(t.deltaAbs)} vs ${li(t.prior)}`}function $m(t,s,n){return t.prior>=Bo&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% ${n}`:`${t.deltaAbs>0?"+":""}${zs(Math.round(t.deltaAbs))} ${s} ${n}`}const Tm=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function Vo(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function zo(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 Qo(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(Vo).map(zo).filter(Boolean)):new Set}function Ho(t,s){const n=Vo(t).map(zo).filter(Boolean).filter(a=>!Tm.has(a)).filter(a=>!s.has(a));return[...new Set(n)].sort().join(" ")}function Mm(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function Lm(t,s){const n=Qo(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=Ho(Mm(o),n);!i||a.has(i)||(a.add(i),r.push(o))}return r}function qm(t){const s=Qo(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const a=new Set;return n.filter(r=>{const o=Ho(r.query,s);return!o||a.has(o)?!1:(a.add(o),!0)})}const Em=1e6;function Dm(t,s="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:s}).format(t/Em)}const Tr={queryClass:"all"},Om=["all","non-brand","branded"];function Wo(t){return typeof t=="string"&&Om.includes(t)}function Yo(t){const s=Wo(t.class)?t.class:Tr.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 Fm(t,s){return s===null||t===null?!1:t!==s}function Gm(t){return{scope:t.scope==="group"&&t.groupKey?`group:${t.groupKey}`:void 0,class:t.queryClass===Tr.queryClass?void 0:t.queryClass}}function Km(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 _m(t){const s=u=>typeof t[u]=="string"&&t[u]!==""?t[u]:void 0,n=Yo({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"||Wo(o)?o:Tr.queryClass};i.measurementScope!=="project"&&(i.measurementScopeKey=r);for(const[u,m]of[["measurementProvider","provider"],["measurementModel","model"],["measurementLocation","location"],["measurementFrom","from"],["measurementTo","to"],["measurementRunId","measurementRunId"],["measurementQueryKey","queryKey"]]){const x=s(u);x!==void 0&&(i[m]=x)}const d=Number(t.measurementRevision);Number.isSafeInteger(d)&&d>0&&(i.revision=d);const c=Km(t.measurementAnswer,i.queryKey);return c&&(i.answer=c),i}function Um(t,s){const n={...t,...s};return["measurementScope","measurementScopeKey","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,n.measurementQueryKey=void 0,s.measurementScope==="project"&&(n.measurementScopeKey=void 0)),"queryClass"in s&&(n.class=void 0),n}function pr({state:t,label:s}){return e.jsx(le,{tone:_l(t),children:s??Kl(t)})}const sn=[{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],ci={"non-brand":"Non-brand",branded:"Branded",pooled:"All queries"},Bm={"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."},Vm="Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other.";function zm(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 Qm({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,d)=>d.mentions-i.mentions||(i.label<d.label?-1:1));return e.jsxs("table",{className:"mention-share-table",children:[e.jsx("caption",{className:"sr-only",children:"Brand mentions by domain, most mentioned first"}),e.jsx("thead",{children:e.jsxs("tr",{className:"mention-share-row mention-share-row-head",children:[e.jsx("th",{scope:"col",className:"mention-share-row-label",children:"Domain"}),e.jsx("th",{"aria-hidden":"true"}),e.jsxs("th",{scope:"col",className:"mention-share-count",children:["Mentions",e.jsx(Me,{text:Vm})]}),e.jsx("th",{scope:"col",className:"mention-share-share",children:"Share"})]})}),e.jsx("tbody",{className:"mention-share-rows",children:o.map(i=>{const d=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:`${d>0?Math.max(d,1.5):0}%`}})})}),e.jsx("td",{className:"mention-share-count",children:i.mentions}),e.jsxs("td",{className:"mention-share-share",children:[d.toFixed(1),"%"]})]},i.label)})})]})}function Hm({summary:t,projectLabel:s,competitorDomains:n}){const[a,r]=l.useState("non-brand"),o=l.useId(),i=t.scope==="pooled",d=!i&&t.branded.snapshotsTotal>0,c=d?a:"non-brand",u=i?"pooled":c,m=c==="branded"?t.branded:t.breakdown,x=c==="branded"?t.breakdown:t.branded,g=zm(m,{hasCompetitors:n.length>0,unavailable:t.unavailable===!0,noRun:t.breakdown.snapshotsTotal===0&&t.branded.snapshotsTotal===0,otherClassHasData:x.snapshotsTotal>0}),h=u==="non-brand"?No[t.tone]:"text-secondary";function p(y){const j=sn.findIndex(k=>k.value===c);let w=null;y.key==="ArrowRight"||y.key==="ArrowDown"?w=(j+1)%sn.length:y.key==="ArrowLeft"||y.key==="ArrowUp"?w=(j-1+sn.length)%sn.length:y.key==="Home"?w=0:y.key==="End"&&(w=sn.length-1),w!==null&&(y.preventDefault(),r(sn[w].value),y.currentTarget.querySelectorAll('[role="radio"]')[w]?.focus())}return e.jsxs("div",{className:"mention-share",children:[e.jsxs("div",{className:"mention-share-head",children:[e.jsxs("div",{className:"mention-share-label",children:[e.jsx("h3",{id:o,className:"mention-share-label-text",children:"Mention share"}),e.jsx(Me,{text:Bm[u]})]}),d?e.jsx("div",{role:"radiogroup","aria-labelledby":o,className:"segmented flex-wrap",onKeyDown:p,children:sn.map(y=>{const j=y.value===c;return e.jsx("button",{type:"button",role:"radio","aria-checked":j,tabIndex:j?0:-1,onClick:()=>r(y.value),className:`segmented-option min-h-11 ${j?"segmented-option-active":""}`,children:y.label},y.value)})}):e.jsx("span",{className:"mention-share-class",children:ci[u]})]}),g.numeric?e.jsxs("p",{className:`mention-share-value ${h}`,children:[g.headline,e.jsx("span",{className:"text-faint",children:"%"})]}):e.jsx("p",{className:"mention-share-value-text",children:g.headline}),e.jsxs("p",{className:"mention-share-caption",children:[e.jsx("span",{className:"mention-share-caption-scope",children:ci[u]}),` · ${g.detail}`]}),i&&e.jsx("p",{className:"mention-share-note",children:"Set a brand name to split branded from non-brand."}),g.showRows&&e.jsx(Qm,{breakdown:m,projectLabel:s,competitorDomains:n})]})}const nn=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],di=5;function Wm(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 Ym(t){return t?t.evidence.answeredResults>0||t.evidence.sourceResults>0?"measured":"not-measured":"unavailable"}function Fa(t){return t==="unavailable"?"Unavailable":"Not measured"}function Jo(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 Jm({value:t,onChange:s}){function n(a){const r=nn.findIndex(d=>d.value===t);let o=null;if(a.key==="ArrowRight"||a.key==="ArrowDown"?o=(r+1)%nn.length:a.key==="ArrowLeft"||a.key==="ArrowUp"?o=(r-1+nn.length)%nn.length:a.key==="Home"?o=0:a.key==="End"&&(o=nn.length-1),o===null)return;a.preventDefault();const i=nn[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:nn.map(a=>{const r=a.value===t;return e.jsx("button",{type:"button",role:"radio","aria-checked":r,tabIndex:r?0:-1,onClick:()=>s(a.value),className:`segmented-option min-h-11 ${r?"segmented-option-active":""}`,children:a.label},a.value)})})]})}function gr({row:t,isProject:s=!1,metricState:n="measured",shareContext:a,canManage:r,onPin:o,onUnpin:i}){const d=!s&&r&&!t.pinned&&!!o,c=!s&&r&&t.pinned&&!!i,u=n==="measured",m=u&&t.sampleUrls.length>0,[x,g]=l.useState(!1),[h,p]=l.useState(null);async function y(j,w){if(!(!w||x)){g(!0),p(null);try{await w(t.domain)===!1&&p(`Could not ${j} competitor. Try again.`)}catch{p(`Could not ${j} competitor. Try again.`)}finally{g(!1)}}}return e.jsxs("tr",{children:[e.jsxs("th",{scope:"row",className:"font-medium text-heading",children:[t.label,s?e.jsx("span",{className:"ml-1 text-secondary",children:"(you)"}):null]}),e.jsx("td",{className:"text-secondary",children:s?"Your brand":Jo(t.surfaceClass)}),e.jsx("td",{className:"tabular-nums text-strong",children:u?Ul(t.shareOfVoice,a):Fa(n)}),e.jsx("td",{className:"tabular-nums text-secondary",children:u?t.mentionCount:Fa(n)}),e.jsx("td",{className:"tabular-nums text-secondary",children:u?t.citationCount:Fa(n)}),e.jsx("td",{className:"text-right",children:d||c||m?e.jsxs("div",{className:"flex min-w-max items-start justify-end gap-2",children:[m?e.jsxs("details",{className:"inline-disclosure text-left text-xs text-secondary",children:[e.jsx("summary",{children:"Source URLs"}),e.jsx("ul",{className:"mt-2 max-w-72 space-y-1 font-mono text-[11px] font-normal",children:t.sampleUrls.map(j=>e.jsx("li",{className:"break-all",children:j},j))})]}):null,c&&i?e.jsxs(A,{type:"button",size:"sm",variant:"outline",disabled:x,onClick:()=>{y("unpin",i)},children:["Unpin"," ",e.jsx("span",{className:"sr-only",children:t.domain})]}):null,d&&o?e.jsxs(A,{type:"button",size:"sm",variant:"outline",disabled:x,onClick:()=>{y("pin",o)},children:["Pin"," ",e.jsx("span",{className:"sr-only",children:t.domain})]}):null,h?e.jsx("span",{role:"alert",className:"sr-only",children:h}):null]}):e.jsx("span",{className:"text-faint",children:"—"})})]})}function fr({children:t}){return e.jsx("tr",{className:"competitor-landscape-group",children:e.jsx("th",{scope:"rowgroup",colSpan:6,children:t})})}function Xm({rows:t,shareContext:s,canManage:n,onPin:a}){const[r,o]=l.useState(!1),i=r?t:t.slice(0,di);return e.jsxs("tbody",{children:[e.jsx(fr,{children:"Observed in this window"}),i.map(d=>e.jsx(gr,{row:{...d,pinned:!1},shareContext:s,canManage:n,onPin:a},d.domain)),t.length>di?e.jsx("tr",{children:e.jsx("td",{colSpan:6,children:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("span",{className:"text-sm text-secondary",children:["Showing ",i.length," of ",t.length," observed competitors."]}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11 text-sm","aria-expanded":r,"aria-label":r?"Show fewer observed competitors":`Show all ${t.length} observed competitors`,onClick:()=>o(d=>!d),children:r?"Show fewer":`Show all ${t.length}`})]})})}):null]})}function Zm({onAddCompetitor:t}){const s=l.useId(),[n,a]=l.useState(""),[r,o]=l.useState(!1),[i,d]=l.useState(null);async function c(){const u=n.trim();if(!(!u||r)){o(!0),d(null);try{if(await t(u)===!1){d("Could not add competitor. Try again.");return}a("")}catch{d("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:u=>{u.preventDefault(),c()},"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:u=>a(u.target.value),placeholder:"competitor.com",className:"mt-1 h-10 w-full rounded-md border border-default bg-surface px-3 text-sm text-primary placeholder-mono-600 focus:outline-none focus:ring-2 focus:ring-mono-400"})]}),e.jsx(A,{type:"submit",size:"sm",className:"min-h-10",disabled:r||!n.trim(),children:r?"Adding…":"Add competitor"}),i?e.jsx("p",{role:"alert",className:"w-full text-sm text-negative",children:i}):null]})]})}function eh({window:t,landscape:s,pinnedFallback:n=[],canWrite:a,isEmbed:r,onWindowChange:o,onPin:i,onUnpin:d,onAddCompetitor:c,error:u,onRetry:m,isLoading:x=!1,scopeLabel:g}){const h=a&&!r,p=s?.pinned??n,y=s?.observed??[],j=s?.otherSources??[],w=s?.evidence,k=Ym(s),M=s?.marketState?.draft?.pendingCompetitorDomains.length??0;return e.jsxs("section",{"aria-labelledby":"competitor-landscape-title","aria-busy":x,className:"competitor-landscape",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Competitive"}),e.jsx("h2",{id:"competitor-landscape-title",children:"Competitor landscape"}),g?e.jsx("p",{className:"supporting-copy mt-1",children:g}):null,s?e.jsx("p",{className:"supporting-copy mt-1",children:Wm(s.filters?.queryClass)}):null,s?.reason?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:wo(s.reason)}):null]}),e.jsx(Jm,{value:t,onChange:o})]}),u?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:u}),m?e.jsx(A,{type:"button",size:"sm",variant:"outline",onClick:m,children:"Retry competitor history"}):null]}):null,x&&!s&&p.length===0?e.jsx("div",{role:"status","aria-live":"polite",className:"h-48 animate-pulse rounded-md bg-surface-subtle",children:e.jsx("span",{className:"sr-only",children:"Loading competitor history"})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"competitor-table-wrap",children:e.jsxs("table",{className:"competitor-table","aria-label":"Competitor landscape",children:[e.jsx("caption",{className:"sr-only",children:"Pinned competitors followed by competitors observed in the selected history window."}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Competitor"}),e.jsx("th",{scope:"col",children:"Type"}),e.jsx("th",{scope:"col",children:"Share of voice"}),e.jsx("th",{scope:"col",children:"Mentions"}),e.jsx("th",{scope:"col",children:"Citations"}),e.jsx("th",{scope:"col",children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsxs("tbody",{children:[s?e.jsxs(e.Fragment,{children:[e.jsx(fr,{children:"You"}),e.jsx(gr,{row:s.project,shareContext:s,isProject:!0,metricState:k,canManage:!1})]}):null,e.jsx(fr,{children:"Pinned"}),p.length>0?p.map(C=>e.jsx(gr,{row:{...C,pinned:!0},shareContext:s,metricState:k,canManage:h,onUnpin:d},C.domain)):e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"text-secondary",children:"No pinned competitors."})})]}),s&&y.length>0?e.jsx(Xm,{shareContext:s,rows:y,canManage:h,onPin:i},JSON.stringify([t,s.project.domain,s.scope,s.filters])):null]})}),w?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:[w.answeredResults," ",w.answeredResults===1?"answer":"answers"]}),w.missingAnswerTextResults>0?e.jsx("span",{className:"text-caution",children:"Answer data incomplete"}):null,w.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(Ws,{size:14,"aria-hidden":"true",className:"transition-transform group-open:rotate-180 motion-reduce:transition-none"})]})]}),e.jsxs("div",{className:"max-w-prose space-y-2 pb-2 pt-1",children:[y.length===0?e.jsx("p",{children:"No additional competitors were identified in this period."}):null,e.jsxs("p",{children:[w.sourceResults," ",w.sourceResults===1?"result includes":"results include"," source URLs."]}),w.missingAnswerTextResults>0?e.jsxs("p",{children:[w.missingAnswerTextResults," ",w.missingAnswerTextResults===1?"result has":"results have"," no answer text and ",w.missingAnswerTextResults===1?"is":"are"," excluded from mention share."]}):null,w.incompleteSourceResults>0?e.jsxs("p",{children:[w.incompleteSourceResults," ",w.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,w.excludedProbeResults+w.excludedNonCompletedResults>0?e.jsxs("p",{children:[w.excludedProbeResults+w.excludedNonCompletedResults," test or unfinished ",w.excludedProbeResults+w.excludedNonCompletedResults===1?"result is":"results are"," excluded."]}):null,s.truncated?e.jsx("p",{children:"Lists include up to 100 observed competitors and 100 other sources. All pinned competitors are included."}):null]})]}):null,M>0?e.jsx("p",{className:"text-sm text-secondary",children:s?.scope.kind==="all-markets"?`${M} competitor${M===1?" is":"s are"} pending publication across markets.`:`${M} competitor${M===1?" is":"s are"} pending publication for this market.`}):null,(s?.observedNames?.length??0)>0?e.jsxs("details",{className:"inline-disclosure text-sm text-secondary",children:[e.jsx("summary",{children:"Names observed in answers"}),e.jsx("p",{children:"Names are observations. Only classified competitor domains enter share of voice."}),e.jsx("ul",{children:s?.observedNames?.map(C=>e.jsxs("li",{children:[C.name," · ",C.answerCount," answers"]},C.name))})]}):null,j.length>0?e.jsxs("details",{className:"inline-disclosure",children:[e.jsxs("summary",{children:["Other observed sources (",j.length,")"]}),e.jsx("ul",{className:"mt-3 space-y-2 text-sm text-secondary",children:j.map(C=>e.jsxs("li",{children:[e.jsxs("span",{children:[C.label," · ",Jo(C.surfaceClass)," · ",C.citationCount," citations"]}),C.sampleUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1 font-mono text-[11px] text-muted",children:C.sampleUrls.map(f=>e.jsx("li",{className:"break-all",children:f},f))}):null]},C.domain))})]}):null]}),h&&c?e.jsx(Zm,{onAddCompetitor:c}):null]})}function ui({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"}),d=new Date(n[o].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),c=n.map((u,m)=>{const x=new Date(u.createdAt).toLocaleDateString();return`${m===o?"Latest run, ":""}${x}: ${u.citationState}${u.model?`, model ${u.model}`:""}`}).join("; ");return e.jsxs("div",{className:"flex items-center gap-1",role:"img","aria-label":`Citation history across ${n.length} runs. ${c}`,children:[e.jsx("span",{className:"text-[9px] text-faint shrink-0","aria-hidden":"true",children:i}),e.jsx("div",{className:"flex items-center gap-[3px]",title:`${n.length} runs`,"aria-hidden":"true",children:n.map((u,m)=>{const x=!!(u.model&&m>0&&n[m-1]?.model&&n[m-1].model!==u.model),g=m===o;return e.jsx("span",{className:`h-2.5 w-2.5 ${r[u.citationState]??"rounded-sm"} ${a[u.citationState]??"bg-mono-700"} ${x?"ring-1 ring-caution-300/80 ring-offset-1 ring-offset-bg":""} ${g?"outline outline-1 outline-offset-2 outline-mono-400":""}`,title:[u.citationState,new Date(u.createdAt).toLocaleDateString(),u.model?`model ${u.model}`:null,x?"model changed":null,g?"latest run":null].filter(Boolean).join(" · ")},`${u.runId}:${u.createdAt}`)})}),e.jsxs("span",{className:"text-[9px] shrink-0 text-secondary","aria-hidden":"true",children:[d," ",e.jsx("span",{className:"text-faint",children:"latest"})]})]})}function yr(t){const s=new Map;for(const a of t)for(const r of a.runHistory){const o=s.get(r.createdAt);o?o.states.push(r.citationState):s.set(r.createdAt,{states:[r.citationState],runId:r.runId})}return[...s.entries()].sort(([a],[r])=>a.localeCompare(r)).map(([a,{states:r,runId:o}])=>({runId:o,createdAt:a,citationState:r.includes("cited")?"cited":r.includes("emerging")?"emerging":"not-cited"}))}const th=320;function sh(t){return t==="branded"?"Branded":t==="non-brand"?"Non-brand":"Unclassified"}function nh(t){return[t.phrase,t.location??"",...t.rawItems.map(s=>s.provider)].join(" ")}function mi(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 hi(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 xi(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 d=t.length-1;d>=0&&t[d].citationState===r;d--)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 ah(t,s){return t.map(n=>Xo(n,s))}function Xo(t,s){return s==="citations"?t:{...t,citationState:mi(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:mi(n,s)}))}}function pi(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",d=o==="cited"||o==="emerging";return r==="lost"||o!==null&&d&&!i?{key:s,label:`Lost ${n}`,tone:"negative"}:r==="emerging"||o!==null&&!d&&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 rh(t){const s=yr(ah(t,"mentions")),n=yr(t);return[pi(s,"mentions"),pi(n,"citations")]}function ih({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 gi({items:t}){return e.jsx("div",{className:"mt-1 flex flex-wrap gap-1","aria-label":"Latest run mention and citation signals",children:rh(t).map(s=>e.jsx(ih,{signal:s},s.key))})}function oh({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:a}=So(),[r,o]=l.useState(new Set),[i,d]=l.useState("mentions"),[c,u]=l.useState(n),[m,x]=l.useState("all"),g=l.useMemo(()=>{const f=new Map;for(const v of t){const S=v.query,R=v.queryClass??null,E=s?v.location??null:null,L=JSON.stringify([S,R,E]),B=f.get(L)??{key:L,phrase:S,queryClass:R,location:E,items:[],rawItems:[]};B.items.push(Xo(v,i)),B.rawItems.push(v),f.set(L,B)}return[...f.values()]},[t,i,s]),h=l.useMemo(()=>g.filter(f=>m==="all"||(m==="unclassified"?f.queryClass===null:f.queryClass===m)),[g,m]),p=xn({rows:h,getSearchText:nh}),y=p.rows.map(f=>f.key),j=y.length>0&&y.every(f=>r.has(f)),w=f=>{o(v=>{const S=new Set(v);return S.has(f)?S.delete(f):S.add(f),S})},k=i==="mentions"?"mentioned":"cited",M=i==="mentions"?"Mention History":"Citation History",C=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:()=>d("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:()=>d("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(f=>{const v=new Set(f);for(const S of y)j?v.delete(S):v.add(S);return v})},children:j?"Collapse page":"Expand page"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Density"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-bg-elevated/60 border border-subtle",role:"tablist","aria-label":"Evidence row density",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":c==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${c==="compact"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>u("compact"),children:"Compact"}),e.jsx("button",{type:"button",role:"tab","aria-selected":c==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${c==="detailed"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>u("detailed"),children:"Detailed"})]})]})]})]}),g.length>0?e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-3",children:[e.jsx(Bs,{value:p.query,onChange:p.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:f=>{x(f.target.value),p.setPage(1)},className:"h-9 rounded-md border border-default bg-surface px-3 text-sm text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500",children:[e.jsx("option",{value:"all",children:"All queries"}),e.jsx("option",{value:"branded",children:"Branded"}),e.jsx("option",{value:"non-brand",children:"Non-brand"}),e.jsx("option",{value:"unclassified",children:"Unclassified"})]})]})]}):null,e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{style:{width:"2rem"}}),e.jsx("th",{scope:"col",children:"Query"}),e.jsx("th",{scope:"col",children:"Status"}),e.jsx("th",{scope:"col",children:M}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:p.rows.map(({key:f,phrase:v,queryClass:S,location:R,items:E,rawItems:L})=>{const B=r.has(f),U=E.map(G=>G.citationState),T=U.includes("cited")?"cited":U.includes("emerging")?"emerging":U.includes("lost")?"lost":U.every(G=>G==="pending")?"pending":"not-cited",N=yr(E),D=E.filter(G=>G.citationState===Bl.cited||G.citationState==="emerging").length,J=xi(N,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:()=>w(f),onKeyDown:G=>{(G.key==="Enter"||G.key===" ")&&(G.preventDefault(),w(f))},tabIndex:0,role:"button","aria-expanded":B,children:[e.jsx("td",{children:e.jsx(Do,{size:14,className:`transition-transform duration-150 text-muted ${B?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-heading",children:v}),s&&e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-muted",children:R??"No location"}),e.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[e.jsx(le,{tone:"neutral",className:"whitespace-nowrap",children:sh(S)}),E.map(G=>e.jsx(Cn,{provider:G.provider},G.id))]})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pr,{state:T,label:hi(T,i)}),e.jsxs("span",{className:"text-[11px] text-muted",title:`${D} of ${E.length} engines ${C}`,children:[D,"/",E.length]})]})}),e.jsx("td",{children:e.jsx(ui,{history:N})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:J}),e.jsx(gi,{items:L})]}),e.jsx("td",{})]}),B&&E.map((G,Z)=>e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"bg-surface",children:[e.jsx("td",{}),e.jsx("td",{className:"evidence-query-cell pl-5",children:e.jsx(Cn,{provider:G.provider})}),e.jsx("td",{children:e.jsx(pr,{state:G.citationState,label:hi(G.citationState,i)})}),e.jsx("td",{children:e.jsx(ui,{history:G.runHistory})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:xi(G.runHistory,i)}),e.jsx(gi,{items:[L[Z]??G]})]}),e.jsx("td",{children:e.jsx(A,{variant:"ghost",size:"sm",type:"button",onClick:de=>{de.stopPropagation(),a(G.id)},children:"View"})})]}),c==="detailed"&&e.jsxs("tr",{className:"bg-surface-subtle",children:[e.jsx("td",{}),e.jsx("td",{colSpan:5,className:"px-5 pb-4",children:e.jsx(dh,{item:G,onViewFull:()=>a(G.id)})})]})]},G.id))]},f)})})]})}),p.totalRows===0&&(p.hasQuery||m!=="all")?e.jsx("p",{className:"supporting-copy mt-3",children:"No tracked queries match this filter."}):null,e.jsx(Rs,{page:p.page,pageSize:p.pageSize,visibleRows:p.rows.length,totalRows:p.totalRows,onPageChange:p.setPage,itemLabel:p.hasQuery||m!=="all"?"matches":"queries"}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",k==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function lh(t){const s=(t.matchedTerms??[]).filter(r=>r.trim().length>2),n=[...(t.mentionedCompetitorDomains??[]).flatMap(r=>{const o=zl(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 fi(t,s){const n=s.toLowerCase().replace(/^www\./,"");return(t.citedCompetitorDomains??[]).some(a=>a.toLowerCase().replace(/^www\./,"")===n)}function ch(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 dh({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}=ch(t.answerSnippet,th),o=lh(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:Vl(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] ${fi(t,i)?"border-negative-900/40 bg-negative-950/30 text-negative":"border-mono-700/60 bg-bg-elevated/60 text-neutral"}`,children:[i,fi(t,i)?" · competitor source":""]},`c-${i}`)),t.citedDomains.length>6&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.citedDomains.length-6," more"]})]}),(t.mentionedCompetitorDomains?.length??0)>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-negative-500/80",children:"Competitors in answer:"}),t.mentionedCompetitorDomains.slice(0,4).map(i=>e.jsx("span",{className:"rounded-full border border-negative-900/40 bg-negative-950/30 px-2 py-0.5 text-[11px] text-negative",children:i},`co-${i}`)),t.mentionedCompetitorDomains.length>4&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.mentionedCompetitorDomains.length-4," more"]})]})]}),r&&e.jsx("button",{type:"button",className:"text-[11px] font-medium text-positive-400 hover:text-positive",onClick:i=>{i.stopPropagation(),s()},children:"View full answer →"})]})}function ea({label:t,value:s,tone:n}){const a=n==="positive"?"text-positive-400":n==="negative"?"text-negative-400":"text-strong";return e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:t}),e.jsx("p",{className:`mt-2 text-2xl font-semibold ${a}`,children:s})]})}function Ra({windows:t,value:s,onChange:n,label:a,formatOption:r,disabled:o=!1}){return e.jsx("div",{className:"segmented",role:"group","aria-label":a,children:t.map(i=>e.jsx("button",{type:"button","aria-pressed":s===i,disabled:o,className:`segmented-option ${s===i?"segmented-option-active":""}`,onClick:()=>n(i),children:r?r(i):i},i))})}const Ga=nt[0],Ka=nt[1],yi=nt[2],bi=nt[3],uh=["both","server","ga4"],vi={fontSize:11,paddingTop:6},ji=new Set(["Pages crawled trend","Page fetches trend","Visits trend"]),Ni=t=>typeof t=="number"?zs(Math.round(t)):String(t),ts=t=>typeof t=="number"&&Number.isFinite(t)?t:0;function _a(t,s){if(!t||s<2)return Array(s).fill(null);const n=t.endIndex-t.startIndex;if(n<=0)return Array(s).fill(null);const a=(t.end-t.start)/n;return Array.from({length:s},(r,o)=>o<t.startIndex||o>t.endIndex?null:t.start+(o-t.startIndex)*a)}function Ua({label:t,value:s,caption:n,tooltip:a}){return e.jsxs("div",{className:"rounded-lg border border-default bg-bg/40 px-4 py-3 flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-1 mb-1",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted",children:t}),e.jsx(Me,{text:a})]}),e.jsx("p",{className:"text-xl font-semibold text-primary tabular-nums",children:s}),e.jsx("p",{className:"text-xs text-muted mt-0.5",children:n})]})}function mh(t,s){return n=>{const{cx:a,cy:r,index:o,key:i}=n,d=o??-1;return!(t[d]!=null&&t[d-1]==null&&t[d+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 hh({projectName:t,sinceMinutes:s}){const[n,a]=l.useState(!0),[r,o]=l.useState(!0),[i,d]=l.useState("both"),c=fm(t,{sinceMinutes:s,granularity:"day",limit:1}),u=ym(t),x=we({...Co({client:W,path:{name:t}}),enabled:!!t,staleTime:dn}).data?.connected===!0,g=we({...ko({client:W,path:{name:t},query:{window:s>=2160*60?"90d":s>=720*60?"30d":"7d"}}),enabled:!!t&&x,staleTime:dn}),h=l.useMemo(()=>c.data?.series?.points??[],[c.data]),p=l.useMemo(()=>{const R=g.data;return new Map((R?.days??[]).map(E=>[E.date,E.sessions]))},[g.data]),y=l.useMemo(()=>{const R=L=>L.measured!==!1;if(h.length===0||R(h[0]))return null;const E=h.findIndex(R)-1;return E<0?{from:h[0].bucket,to:h[h.length-1].bucket}:{from:h[0].bucket,to:h[E].bucket}},[h]),j=c.data?.series?.coverageStart??null,w=c.data?.series?.trends,k=l.useMemo(()=>{const R=_a(w?.crawlerContentHits,h.length),E=_a(w?.aiUserFetchHits,h.length),L=_a(w?.aiReferralLandedHits,h.length);return h.map((B,U)=>({...B,crawlerContentHits:B.measured!==!1?ts(B.crawlerContentHits):null,aiUserFetchHits:B.measured!==!1?ts(B.aiUserFetchHits):null,aiReferralLandedHits:B.measured!==!1?ts(B.aiReferralLandedHits):null,ga4Visits:p.get(B.bucket)??null,crawlTrend:R[U],fetchTrend:E[U],visitTrend:L[U]}))},[h,p,w]),M=c.data?.totals,C=M&&{crawlers:ts(M.crawlerContentHits),fetches:ts(M.aiUserFetchHits),visits:ts(M.aiReferralLandedHits)},f=l.useMemo(()=>h.reduce((R,E)=>({crawlers:R.crawlers+ts(E.crawlerContentHits),fetches:R.fetches+ts(E.aiUserFetchHits),visits:R.visits+ts(E.aiReferralLandedHits)}),{crawlers:0,fetches:0,visits:0}),[h]),v=C??f,S=v.crawlers>0||v.fetches>0||v.visits>0;if(c.isLoading)return e.jsx(xe,{className:"surface-card p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading AI traffic history…"})});if(c.isError)return e.jsxs(xe,{className:"surface-card p-5",children:[e.jsx("p",{className:"text-sm text-secondary",children:"Could not load AI traffic history."}),e.jsx("p",{className:"text-xs text-muted mt-1",children:"The request failed, so this is not a reading of zero activity. Retry, or check the traffic source."})]});if(!S){const R=u.data?.sources,E=R!==void 0&&R.length===0,L=!E&&j===null;return e.jsxs(xe,{className:"surface-card p-5",children:[e.jsx("p",{className:"text-sm text-secondary",children:E?"No server-side traffic source connected yet.":L?"No AI activity recorded yet.":"No AI activity recorded in this period."}),e.jsx("p",{className:"text-xs text-muted mt-1",children:E?"Connect a traffic source to see how AI engines read this site over time.":L?"The source is connected but has not reported anything yet. A new source can take a few hours to appear.":"The window was measured and nothing was recorded. Try a longer range."})]})}return e.jsxs(xe,{className:"surface-card p-5",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3 mb-5",children:[e.jsx(Ua,{label:"AI crawlers",value:zs(v.crawlers),caption:"pages crawled",tooltip:"Requests from AI crawlers for a real content page. Robots.txt and sitemap re-fetches are excluded, because they are not a page an engine read."}),e.jsx(Ua,{label:"AI page fetches",value:zs(v.fetches),caption:"reading a page to answer",tooltip:"An AI engine fetching a page live while answering someone, rather than crawling it for an index."}),e.jsx(Ua,{label:"AI visitors",value:zs(v.visits),caption:"arrived from an AI answer",tooltip:"Visits your server answered that came from an AI engine. Requests answered with a redirect are excluded: a redirect is a hop, not an arrival."})]}),h.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:ts(h[h.length-1].crawlerContentHits).toLocaleString()}),"pages crawled"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:ts(h[h.length-1].aiUserFetchHits).toLocaleString()}),"page fetches"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:ts(h[h.length-1].aiReferralLandedHits).toLocaleString()}),"visits, server"]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-heading font-semibold tabular-nums mr-1",children:p.get(h[h.length-1].bucket)?.toLocaleString()??"—"}),"visits, GA4"]}),e.jsx("span",{className:"text-faint",children:"still filling"})]}),e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Machines reading your site"}),e.jsx(Me,{text:"Crawlers index pages for later. Page fetches happen while an engine is answering someone. Both are machines, not people."})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-secondary cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:n,onChange:R=>a(R.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:R=>o(R.target.checked),className:"accent-current"}),"Trend line"]})]})]}),e.jsx(Ys,{width:"100%",height:206,children:e.jsxs(Js,{data:k,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(Vn,{stroke:Bn,vertical:!1}),e.jsx(Xs,{dataKey:"bucket",tick:Rt,stroke:is,tickFormatter:pn,minTickGap:28}),e.jsx(Zs,{tick:Rt,stroke:is,width:48,allowDecimals:!1}),e.jsx(en,{contentStyle:Xt.contentStyle,labelStyle:Xt.labelStyle,itemStyle:Xt.itemStyle,labelFormatter:Ot,formatter:Ni}),y&&e.jsx(xr,{x1:y.from,x2:y.to,fill:"var(--color-overlay-hover)",fillOpacity:.5,stroke:"none",label:{value:"not measured",position:"insideTop",fontSize:10,fill:"var(--chart-neutral-text-dim, #71717a)"}}),e.jsx(wa,{wrapperStyle:vi,iconType:"plainline",iconSize:14,formatter:R=>ji.has(R)?"":R}),e.jsx(Gs,{type:"monotone",dataKey:"crawlerContentHits",name:"Pages crawled",stroke:Ga,fill:Ga,fillOpacity:.22,strokeWidth:1.8}),n&&e.jsx(Gs,{type:"monotone",dataKey:"aiUserFetchHits",name:"Page fetches",stroke:Ka,fill:Ka,fillOpacity:.18,strokeWidth:1.6}),r&&e.jsx(Ps,{type:"linear",dataKey:"crawlTrend",name:"Pages crawled trend",dot:!1,tooltipType:"none",stroke:Ga,strokeWidth:1.4,strokeDasharray:"5 4",connectNulls:!0}),r&&n&&e.jsx(Ps,{type:"linear",dataKey:"fetchTrend",name:"Page fetches trend",dot:!1,tooltipType:"none",stroke:Ka,strokeWidth:1.3,strokeDasharray:"5 4",connectNulls:!0})]})}),e.jsxs("div",{className:"flex items-center justify-between gap-3 mt-5 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"People arriving from AI"}),e.jsx(Me,{text:"Two independent counts of the same thing. Server reads your own logs and misses nothing a browser blocks, but cannot see a page served from cache. GA4 needs the browser to run a tag. They rarely match, and neither is the correction of the other."})]}),e.jsx(Ra,{windows:uh,value:i,onChange:d,label:"Visit measurement source",formatOption:R=>R==="ga4"?"GA4":R==="both"?"Both":"Server"})]}),e.jsx(Ys,{width:"100%",height:176,children:e.jsxs(Js,{data:k,margin:{top:4,right:8,left:-18,bottom:0},children:[e.jsx(Vn,{stroke:Bn,vertical:!1}),e.jsx(Xs,{dataKey:"bucket",tick:Rt,stroke:is,tickFormatter:pn,minTickGap:28}),e.jsx(Zs,{tick:Rt,stroke:is,width:48,allowDecimals:!1}),e.jsx(en,{contentStyle:Xt.contentStyle,labelStyle:Xt.labelStyle,itemStyle:Xt.itemStyle,labelFormatter:Ot,formatter:Ni}),y&&e.jsx(xr,{x1:y.from,x2:y.to,fill:"var(--color-overlay-hover)",fillOpacity:.5,stroke:"none",label:{value:"not measured",position:"insideTop",fontSize:10,fill:"var(--chart-neutral-text-dim, #71717a)"}}),e.jsx(wa,{wrapperStyle:vi,iconType:"plainline",iconSize:14,formatter:R=>ji.has(R)?"":R}),i!=="ga4"&&e.jsx(Ps,{type:"monotone",dataKey:"aiReferralLandedHits",name:"Visits, server",stroke:yi,strokeWidth:2,dot:!1}),i!=="server"&&e.jsx(Ps,{type:"monotone",dataKey:"ga4Visits",name:"Visits, GA4",connectNulls:!1,stroke:bi,strokeWidth:1.8,strokeDasharray:"5 3",dot:mh(k.map(R=>R.ga4Visits),bi)}),r&&i!=="ga4"&&e.jsx(Ps,{type:"linear",dataKey:"visitTrend",name:"Visits trend",dot:!1,tooltipType:"none",stroke:yi,strokeWidth:1.3,strokeDasharray:"5 4",connectNulls:!0})]})})]})}const xh=6,kn="__other__",wn="_socialTotal";function ph(t,s=xh){const n=new Map;for(const m of t)n.set(m.source,(n.get(m.source)??0)+m.sessions);const a=[...n.entries()].sort((m,x)=>x[1]!==m[1]?x[1]-m[1]:m[0].localeCompare(x[0])),r=a.slice(0,s),o=new Set(r.map(([m])=>m)),i=Math.max(0,a.length-s),d=new Map;for(const m of t){let x=d.get(m.date);x||(x={date:m.date,[wn]:0},d.set(m.date,x));const g=o.has(m.source)?m.source:kn;x[g]=(x[g]??0)+m.sessions,x[wn]=(x[wn]??0)+m.sessions}const c=[...d.values()].sort((m,x)=>String(m.date).localeCompare(String(x.date))),u=r.map(([m])=>m);return i>0&&u.push(kn),{data:c,sources:u,otherCount:i}}function Sn(t){return t.replace(/\+/g," ")}function Zo(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const wi="_totalSessions",Si="_organicSessions";function gh(t,s){const n=new Map;for(const i of s)n.set(i.date,{[wi]:i.sessions,[Si]:i.organicSessions});for(const i of t.days){let d=n.get(i.date);d||(d={[wi]:0,[Si]:0},n.set(i.date,d));for(const c of i.bySource)d[c.source]=(d[c.source]??0)+c.sessions}const a=[...n.entries()].sort(([i],[d])=>i.localeCompare(d)).map(([i,d])=>({date:i,...d})),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 fh=["7d","30d","90d"],yh={"7d":10080,"30d":720*60,"90d":2160*60,all:2160*60},Fs=nt,br=os.textDim,el=os.textFaint,Tn=25;function bh(t){return Ko(t.landingPage)}const vh=25,jh=10,Ba={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0};function ta(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function tl(t){const s=Date.now()-new Date(t).getTime(),n=Math.floor(s/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const a=Math.floor(n/60);return a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`}function Nh({projectName:t}){const{data:s,isLoading:n,isError:a}=bm(t);if(n)return e.jsx(xe,{className:"p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading server activity…"})});if(a)return e.jsx(xe,{className:"p-5",children:e.jsx("div",{className:"text-sm text-negative-400",children:"Failed to load server activity."})});const r=s?.sources??[];return e.jsxs("section",{children:[e.jsx("div",{className:"flex items-baseline justify-between mb-3",children:e.jsxs("div",{children:[e.jsx("div",{className:"eyebrow",children:"Server activity (last 24h)"}),e.jsx("h2",{className:"text-lg font-semibold text-primary",children:"Server activity"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["Crawler, AI fetch, and referral activity from connected sources."," ",!te()&&e.jsx(js,{to:"/traffic",className:"text-link hover:underline",children:"Manage sources →"})]})]})}),r.length===0?e.jsx(xe,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-secondary",children:["No server traffic source connected yet."," ",!te()&&e.jsxs(e.Fragment,{children:[e.jsx(js,{to:"/traffic",className:"text-link hover:underline",children:"Connect a traffic source"})," ","to surface bot crawls and AI referrals straight from server logs."]})]})}):e.jsx(xe,{className:"overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-bg-elevated/50 text-[10px] uppercase tracking-wide text-muted",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Source"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Status"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Crawler hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI sessions 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Last sync"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium","aria-label":"open"})]})}),e.jsx("tbody",{children:r.map(o=>e.jsxs("tr",{className:"border-t border-default",children:[e.jsx("td",{className:"px-4 py-3 text-heading",children:o.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(le,{tone:vm(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?tl(o.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:te()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(js,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:o.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},o.id))})]})})]})}function wh({projectName:t}){const[s,n]=l.useState("30d");return e.jsxs("div",{className:"space-y-10",children:[e.jsx(Nh,{projectName:t}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(Ra,{windows:fh,value:s,onChange:n,label:"Traffic time period"})}),e.jsx(Sh,{projectName:t,window:s}),e.jsx(hh,{projectName:t,sinceMinutes:yh[s]})]})}function Sh({projectName:t,window:s}){const n=Ns(),a=s??"30d",[r,o]=l.useState(null),[i,d]=l.useState(null),[c,u]=l.useState(!0),[m,x]=l.useState(!1),[g,h]=l.useState(!1),[p,y]=l.useState(null),[j,w]=l.useState(null),[k,M]=l.useState("sessions"),[C,f]=l.useState("desc"),[v,S]=l.useState("sessions"),[R,E]=l.useState("desc"),[L,B]=l.useState("sessions"),[U,T]=l.useState("desc"),[N,D]=l.useState("sessions"),[J,G]=l.useState("desc"),[Z,de]=l.useState(Ba),[se,Q]=l.useState([]),[$,ie]=l.useState([]),[O,_]=l.useState(!1);async function X(Y){u(!0),y(null);try{const Re=await n.fetchQuery({...Co({client:W,path:{name:t}}),staleTime:dn});if(Y.current)return;if(o(Re),!Re.connected){d(null),de(Ba),Q([]),ie([]),u(!1);return}const be=a==="all"?void 0:a,je=await n.fetchQuery({...Ql({client:W,path:{name:t},query:be?{window:be}:void 0}),staleTime:dn}).then(ls=>ls),Gt=je.windowStart||je.windowEnd?{...je.windowStart?{startDate:je.windowStart}:{},...je.windowEnd?{endDate:je.windowEnd}:{}}:void 0,[ze,ft,Tt]=await Promise.all([n.fetchQuery({...ko({client:W,path:{name:t},query:be?{window:be}:void 0}),staleTime:dn}).catch(()=>Ba),n.fetchQuery({...Hl({client:W,path:{name:t},query:be?{window:be}:void 0}),staleTime:dn}).catch(()=>[]),n.fetchQuery({...Wl({client:W,path:{name:t},query:Gt}),staleTime:dn}).catch(()=>[])]);if(Y.current)return;d(je),de(ze),Q(ft),ie(Tt),u(!1)}catch(Re){if(Y.current)return;y(Re instanceof Error?Re.message:"Failed to load GA4 data"),u(!1)}}l.useEffect(()=>{const Y={current:!1};return X(Y),()=>{Y.current=!0}},[t,a,n]);async function ge(){x(!0),y(null),w(null);try{const Y=await Ao(t);w(`Synced ${Y.rowCount.toLocaleString()} page rows, ${Y.aiReferralCount.toLocaleString()} AI and ${Y.socialReferralCount.toLocaleString()} social referral rows (${Y.days} days)`),await Nt(n,"ga"),await X({current:!1})}catch(Y){y(Y instanceof Error?Y.message:"Sync failed")}finally{x(!1)}}async function H(){h(!0),y(null),w(null);try{await Yl(t),await Nt(n,"ga"),o({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),d(null),w("GA4 disconnected")}catch(Y){y(Y instanceof Error?Y.message:"Disconnect failed")}finally{h(!1)}}function ae(Y){Pe.setPage(1),k===Y?f(Re=>Re==="desc"?"asc":"desc"):(M(Y),f("desc"))}function ue(Y){v===Y?E(Re=>Re==="desc"?"asc":"desc"):(S(Y),E("desc"))}function Oe(Y){L===Y?T(Re=>Re==="desc"?"asc":"desc"):(B(Y),T("desc"))}const Fe=l.useMemo(()=>i?.topPages?[...i.topPages].sort((Y,Re)=>{const be=Y[k],je=Re[k];return typeof be=="string"&&typeof je=="string"?C==="asc"?be.localeCompare(je):je.localeCompare(be):C==="asc"?be-je:je-be}):[],[i?.topPages,k,C]),Pe=xn({rows:Fe,getSearchText:Y=>Ko(Y.landingPage),pageSize:jh}),tt=l.useMemo(()=>i?.aiReferrals?[...i.aiReferrals].sort((Y,Re)=>{const be=Y[v],je=Re[v];return typeof be=="string"&&typeof je=="string"?R==="asc"?be.localeCompare(je):je.localeCompare(be):R==="asc"?be-je:je-be}):[],[i?.aiReferrals,v,R]),it=l.useMemo(()=>i?.aiReferralLandingPages?[...i.aiReferralLandingPages].sort((Y,Re)=>{const be=Y[N],je=Re[N];return typeof be=="string"&&typeof je=="string"?J==="asc"?be.localeCompare(je):je.localeCompare(be):J==="asc"?be-je:je-be}):[],[i?.aiReferralLandingPages,N,J]),ke=xn({rows:it,getSearchText:bh,pageSize:vh}),Xe=ke.totalRows>0?`${ke.totalRows.toLocaleString()} ${ke.hasQuery?ke.totalRows===1?"match":"matches":ke.totalRows===1?"row":"rows"}`:ke.hasQuery&&(i?.aiReferralLandingPages.length??0)>0?"0 matches":"No landing-page rows";function _e(Y){ke.setPage(1),N===Y?G(Re=>Re==="desc"?"asc":"desc"):(D(Y),G("desc"))}const Ve=l.useMemo(()=>i?.socialReferrals?[...i.socialReferrals].sort((Y,Re)=>{const be=Y[L],je=Re[L];return typeof be=="string"&&typeof je=="string"?U==="asc"?be.localeCompare(je):je.localeCompare(be):U==="asc"?be-je:je-be}):[],[i?.socialReferrals,L,U]),{socialChartData:He,socialChartSources:Te,socialOtherCount:V}=l.useMemo(()=>{const Y=ph($);return{socialChartData:Y.data,socialChartSources:Y.sources,socialOtherCount:Y.otherCount}},[$]),{chartData:F,chartSources:z,dateRange:Ne}=l.useMemo(()=>{const Y=gh(Z,se);return{chartData:Y.data,chartSources:Y.sources,dateRange:Y.dateRange}},[Z,se]);if(c&&!r)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!r?.connected)return te()?e.jsx(xe,{className:"p-5",children:e.jsx("div",{className:"text-sm text-secondary",children:"No Google Analytics 4 property connected yet."})}):e.jsx(Ch,{projectName:t,onConnected:()=>{(async()=>(await Nt(n,"ga"),await X({current:!1})))()}});const Ie=i?.organicSharePctDisplay??"0%",ee=i?.channelBreakdown?.organic.sharePctDisplay??Ie,We=i?.channelBreakdown?.organic.sessions??i?.totalOrganicSessions??0,ht=i?.aiSessionsDeduped??0,Ze=i?.channelBreakdown?.ai.sessions??i?.aiSessionsBySession??0,ye=i?.channelBreakdown?.ai.sharePctDisplay??i?.aiSharePctBySessionDisplay??"0%",Ge=i?.paidAiSessionsBySession??0,It=i?.paidAiSharePctBySessionDisplay??"0%",xt=i?new Set(i.aiReferrals.map(Y=>Y.source.toLowerCase())).size:0,qe=tt[0]??null,Ye=i?.totalDirectSessions??0,pt=i?.directSharePctDisplay??"0%",St=i?.channelBreakdown?.direct.sessions??Ye,Ke=i?.channelBreakdown?.direct.sharePctDisplay??pt,Le=i?.channelBreakdown?.other.sessions??i?.otherSessions??0,et=i?.channelBreakdown?.other.sharePctDisplay??i?.otherSharePctDisplay??"0%",Ue=i?.socialSessions??0,Be=i?.socialSharePctDisplay??"0%",$t=i?.channelBreakdown?.social.sessions??Ue,vt=i?.channelBreakdown?.social.sharePctDisplay??Be,Ft=i?new Set(i.socialReferrals.map(Y=>Y.source.toLowerCase())).size:0,gt=Ve[0]??null;return e.jsxs(e.Fragment,{children:[p&&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:p}),j&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-positive-900/20 border border-positive-800/60 text-sm text-positive",children:j}),e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-positive-500"}),e.jsxs("span",{className:"text-xs text-secondary",children:["Property ",e.jsx("span",{className:"text-neutral",children:r.propertyId}),r.clientEmail&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"text-muted",children:r.clientEmail})]})]})]}),!te()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(A,{variant:"outline",size:"sm",disabled:m,onClick:Ee(ge),children:[e.jsx(Na,{className:`w-3.5 h-3.5 mr-1.5 ${m?"animate-spin":""}`}),m?"Syncing…":"Sync"]}),e.jsxs(A,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:g,onClick:Ee(H),children:[e.jsx(am,{className:"w-3.5 h-3.5 mr-1.5"}),"Disconnect"]})]})]}),e.jsxs("section",{children:[e.jsx("div",{className:"mb-4 flex items-start justify-between",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Traffic Overview"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Site Traffic",e.jsx(Me,{text:`Aggregated traffic metrics from Google Analytics 4.${i?.periodStart&&i?.periodEnd?` Data available: ${new Date(i.periodStart+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})} – ${new Date(i.periodEnd+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}.`:""} Distinct users are unavailable when the selected history extends beyond a stored aggregate. Organic sessions are Google organic search sessions specifically.`})]})]})}),i?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(Va,{value:ta(i.totalSessions),label:"Total Sessions",subtitle:i.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(Va,{value:ta(i.totalOrganicSessions),label:"Organic Sessions",subtitle:`${Ie} of total`,tone:"positive"}),e.jsx(Va,{value:i.totalUsers===null?"—":ta(i.totalUsers),label:"Total Users",subtitle:i.totalUsers===null?"Unavailable for this range":i.totalUsers.toLocaleString(),tone:"neutral"})]}):e.jsxs("div",{className:"surface-card rounded-lg p-6 text-center border border-default",children:[e.jsx("p",{className:"text-sm text-secondary mb-3",children:"No traffic data yet."}),!te()&&e.jsxs(A,{variant:"outline",size:"sm",disabled:m,onClick:Ee(ge),children:[e.jsx(Na,{className:`w-3.5 h-3.5 mr-1.5 ${m?"animate-spin":""}`}),"Sync from GA4"]})]})]}),i&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Traffic Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Traffic by channel",e.jsx(Me,{text:"Decomposes GA4 sessions into five disjoint channels — known AI referrers first, then organic search, social, direct, and other channels. Known AI includes paid and organic AI referrals; paid rows are labeled in the source table below. Known AI referrers are removed from their native GA4 channel before the residual Other bucket is computed."})]})]}),Ne&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(Ne.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(Ne.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),F.length>0&&e.jsxs(xe,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:z.length>0?"AI vs. total sessions":"All sessions (baseline)"}),z.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),z.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(Ys,{width:"100%",height:"100%",children:e.jsxs(Js,{data:F,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Xs,{dataKey:"date",tick:Rt,tickLine:!1,axisLine:{stroke:is},tickFormatter:pn}),e.jsx(Zs,{tick:Rt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(en,{...Xt,labelFormatter:Ot,formatter:(Y,Re)=>{const be=typeof Y=="number"?Y.toLocaleString():String(Y??0),je=String(Re??"");return je==="_totalSessions"?[be,"Total Sessions"]:je==="_organicSessions"?[be,"Organic Sessions"]:[be,je]}}),e.jsx(wa,{wrapperStyle:{fontSize:11,color:os.text},formatter:Y=>Y==="_totalSessions"?"Total Sessions":Y==="_organicSessions"?"Organic Sessions":Y}),e.jsx(Gs,{type:"monotone",dataKey:"_totalSessions",stroke:os.textFaint,fill:os.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),z.map((Y,Re)=>e.jsx(Gs,{type:"monotone",dataKey:Y,stackId:"ai",stroke:Fs[Re%Fs.length],fill:Fs[Re%Fs.length],fillOpacity:.4,strokeWidth:1.5},Y))]})})})]}),e.jsxs(xe,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Summary"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Sessions by channel"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(us,{label:"Organic",value:ee,hint:`${We.toLocaleString()} sessions`,tone:"positive",tooltip:"Sessions from Google organic search (sessionDefaultChannelGrouping = 'Organic Search'), after known AI referrers are removed for a disjoint channel breakdown."}),e.jsx(us,{label:"Social",value:vt,hint:`${$t.toLocaleString()} sessions`,tone:"neutral",tooltip:"Sessions from social platforms (sessionDefaultChannelGrouping = 'Organic Social' or 'Paid Social'), after known AI referrers are removed for a disjoint channel breakdown."}),e.jsx(us,{label:"Direct",value:Ke,hint:`${St.toLocaleString()} sessions`,tone:"neutral",tooltip:"Sessions with no source — bookmarks, typed URLs, untagged email, in-app browsers, and AI-driven traffic whose referrer header was stripped. Known AI referrers are removed if GA4 classified them as Direct."}),e.jsx(us,{label:"Visitors from AI (at least)",value:ye,hint:Ge>0?`${Ze.toLocaleString()} sessions · ${Ge.toLocaleString()} paid`:`${Ze.toLocaleString()} sessions`,tone:"positive",tooltip:"Sessions whose current sessionSource matched a known AI engine (e.g. chatgpt.com, claude.ai, gemini.google.com). Paid AI is inferred from paid/cpc/sponsored UTM values or GA4 paid channel groups. Untagged ad clicks with no referrer still fall under Direct because GA4 has no paid evidence for them."}),e.jsx(us,{label:"Other channels",value:et,hint:`${Le.toLocaleString()} sessions`,tone:"neutral",tooltip:"Remaining GA4 session default channel groups after Known AI, Organic Search, Organic/Paid Social, and Direct are accounted for. This is a residual bucket, not a single source. It can include Referral, Email, Paid Search, Display, Cross-network, Shopping, Video, Affiliates, SMS, Mobile Push Notifications, Paid Other, and unclassified traffic."})]}),qe&&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:qe.source})," via ",qe.medium,", accounting for ",qe.sessions.toLocaleString()," sessions.",Ge>0&&e.jsxs("span",{children:[" Paid AI: ",Ge.toLocaleString()," sessions (",It,")."]})]})]}),e.jsxs(xe,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Detail"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Where AI visitors came from"})]}),e.jsx("p",{className:"text-xs text-muted",children:i.aiReferrals.length>0?`${xt} unique sources, ${i.aiReferrals.length} rows`:"No source rows"})]}),i.aiReferrals.length>0?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(ss,{label:"Source",sortKey:"source",current:v,dir:R,onSort:ue,align:"left"}),e.jsx(ss,{label:"Medium",sortKey:"medium",current:v,dir:R,onSort:ue,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Class"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(ss,{label:"Sessions",sortKey:"sessions",current:v,dir:R,onSort:ue,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:tt.map(Y=>e.jsx(Ah,{referral:Y,totalSessions:ht},`${Y.source}:${Y.medium}:${Y.sourceDimension}`))})]})}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No AI referrer sessions detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"AI engines that preserve a referrer (Perplexity, copy/paste from ChatGPT, etc.) will appear here. Most AI traffic strips the referrer — see the Direct cell above for the upper bound."})]})]}),e.jsxs(xe,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Detail"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Pages AI visitors landed on"})]}),e.jsx("p",{className:"text-xs text-muted",children:Xe})]}),i.aiReferralLandingPages.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Bs,{value:ke.query,onChange:ke.setQuery,label:"Filter landing page URLs or query parameters",placeholder:"Filter URL or query parameters",className:"mb-4 max-w-md"}),ke.totalRows>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(ss,{label:"Landing Page",sortKey:"landingPage",current:N,dir:J,onSort:_e,align:"left"}),e.jsx(ss,{label:"Source",sortKey:"source",current:N,dir:J,onSort:_e,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(ss,{label:"Sessions",sortKey:"sessions",current:N,dir:J,onSort:_e,align:"right"})]})}),e.jsx("tbody",{children:ke.rows.map(Y=>e.jsx(Ph,{row:Y},`${Y.landingPage}:${Y.source}:${Y.medium}:${Y.sourceDimension}`))})]})}),e.jsx(Rs,{page:ke.page,pageSize:ke.pageSize,visibleRows:ke.rows.length,totalRows:ke.totalRows,onPageChange:ke.setPage,itemLabel:ke.hasQuery?"matches":"rows"})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary",children:"No landing pages match this filter"}),e.jsx("button",{type:"button",onClick:()=>ke.setQuery(""),className:"mt-2 text-xs text-link hover:underline focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",children:"Clear filter"})]})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No AI visits recorded yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"Pages appear here once a GA4 sync records a visit that arrived from an AI engine."})]})]})]})]}),i&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Social Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Social Media Traffic",e.jsx(Me,{text:"Tracks sessions classified as social traffic by GA4's default channel grouping (Organic Social and Paid Social). Google maintains the source-to-channel mapping."})]})]}),e.jsxs("div",{className:"grid gap-4",children:[e.jsxs(xe,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Summary"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Visits from social"})]}),i.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(us,{label:"Social Sessions",value:ta(Ue),hint:`${Ue.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(us,{label:"Share of Traffic",value:Be,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(us,{label:"Platforms",value:String(Ft),hint:`${i.socialReferrals.length} source rows`,tone:"neutral",tooltip:"Number of distinct social media platforms detected. Each unique source/medium combination counts as one source row."})]}),gt&&e.jsxs("div",{className:"mt-4 rounded-lg border border-info-800/40 bg-info-500/6 px-4 py-3 text-sm text-info-100",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-info-300/70 mb-1",children:"Top social source"}),e.jsx("p",{className:"font-medium truncate",title:`${gt.source} via ${gt.medium}`,children:Zo(Sn(gt.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:gt.medium,children:["via ",Sn(gt.medium)," · ",gt.sessions.toLocaleString()," sessions"]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(us,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(us,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(us,{label:"Platforms",value:"0",hint:"known platforms",tone:"neutral",tooltip:"Number of distinct social media platforms detected."})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3 text-sm text-secondary",children:[e.jsx("p",{className:"mb-1.5 text-neutral",children:"Monitoring social media traffic via GA4 channel grouping"}),e.jsx("p",{className:"text-xs text-muted",children:"Sessions classified as Organic Social or Paid Social by GA4 will appear here. Google maintains the source-to-channel mapping, which includes Facebook, Instagram, X/Twitter, LinkedIn, Reddit, Pinterest, Snapchat, and other platforms."})]})]})]}),He.length>0&&e.jsxs(xe,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social sessions"})]}),V>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",Te.length-1," sources · ",V," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(Ys,{width:"100%",height:"100%",children:e.jsxs(Js,{data:He,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Xs,{dataKey:"date",tick:Rt,tickLine:!1,axisLine:{stroke:is},tickFormatter:pn}),e.jsx(Zs,{tick:Rt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(en,{...Xt,labelFormatter:Ot,formatter:(Y,Re)=>{const be=typeof Y=="number"?Y.toLocaleString():String(Y??0),je=String(Re??"");if(je===wn)return[be,"Total Social"];if(je===kn){const Gt=`Other (${V} source${V===1?"":"s"})`;return[be,Gt]}return[be,Sn(je)]}}),e.jsx(Gs,{type:"monotone",dataKey:wn,stroke:el,fill:os.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),Te.map((Y,Re)=>{const je=Y===kn?br:Fs[Re%Fs.length];return e.jsx(Gs,{type:"monotone",dataKey:Y,stackId:"social",stroke:je,fill:je,fillOpacity:.4,strokeWidth:1.5},Y)})]})})}),e.jsx(Ih,{sources:Te,otherCount:V})]}),e.jsxs(xe,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Breakdown"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social sources"})]}),e.jsx("p",{className:"text-xs text-muted",children:i.socialReferrals.length>0?Ve.length>Tn&&!O?`Top ${Tn} of ${Ve.length}`:`${Ve.length} rows`:"No source rows"})]}),i.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm table-fixed",children:[e.jsxs("colgroup",{children:[e.jsx("col",{className:"w-[32%]"}),e.jsx("col",{className:"w-[22%]"}),e.jsx("col",{className:"w-[12%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[12%]"})]}),e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(ss,{label:"Source",sortKey:"source",current:L,dir:U,onSort:Oe,align:"left"}),e.jsx(ss,{label:"Medium",sortKey:"medium",current:L,dir:U,onSort:Oe,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(ss,{label:"Sessions",sortKey:"sessions",current:L,dir:U,onSort:Oe,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:(O?Ve:Ve.slice(0,Tn)).map(Y=>e.jsx(Rh,{referral:Y,totalSessions:Ue},`${Y.source}:${Y.medium}:${Y.channelGroup}`))})]})}),Ve.length>Tn&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>_(Y=>!Y),className:"rounded-md border border-base px-3 py-1.5 text-xs text-secondary transition-colors hover:border-strong hover:text-strong",children:O?`Show top ${Tn}`:`Show all ${Ve.length} sources`})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No social media sessions detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"When visitors arrive from Facebook, X/Twitter, LinkedIn, or other social platforms, their sessions will be broken down here by source and medium."})]})]})]})]})]}),i&&i.topPages.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Page Performance"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Top Landing Pages",e.jsx(Me,{text:"Landing pages ranked by session volume. Click column headers to sort. Organic % shows the share of sessions coming from Google organic search."})]})]}),e.jsx(Bs,{value:Pe.query,onChange:Pe.setQuery,label:"Filter landing page URLs",placeholder:"Filter landing pages",className:"mb-4 max-w-md"}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(ss,{label:"Landing Page",sortKey:"landingPage",current:k,dir:C,onSort:ae,align:"left"}),e.jsx(ss,{label:"Sessions",sortKey:"sessions",current:k,dir:C,onSort:ae,align:"right"}),e.jsx(ss,{label:"Organic",sortKey:"organicSessions",current:k,dir:C,onSort:ae,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"})]})}),e.jsx("tbody",{children:Pe.rows.map(Y=>e.jsx(kh,{page:Y},Y.landingPage))})]})}),Pe.totalRows===0&&Pe.hasQuery&&e.jsx("p",{className:"text-sm text-secondary mt-3",children:"No landing pages match this filter"}),e.jsx(Rs,{page:Pe.page,pageSize:Pe.pageSize,visibleRows:Pe.rows.length,totalRows:Pe.totalRows,onPageChange:Pe.setPage,itemLabel:Pe.hasQuery?"matches":"pages"})]})]}),e.jsxs("div",{className:"mt-6 flex items-center justify-between text-xs text-muted",children:[e.jsx("span",{children:i?.lastSyncedAt?`Last synced ${tl(i.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:i?`${i.topPages.length} pages · ${i.aiReferrals.length} AI rows · ${i.socialReferrals.length} social rows`:""})]})]})}function Ch({projectName:t,onConnected:s}){const[n,a]=l.useState(""),[r,o]=l.useState(null),[i,d]=l.useState(null),[c,u]=l.useState(!1),[m,x]=l.useState(null),g=l.useRef(null),h=l.useCallback(y=>{const j=y.target.files?.[0];if(!j)return;x(null),o(j.name);const w=new FileReader;w.onload=()=>{const k=w.result;try{const M=JSON.parse(k);if(!M.client_email||!M.private_key){x("JSON file is missing required fields: client_email and private_key. Make sure you downloaded a service account key (not an OAuth client)."),d(null);return}d(k)}catch{x("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),d(null)}},w.onerror=()=>{x("Failed to read file."),d(null)},w.readAsText(j)},[]);async function p(){if(x(null),!n.trim()){x("Property ID is required.");return}if(!i){x("Please upload a service account key file.");return}u(!0);try{await Jl(t,{propertyId:n.trim(),keyJson:i});try{await Ao(t)}catch{}s()}catch(y){x(y instanceof Error?y.message:"Failed to connect GA4")}finally{u(!1)}}return e.jsxs(xe,{className:"surface-card p-6",children:[e.jsx("h3",{className:"text-base font-semibold text-primary mb-1",children:"Connect Google Analytics 4"}),e.jsx("p",{className:"text-sm text-secondary mb-5",children:"Connect a GA4 property to see traffic data for this project. You'll need a service account key file from Google Cloud Console."}),m&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative",children:m}),e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{htmlFor:"ga4-property-id",className:"block text-xs font-medium text-secondary mb-1.5",children:"GA4 Property ID"}),e.jsx("input",{id:"ga4-property-id",type:"text",placeholder:"e.g. 123456789",value:n,onChange:y=>a(y.target.value),className:"w-full rounded-lg bg-bg-elevated/60 border border-default px-3 py-2 text-sm text-strong placeholder-mono-600 focus:outline-none focus:ring-1 focus:ring-mono-600"}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:"Find this in GA4 → Admin → Property Settings. It's a numeric ID, not the Measurement ID (G-XXXXXX)."})]}),e.jsxs("div",{className:"mb-5",children:[e.jsx("label",{className:"block text-xs font-medium text-secondary mb-1.5",children:"Service Account Key File"}),e.jsx("input",{ref:g,type:"file",accept:".json,application/json",onChange:h,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>g.current?.click(),className:"flex items-center gap-2 w-full rounded-lg bg-bg-elevated/60 border border-default border-dashed px-4 py-3 text-sm text-secondary hover:border-mono-600 hover:text-neutral transition-colors cursor-pointer",children:[e.jsx(rm,{className:"w-4 h-4 shrink-0"}),r?e.jsx("span",{className:"text-strong truncate",children:r}):e.jsx("span",{children:"Upload .json key file"})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Download from Google Cloud Console → IAM & Admin → Service Accounts → Keys → Add Key → JSON. The service account must have ",e.jsx("span",{className:"text-secondary",children:"Viewer"})," access on the GA4 property."]})]}),e.jsx(A,{variant:"default",size:"sm",disabled:c||!n.trim()||!i,onClick:Ee(p),children:c?"Connecting & syncing…":"Connect GA4"})]})}function ss({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 sl={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function Va({value:t,label:s,subtitle:n,tone:a}){return e.jsxs("div",{className:"rounded-lg bg-surface border border-default px-5 py-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:s}),e.jsx("p",{className:`text-2xl font-bold tabular-nums ${sl[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function us({value:t,label:s,hint:n,tone:a,tooltip:r}){return e.jsxs("div",{className:"rounded-lg border border-default bg-bg/40 px-4 py-3 flex flex-col",children:[e.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1 flex items-center gap-1",children:[s,r&&e.jsx(Me,{text:r})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${sl[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function kh({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 nl={session:"Session",first_user:"First Visit",manual_utm:"UTM"},al={session:"Detected via GA4 sessionSource (referrer or utm_source for this session)",first_user:"Detected via GA4 firstUserSource (referrer from the user's first-ever visit)",manual_utm:"Detected via GA4 sessionManualSource (explicit utm_source parameter for the session)"};function Ah({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=nl[t.sourceDimension]??t.sourceDimension,r=al[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 Ph({row:t}){const s=nl[t.sourceDimension]??t.sourceDimension,n=al[t.sourceDimension]??"";return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"max-w-[400px] py-1.5 text-neutral",children:e.jsx(xa,{value:t.landingPage,className:"whitespace-nowrap"})}),e.jsx("td",{className:"py-1.5 text-strong max-w-[220px] truncate",title:t.source,children:t.source}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:n,children:s})}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.sessions.toLocaleString()})]})}function Rh({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=t.channelGroup==="Paid Social"?"Paid":"Organic",r=Sn(t.source),o=Sn(t.medium);return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 pr-3 text-strong truncate",title:t.source,children:r}),e.jsx("td",{className:"py-1.5 pr-3 text-muted truncate",title:t.medium,children:o}),e.jsx("td",{className:"py-1.5 pr-3",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:`GA4 channel group: ${t.channelGroup}`,children:a})}),e.jsx("td",{className:"py-1.5 text-right text-info-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[n,"%"]})]})}function Ih({sources:t,otherCount:s}){const n=[{key:wn,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===kn)n.push({key:kn,color:br,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const o=Sn(r);n.push({key:r,color:Fs[a%Fs.length]??br,label:Zo(o,32),tooltip:o})}}return e.jsx("div",{className:"mt-3 flex flex-wrap gap-x-4 gap-y-1.5 text-[11px] text-secondary",children:n.map(a=>e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 max-w-[260px]",title:a.tooltip,children:[e.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-sm shrink-0",style:{backgroundColor:a.color},"aria-hidden":"true"}),e.jsx("span",{className:"truncate",children:a.label})]},a.key))})}function $h(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 Th=["7d","30d","90d","all"],sa=500,Ci=[{key:"clicks",label:"Clicks",color:nt[1],format:t=>t.toLocaleString()},{key:"impressions",label:"Impressions",color:nt[4],format:t=>t.toLocaleString()},{key:"ctr",label:"CTR",color:Is.caution,format:t=>`${(t*100).toFixed(1)}%`},{key:"position",label:"Avg position",color:nt[2],inverted:!0,format:t=>t.toFixed(1)}],qs=25,Mh="canonry:google-oauth-complete",Lh=new Intl.NumberFormat(void 0,{maximumFractionDigits:1});function qh(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 c=t.prior[s],u=t.trailing[s];return c!==null&&u!==null&&c<=0&&u>0?`new in the last ${a}d`:c===null||c<=0?`no prior ${a}d to compare`:u===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%":`${Lh.format(o)}%`;return`${(n?r<0:r>0)?"↑":"↓"} ${i} vs prior ${a}d`}function Eh(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}`,d=`${r.startDate} to ${r.endDate}`,c=`Tile percentages compare these ${s} ${o} (${d}) with the ${s} ${o} before them (${i}).`;return n!=="split-window"?c:`${c} 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 ki(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function Ai(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 Pi(t){return t.isPending?"Processing":Number(t.errors??0)>0?"Errors":Number(t.warnings??0)>0?"Warnings":"Success"}function Dh({projectName:t,refreshNonce:s}){const n=Ns(),[a,r]=l.useState(!1),[o,i]=l.useState([]),[d,c]=l.useState([]),[u,m]=l.useState([]),[x,g]=l.useState(null),[h,p]=l.useState([]),[y,j]=l.useState([]),[w,k]=l.useState(null),[M,C]=l.useState(""),[f,v]=l.useState(""),[S,R]=l.useState("30"),[E,L]=l.useState(!1),[B,U]=l.useState("30d"),[T,N]=l.useState(["clicks","impressions"]),[D,J]=l.useState(!0),[G,Z]=l.useState(null),[de,se]=l.useState(0),[Q,$]=l.useState({startDate:"",endDate:"",query:"",page:""}),[ie,O]=l.useState(0),[_,X]=l.useState(!1),[ge,H]=l.useState(0),[ae,ue]=l.useState(!1),[Oe,Fe]=l.useState(""),[Pe,tt]=l.useState(!0),[it,ke]=l.useState(!1),[Xe,_e]=l.useState(!1),[Ve,He]=l.useState(!1),[Te,V]=l.useState(!1),[F,z]=l.useState(!1),[Ne,Ie]=l.useState(!1),[ee,We]=l.useState(null),[ht,Ze]=l.useState(!1),[ye,Ge]=l.useState(!1),[It,xt]=l.useState(null),[qe,Ye]=l.useState(null),[pt,St]=l.useState([]),[Ke,Le]=l.useState(new Set),[et,Ue]=l.useState({}),[Be,$t]=l.useState(new Set),[vt,Ft]=l.useState(""),[gt,Y]=l.useState(null),[Re,be]=l.useState(""),[je,Gt]=l.useState(!1),[ze,ft]=l.useState(!1),[Tt,ls]=l.useState(!1),[Mt,Kt]=l.useState(!1),[ot,cs]=l.useState("indexed"),[Ct,Ts]=l.useState(null),zt=!!(Q.query.trim()||Q.page.trim()||Ct),Zt=Ct!==null,Qt=l.useMemo(()=>{if(!Ct)return u;const{key:b,dir:K}=Ct;return[...u].sort((ce,pe)=>{const Qe=b===un.CTR?Number.isFinite(ce.ctr)?ce.ctr:0:ce[b],Je=b===un.CTR?Number.isFinite(pe.ctr)?pe.ctr:0:pe[b];return K==="asc"?Qe-Je:Je-Qe})},[u,Ct]),dt=xn({rows:Qt,pageSize:Cs}),ws=ae?dt.rows:Qt,Ht=xn({rows:(It??[]).filter(b=>b.path.toLowerCase().includes(vt.trim().toLowerCase())),pageSize:Cs}),[ct,ms]=l.useState([]),[jt,es]=l.useState(null),[hs,xs]=l.useState(1),Lt=l.useMemo(()=>{if(ct.length<2)return null;const b=ct[ct.length-1],K=ct[ct.length-2];return{indexed:b.indexed-K.indexed,notIndexed:b.notIndexed-K.notIndexed}},[ct]);l.useEffect(()=>{xs(1)},[ee,ot,jt]);const q=l.useMemo(()=>jt?(ee?.reasonGroups??[]).find(b=>b.reason===jt):void 0,[ee,jt]),ne=l.useMemo(()=>ee?ot==="indexed"?ee.indexed:ot==="deindexed"?ee.deindexed:ot==="notIndexed"?jt?q?.urls??[]:(ee.reasonGroups??[]).length===0?ee.notIndexed:[]:[]:[],[ee,ot,jt,q]),fe=Math.max(1,Math.ceil(ne.length/qs)),re=Math.min(Math.max(1,hs),fe),oe=(re-1)*qs,$e=l.useMemo(()=>ee?.indexed.slice(oe,oe+qs)??[],[ee,oe]),Wt=l.useMemo(()=>ee?.notIndexed.slice(oe,oe+qs)??[],[ee,oe]),yt=l.useMemo(()=>ee?.deindexed.slice(oe,oe+qs)??[],[ee,oe]),ps=l.useMemo(()=>(q?.urls??[]).slice(oe,oe+qs),[q,oe]),[P,me]=l.useState(!1),[st,Ae]=l.useState(null),[ut,ds]=l.useState(null),[_t,Yt]=l.useState(null);function $a(b,K){const ce=jm(b),pe=$h(ce);pe?(ds(pe),Ae(null)):(ds(null),Ae(ce.message||K))}const kt=o.find(b=>b.connectionType==="gsc"),Ss=(kt?.scopes??[]).includes("https://www.googleapis.com/auth/webmasters"),gn=pt.length>0?pt:(It??[]).map(b=>b.path),Pn=gn.filter(b=>It?.some(K=>K.path===b&&K.isSitemapsIndex)).length,Jt=Pn===1?"Resubmit sitemap index":Pn>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",Ta=u.length>0||h.length>0||y.length>0,Rn=Xl(),In=Zl();async function Jn(b,K=!1){if(!b){c([]),C("");return}_e(!0);try{const{sites:ce}=await n.fetchQuery({...hc({client:W,path:{name:t}}),staleTime:K?0:Dt});c(ce),C(b.propertyId??ce[0]?.siteUrl??""),ds(null)}catch(ce){c([]),$a(ce,"Failed to load Search Console properties")}finally{_e(!1)}}async function tn(b){V(!0);const K=b??ie;try{const ce=zt?sa:Cs,pe=zt?0:K,Qe={limit:String(ce)};Q.startDate&&(Qe.startDate=Q.startDate),Q.endDate&&(Qe.endDate=Q.endDate),Q.query&&(Qe.query=Q.query),Q.page&&(Qe.page=Q.page),pe>0&&(Qe.offset=String(pe)),B&&B!=="all"&&!Q.startDate&&(Qe.window=B);const Je=await n.fetchQuery({...sc({client:W,path:{name:t},query:Qe}),staleTime:Dt}),at=Je.rows;zt?(X(!1),m(at),H(at.length),ue(!0)):(X(pe+at.length<Je.totalMatching),m(at),H(0),ue(!1))}catch(ce){m([]),X(!1),H(0),Ae(ce instanceof Error?ce.message:"Failed to load GSC performance data")}finally{V(!1)}}async function I(){try{const b={};Q.startDate&&(b.startDate=Q.startDate),Q.endDate&&(b.endDate=Q.endDate),B&&B!=="all"&&!Q.startDate&&(b.window=B);const K=await n.fetchQuery({...tc({client:W,path:{name:t},query:b}),staleTime:Dt});g(K)}catch{g(null)}}async function he(b=!1){z(!0);try{const K=Oe.trim()||void 0,ce={limit:"20"};K&&(ce.url=K);const[pe,Qe]=await Promise.all([n.fetchQuery({...uc({client:W,path:{name:t},query:ce}),staleTime:b?0:Dt}),n.fetchQuery({...mc({client:W,path:{name:t}}),staleTime:b?0:Dt})]);p(pe),j(Qe)}catch(K){p([]),j([]),Ae(K instanceof Error?K.message:"Failed to load GSC inspection history")}finally{z(!1)}}async function Ce(b=!1){Ze(!0);try{const[K,ce]=await Promise.all([n.fetchQuery({...rc({client:W,path:{name:t}}),staleTime:b?0:Dt}),n.fetchQuery({...ic({client:W,path:{name:t}}),staleTime:b?0:Dt}).catch(()=>[])]);We(K),ms(ce)}catch(K){We(null),ms([]),Ae(K instanceof Error?K.message:"Failed to load coverage data")}finally{Ze(!1)}}async function Ut(b){me(!0),Ae(null);try{const K=await si(t,{urls:b}),{succeeded:ce,failed:pe,total:Qe}=K.summary;Se({title:"Indexing requested",detail:pe===0?`${ce} URL${ce!==1?"s":""} submitted for indexing.`:`${ce}/${Qe} submitted successfully, ${pe} failed.`,tone:pe===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(K){Ae(K instanceof Error?K.message:"Failed to request indexing")}finally{me(!1)}}async function gs(){me(!0),Ae(null);try{const b=await si(t,{urls:[],allUnindexed:!0}),{succeeded:K,failed:ce,total:pe}=b.summary;Se({title:"Indexing requested",detail:ce===0?`${K} unindexed URL${K!==1?"s":""} submitted for indexing.`:`${K}/${pe} submitted successfully, ${ce} failed.`,tone:ce===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(b){Ae(b instanceof Error?b.message:"Failed to request indexing")}finally{me(!1)}}async function Ma(){Ge(!0),Ae(null);try{const b=await qa(t);n.setQueryData(oc({client:W,path:{name:t}}),b),xt(b.sitemaps),Ye(b.summary),St(b.preferredSubmissionUrls),Le(new Set),Ue({}),b.sitemaps.length===0&&Yt("No sitemaps found in this GSC property. Submit one here to start Google processing it.")}catch(b){Ae(b instanceof Error?b.message:"Failed to list sitemaps")}finally{Ge(!1)}}async function $l(b){const K=Ke.has(b);if(Le(ce=>{const pe=new Set(ce);return K?pe.delete(b):pe.add(b),pe}),!(K||et[b])){$t(ce=>new Set(ce).add(b));try{const ce=await qa(t,b);Ue(pe=>({...pe,[b]:ce.sitemaps}))}catch(ce){Ae(ce instanceof Error?ce.message:"Failed to load sitemap files")}finally{$t(ce=>{const pe=new Set(ce);return pe.delete(b),pe})}}}async function fn(b){if(!Ss||b.length===0)return;const K=[...new Set(b)];ft(!0),Ae(null),Y({completed:0,total:K.length});let ce=0,pe=0,Qe=0,Je=null;try{for(let wt=0;wt<K.length;wt+=50){const rt=K.slice(wt,wt+50);try{const ve=await lc(t,rt);ce+=ve.summary.accepted,pe+=ve.summary.failed,Qe+=rt.length,Y({completed:Qe,total:K.length})}catch(ve){Qe+=rt.length;const Ms=rt.length,$n=K.length-Qe,Xn=ve instanceof Error?ve.message:"The batch request failed",Ls=`${ce} accepted, ${pe} failed, ${Ms} unconfirmed, ${$n} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;Je=`Sitemap submission stopped after a batch request failed. ${Ls} ${Xn}`,Ae(Je),Se({title:"Sitemap resubmission partially completed",detail:Ls,tone:"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"});return}}const at=K.length;Se({title:pe===0?"Sitemap submitted to Google":"Some sitemap submissions need attention",detail:pe===0?"Google accepted the sitemap submission/refetch request; indexing is not guaranteed.":`Google accepted ${ce}/${at} sitemap submissions; ${pe} failed. Indexing is not guaranteed.`,tone:pe===0?"positive":"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"}),be("")}catch(at){Ae(at instanceof Error?at.message:"Failed to submit sitemap to Google")}finally{ft(!1),Y(null),await Ma(),Je&&Ae(Je)}}async function Tl(){ft(!0);const b=It??[];try{const K=b.filter(pe=>pe.isSitemapsIndex),ce=[];for(let pe=0;pe<K.length;pe+=4)(await Promise.all(K.slice(pe,pe+4).map(async Je=>{const at=et[Je.path];if(at)return at;const wt=await qa(t,Je.path);return Ue(rt=>({...rt,[Je.path]:wt.sitemaps})),wt.sitemaps}))).forEach((Je,at)=>{ce.push(...Je.length>0?Je.map(wt=>wt.path):[K[pe+at].path])});await fn([...b.filter(pe=>!pe.isSitemapsIndex).map(pe=>pe.path),...ce])}catch(K){Ae(K instanceof Error?K.message:"Failed to load sitemap files"),ft(!1)}}async function Hr(b){Gt(!0),Ae(null);try{await cc(t,"gsc",b),await Nt(n,"google"),i(K=>K.map(ce=>ce.connectionType==="gsc"?{...ce,sitemapUrl:b}:ce)),Se({title:"Default sitemap updated",detail:b,tone:"positive",dedupeKey:`gsc:sitemap-default:${t}`,dedupeMode:"replace"})}catch(K){Ae(K instanceof Error?K.message:"Failed to set the default sitemap")}finally{Gt(!1)}}async function Wr(b){try{await In.mutateAsync({projectName:t,projectLabel:t,opts:b?{sitemapUrl:b}:void 0})}catch{}}async function Yr(){tt(!0),Ae(null);try{const[b,K]=await Promise.all([Po().catch(()=>null),n.fetchQuery({...$r({client:W,path:{name:t}}),staleTime:Dt}).catch(()=>[])]);r(!!b?.google?.configured),i(K);const ce=K.find(pe=>pe.connectionType==="gsc");await Promise.all([Jn(ce),tn(),I(),he(),Ce(),ce?.propertyId?Ma():Promise.resolve()])}finally{tt(!1)}}l.useEffect(()=>{Yr()},[t,s]),l.useEffect(()=>{O(0),Z(null),$(b=>b.startDate||b.endDate?{...b,startDate:"",endDate:""}:b),se(b=>b+1),I()},[B]);const Jr=l.useRef(!1);l.useEffect(()=>{if(!Jr.current){Jr.current=!0;return}O(0),dt.setPage(1),tn(0)},[de]);function La(b){const K=G===b?null:b;Z(K),$(ce=>({...ce,startDate:K??"",endDate:K??""})),se(ce=>ce+1)}const Xr=l.useRef(!1);l.useEffect(()=>{if(!Xr.current){Xr.current=!0;return}O(0),tn(0)},[Zt]);async function Zr(){if(!a){Ae("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}ke(!0),Ae(null),Yt(null);try{let b=function(ve){if(ve.source!==pe||ve.origin!==Qe||!ve.data||typeof ve.data!="object")return;const Ms=ve.data;Ms.type!==Mh||Ms.connectionType!=="gsc"||rt(!0)};const{authUrl:K,redirectUri:ce}=await ac(t,"gsc");if(!K.startsWith("https://accounts.google.com/")){Ae("Unexpected OAuth redirect URL. Please try again.");return}const pe=window.open(K,"_blank","width=600,height=700");if(!pe){window.location.assign(K);return}const Qe=ce?new URL(ce).origin:window.location.origin;let Je=!1,at=null;const wt=()=>{at!==null&&window.clearInterval(at),window.removeEventListener("message",b)},rt=async ve=>{if(!Je){Je=!0,wt(),Yt(ve?"Google connected. Refreshing access…":"Refreshing Google connection…");try{await Nt(n,"google"),await Yr()}finally{Yt(null)}}};window.addEventListener("message",b),Yt("Finish the Google consent flow in the popup. This page will refresh automatically."),at=window.setInterval(()=>{pe.closed&&rt(!1)},1e3)}catch(b){Ae(b instanceof Error?b.message:"Failed to start OAuth flow")}finally{ke(!1)}}async function Ml(){Ae(null),Yt(null);try{await nc(t,"gsc"),await Nt(n,"google"),i(b=>b.filter(K=>K.connectionType!=="gsc")),c([]),C("")}catch(b){Ae(b instanceof Error?b.message:"Failed to disconnect")}}async function Ll(){if(M){He(!0),Ae(null);try{await xc(t,"gsc",M),await Nt(n,"google"),i(b=>b.map(K=>K.connectionType==="gsc"?{...K,propertyId:M}:K)),Se({title:"GSC property updated",detail:`${t} is now linked to ${M}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(b){Ae(b instanceof Error?b.message:"Failed to save GSC property")}finally{He(!1)}}}async function ql(){Ae(null),Yt(null);try{await Rn.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(S,10)||void 0,full:E||void 0}}),await Nt(n,"gsc")}catch{}}async function ei(){if(f.trim()){Ie(!0),Ae(null),Yt(null);try{const b=await dc(t,f.trim());await Nt(n,"gsc"),k(b),v(""),await he()}catch(b){Ae(b instanceof Error?b.message:"Failed to inspect URL")}finally{Ie(!1)}}}return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search Console"}),e.jsx("h2",{children:"Google Search Console"})]})}),ut&&e.jsx("div",{className:"mb-3 rounded-lg border border-caution-800/40 bg-caution-950/20 px-3 py-2.5 text-sm text-caution-200",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-caution-100",children:ut.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:ut.message}),(Os(ut.enableUrl)||Os(ut.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[Os(ut.enableUrl)&&e.jsx("a",{href:Os(ut.enableUrl),target:"_blank",rel:"noopener noreferrer",className:"font-medium text-caution-100 underline decoration-caution-500/50 underline-offset-2 hover:text-caution-50",children:"Enable Search Console API ↗"}),Os(ut.indexingApiUrl)&&e.jsx("a",{href:Os(ut.indexingApiUrl),target:"_blank",rel:"noopener noreferrer",className:"font-medium text-caution-100 underline decoration-caution-500/50 underline-offset-2 hover:text-caution-50",children:"Enable Indexing API ↗"})]})]}),e.jsx("button",{type:"button",className:"text-caution-400 hover:text-caution-200",onClick:()=>ds(null),children:"×"})]})}),st&&e.jsxs("div",{className:"mb-3 rounded-lg border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:[st,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>Ae(null),children:"×"})]}),_t&&e.jsxs("div",{className:"mb-3 rounded-lg border border-positive-800/40 bg-positive-950/20 px-3 py-2 text-sm text-positive",children:[_t,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>Yt(null),children:"×"})]}),Pe?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[kt?e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 px-1 text-xs text-muted",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-positive-500"}),e.jsx("span",{className:"text-neutral",children:"Authorized"})]}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsx("code",{className:"text-secondary",children:kt.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Coverage measured"," ",ee?.lastInspectedAt?Bt(ee.lastInspectedAt):"never"]}),e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:Ee(Ml),children:"Disconnect"})]}):e.jsxs(xe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(le,{tone:a?"caution":"negative",children:a?"Ready to connect":"App credentials missing"})]}),e.jsxs("div",{className:"mt-3 rounded-lg border border-default bg-surface px-4 py-5",children:[e.jsx("p",{className:"text-sm text-neutral",children:a?"Generate a Google OAuth link for this project and have the client sign in with a Google account that already has access to the correct Search Console property.":"Set Google OAuth client credentials first. Once configured, you can generate a consent link for this project domain."}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[a?e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:it,onClick:Ee(Zr),children:it?"Opening…":"Connect Google Search Console"}):e.jsx(A,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(js,{to:"/settings",children:"Open Settings"})}),!a&&e.jsx("p",{className:"text-xs text-muted",children:"The same Google OAuth app credentials are shared across all projects."})]})]})]}),(kt||Ta)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs(xe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Performance"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Search performance"}),e.jsx(Me,{text:`${Eh(x?.periodComparison)} The optional trend line shows the fitted direction. Click any day to filter the table below to that date. Query and page filters match case-insensitive substrings and run on Apply filters. Filtering and sorting examine up to ${sa.toLocaleString()} matching rows while the table shows ${Cs} per page.`})]}),x?.window?.startDate&&x.window.endDate&&e.jsxs("p",{className:"text-xs text-muted",children:[x.window.startDate," to ",x.window.endDate,(x.window.daysSinceLatestData??0)>0&&` · latest data ${x.window.daysSinceLatestData} day${x.window.daysSinceLatestData===1?"":"s"} ago`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ra,{windows:Th,value:B,onChange:b=>{U(b),O(0),dt.setPage(1)},label:"Search Console time period",formatOption:b=>b==="all"?"All":b}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:Te,onClick:()=>{O(0),dt.setPage(1),tn(0),I()},children:Te?"Loading…":"Apply filters"})]})]}),x&&x.daily.length>0&&(()=>{const{totals:b,daily:K,trends:ce,periodComparison:pe}=x,Je=Ci.filter(ve=>T.includes(ve.key)).map(ve=>({dataKey:ve.key,label:ve.label,color:ve.color,axisId:ve.key,inverted:ve.inverted,formatValue:ve.format,trend:D?ce?.[ve.key]??null:null})),at=ve=>b[ve]??null,wt=new Map(K.map(ve=>[ve.date,ve])),rt=K.length===0?[]:km(K[0].date,K[K.length-1].date).map(ve=>wt.get(ve)??{date:ve});return e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:Ci.map(ve=>{const Ms=T.includes(ve.key),$n=at(ve.key),Xn=$n===null;return e.jsxs("button",{type:"button","aria-pressed":Ms,disabled:Xn,className:`rounded-md border px-3 py-2 text-left transition-colors ${Ms?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${Xn?"cursor-not-allowed opacity-50":""}`,onClick:()=>{N(Ls=>Ls.includes(ve.key)?Ls.length===1?Ls:Ls.filter(El=>El!==ve.key):[...Ls,ve.key])},children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2 w-2 rounded-full",style:{backgroundColor:Ms?ve.color:"transparent",border:`1px solid ${ve.color}`}}),e.jsx("span",{className:"text-xs text-secondary",children:ve.label})]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:$n===null?"—":ve.format($n)}),e.jsx("span",{className:"block text-[11px] tabular-nums text-muted",children:qh(pe,ve.key,ve.inverted)})]},ve.key)})}),e.jsx("div",{className:"mt-2 flex items-center justify-end",children:e.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5 text-xs text-secondary",children:[e.jsx("input",{type:"checkbox",className:"accent-mono-400",checked:D,onChange:ve=>J(ve.target.checked)}),"Trend line"]})}),e.jsx("div",{className:"mt-1",children:e.jsx(_o,{data:rt,xKey:"date",series:Je,xTickFormatter:pn,labelFormatter:Ot,onSelectX:La,selectedX:G})}),e.jsx("div",{role:"group","aria-label":"Filter the table to a single day",children:K.map(ve=>e.jsxs("button",{type:"button",className:"sr-only focus:not-sr-only focus:inline-block focus:rounded focus:border focus:border-strong focus:bg-surface-active focus:px-2 focus:py-1 focus:text-xs focus:text-strong","aria-pressed":G===ve.date,onClick:()=>La(ve.date),children:[Ot(ve.date),": ",ve.clicks," clicks, ",ve.impressions," impressions"]},ve.date))}),G&&e.jsxs("div",{className:"mt-1 flex items-center gap-2 text-xs",children:[e.jsxs("span",{className:"text-secondary",children:["Table showing ",Ot(G)]}),e.jsxs("button",{type:"button",className:"text-link hover:underline",onClick:()=>La(G),children:["Show all ",b.days," days"]})]}),b.position!==null&&(b.positionDays??b.days)<b.days&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position covers ",b.positionDays," of ",b.days," days. The rest have no property-level position recorded."]}),(b.position===null||b.position===void 0)&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position needs a property-level sync. Run ",e.jsx("code",{children:"canonry google sync"})," to record it."]})]})})(),e.jsxs("div",{className:"mt-3 grid gap-2 lg:grid-cols-4",children:[e.jsx("input",{className:"rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"date","aria-label":"Start date",title:"Start date (inclusive). Leave blank to use the window above.",value:Q.startDate,onChange:b=>$(K=>({...K,startDate:b.target.value}))}),e.jsx("input",{className:"rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"date","aria-label":"End date",title:"End date (inclusive).",value:Q.endDate,onChange:b=>$(K=>({...K,endDate:b.target.value}))}),e.jsx(Bs,{value:Q.query,onChange:b=>$(K=>({...K,query:b})),label:"Filter search queries",placeholder:"Contains query…"}),e.jsx(Bs,{value:Q.page,onChange:b=>$(K=>({...K,page:b})),label:"Filter page URLs",placeholder:"Contains page URL…"})]}),u.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Date"}),e.jsx("th",{className:"text-left",children:"Query"}),e.jsx("th",{className:"text-left",children:"Page"}),Object.values(un).map(b=>e.jsx("th",{className:"text-right","aria-sort":Ct?.key===b?Ct.dir==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"w-full cursor-pointer select-none text-right hover:text-strong focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-400 rounded px-1 -mx-1",onClick:()=>{dt.setPage(1),Ts(K=>K?.key===b?K.dir==="desc"?{key:b,dir:"asc"}:null:{key:b,dir:"desc"})},children:[ec[b],Ct?.key===b?Ct.dir==="desc"?" ↓":" ↑":""]})},b))]})}),e.jsx("tbody",{children:ws.map((b,K)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:b.date}),e.jsx("td",{className:"max-w-xs truncate text-strong",children:b.query}),e.jsx("td",{className:"max-w-xs text-secondary",children:e.jsx(xa,{value:b.page})}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:b.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:b.impressions.toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[(Number.isFinite(b.ctr)?b.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:b.position.toFixed(1)})]},`${b.date}:${b.query}:${b.page}:${K}`))})]})}),e.jsx(Rs,{page:ae?dt.page:Math.floor(ie/Cs)+1,pageSize:Cs,visibleRows:ws.length,totalRows:ae?ge:void 0,hasNextPage:ae?void 0:_,disabled:Te,itemLabel:ae?"matches":"rows",onPageChange:b=>{if(ae){dt.setPage(b);return}const K=(b-1)*Cs;O(K),tn(K)}}),ae&&ge>=sa?e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Results are capped at ",sa.toLocaleString(),"; narrow the filters to search beyond this set."]}):null]}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No performance rows match the current filters yet."})]}),e.jsxs(xe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Coverage"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Index coverage"}),e.jsx(Me,{text:"Google's Indexing API is intended for eligible JobPosting and BroadcastEvent pages. Sitemap resubmission is the general-site bulk path."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[ee&&ee.notIndexed.length>0&&e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:P,onClick:()=>{gs()},children:P?"Requesting…":`Request indexing (${ee.notIndexed.length})`}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:ht,onClick:()=>{Ce(!0)},children:ht?"Loading…":"Reload saved coverage"})]})]}),ee&&ee.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const b=ee.summary.indexed+ee.summary.notIndexed,K=b>0?ee.summary.indexed/b:0,ce=b>0?ee.summary.notIndexed/b:0,pe=54,Qe=2*Math.PI*pe,Je=Qe*(1-K),at=Qe*ce,wt=Qe*K;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative h-48 w-48",children:[e.jsxs("svg",{viewBox:"0 0 128 128",className:"h-full w-full","aria-hidden":"true",children:[e.jsx("circle",{cx:"64",cy:"64",r:pe,fill:"none",stroke:os.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:pe,fill:"none",stroke:Is.positiveDeep,strokeWidth:"14",strokeDasharray:Qe,strokeDashoffset:Je,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),ee.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:pe,fill:"none",stroke:os.textFaint,strokeWidth:"14",strokeDasharray:`${at} ${Qe-at}`,strokeDashoffset:-wt,transform:"rotate(-90 64 64)",style:{transition:"stroke-dasharray 0.6s ease, stroke-dashoffset 0.6s ease"}})]}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[e.jsxs("span",{className:"text-3xl font-bold tabular-nums text-primary",children:[(K*100).toFixed(0),"%"]}),e.jsx("span",{className:"text-xs uppercase tracking-widest text-muted mt-0.5",children:"Indexed"})]})]}),e.jsxs("div",{className:"mt-4 flex items-center justify-center gap-8",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-positive-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:ee.summary.indexed.toLocaleString()}),e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:"Indexed"})]})]}),e.jsx("div",{className:"h-8 w-px bg-mono-800"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-mono-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:ee.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:["Not indexed",(ee.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-faint",children:["· ",(ee.reasonGroups??[]).length," ",(ee.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),ee.summary.deindexed>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-8 w-px bg-mono-800"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-negative-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:ee.summary.deindexed.toLocaleString()}),e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:"Deindexed"})]})]})]})]})]})})()}),e.jsx("div",{className:"mt-3 flex border-b border-default",role:"tablist","aria-label":"Coverage status",children:["indexed","notIndexed","deindexed"].map(b=>{const K=b==="indexed"?ee.indexed.length:b==="notIndexed"?ee.notIndexed.length:ee.deindexed.length,ce=b==="indexed"?"Indexed":b==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",role:"tab","aria-selected":ot===b,className:`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${ot===b?"border-accent text-heading":"border-transparent text-secondary hover:border-mono-600 hover:text-strong"}`,onClick:()=>{cs(b),es(null)},children:[ce," (",K,")"]},b)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[ot==="indexed"&&ee.indexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Verdict"}),e.jsx("th",{className:"text-left",children:"Last Crawl"}),e.jsx("th",{className:"text-left",children:"Mobile"})]})}),e.jsx("tbody",{children:$e.map(b=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:b.url}),e.jsx("td",{className:"text-secondary",children:b.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:b.crawlTime?b.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:b.isMobileFriendly===!0?"Yes":b.isMobileFriendly===!1?"No":"—"})]},b.id))})]}),ot==="notIndexed"&&!jt&&(ee.reasonGroups??[]).length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Reason"}),e.jsx("th",{className:"text-right",children:"Pages"})]})}),e.jsx("tbody",{children:(ee.reasonGroups??[]).map(b=>e.jsxs("tr",{className:"cursor-pointer hover:bg-surface-inset-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>es(b.reason),onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(K.preventDefault(),es(b.reason))},tabIndex:0,role:"button","aria-label":`View ${b.reason} pages`,children:[e.jsx("td",{className:"text-strong",children:b.reason}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:b.count})]},b.reason))})]}),ot==="notIndexed"&&!jt&&(ee.reasonGroups??[]).length===0&&ee.notIndexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Indexing State"}),e.jsx("th",{className:"text-left",children:"Coverage"})]})}),e.jsx("tbody",{children:Wt.map(b=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:b.url}),e.jsx("td",{className:"text-secondary",children:b.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:b.coverageState??"Unknown"})]},b.id))})]}),ot==="notIndexed"&&jt&&(()=>{const b=(ee.reasonGroups??[]).find(K=>K.reason===jt);return b?e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsxs("button",{type:"button",className:"text-xs text-secondary hover:text-strong transition-colors",onClick:()=>es(null),children:["←"," Back to reasons"]})}),e.jsxs("div",{className:"mb-3 flex items-center justify-between rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:b.reason}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[b.count," affected page",b.count!==1?"s":""]})]}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:P,onClick:()=>{Ut(b.urls.map(K=>K.url))},children:P?"Requesting…":`Request indexing (${b.count})`})]}),e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Last Crawl"}),e.jsx("th",{className:"w-8"})]})}),e.jsx("tbody",{children:ps.map(K=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:K.url}),e.jsx("td",{className:"text-secondary",children:K.crawlTime?K.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-strong transition-colors",disabled:P,onClick:()=>{Ut([K.url])},title:"Request indexing",children:"Index"})})]},K.id))})]})]}):null})(),ot==="deindexed"&&ee.deindexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Previous"}),e.jsx("th",{className:"text-left",children:"Current"}),e.jsx("th",{className:"text-left",children:"Detected"})]})}),e.jsx("tbody",{children:yt.map((b,K)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:b.url}),e.jsx("td",{className:"text-secondary",children:b.previousState}),e.jsx("td",{className:"text-secondary",children:b.currentState}),e.jsx("td",{className:"text-secondary",children:b.transitionDate.split("T")[0]})]},`${b.url}-${K}`))})]}),(ot==="indexed"&&ee.indexed.length===0||ot==="notIndexed"&&!jt&&ee.notIndexed.length===0||ot==="deindexed"&&ee.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),e.jsx(Rs,{page:re,pageSize:qs,visibleRows:Math.min(qs,ne.length-oe),totalRows:ne.length,onPageChange:xs,itemLabel:"URLs"})]}),e.jsxs("div",{className:"mt-4 border-t border-default pt-3",children:[e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between text-left text-xs text-secondary hover:text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400","aria-expanded":Mt,onClick:()=>Kt(b=>!b),children:[e.jsx("span",{children:"Coverage history"}),e.jsx("span",{children:Mt?"Hide snapshots":ct.length>0?`View ${ct.length} snapshots`:"View history"})]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["Current: ",ee.summary.indexed.toLocaleString()," indexed, ",ee.summary.notIndexed.toLocaleString()," not indexed.",Lt&&e.jsxs(e.Fragment,{children:[" Since the last snapshot: ",Lt.indexed>=0?"+":"",Lt.indexed.toLocaleString()," indexed, ",Lt.notIndexed>=0?"+":"",Lt.notIndexed.toLocaleString()," not indexed."]})]}),Mt&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:ct.length>0?e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Date"}),e.jsx("th",{className:"text-right",children:"Indexed"}),e.jsx("th",{className:"text-right",children:"Not indexed"})]})}),e.jsx("tbody",{children:ct.map(b=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:b.date}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:b.indexed.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:b.notIndexed.toLocaleString()})]},b.date))})]}):e.jsx("p",{className:"text-sm text-muted",children:"No saved coverage snapshots yet."})})]})]}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:ht?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),e.jsxs(xe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Sitemaps"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Sitemap operations"}),e.jsx(Me,{text:"Submitting asks Google to refetch these sitemaps. Indexing is not guaranteed."})]})]}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:ye||!kt?.propertyId,onClick:()=>{Ma()},children:ye?"Reloading…":"Reload from Google"})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"url",placeholder:"https://example.com/sitemap.xml",value:Re,onChange:b=>be(b.target.value),onKeyDown:b=>b.key==="Enter"&&void fn([Re.trim()])}),e.jsx(A,{type:"button",size:"sm",disabled:!Ss||ze||!Re.trim(),onClick:()=>{fn([Re.trim()])},children:ze?"Submitting…":"Submit sitemap to Google"})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:!Ss||ze||gn.length===0,onClick:()=>{fn(gn)},children:ze?"Resubmitting…":Jt}),e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:!Ss||ze||!It?.length,onClick:()=>{Tl()},children:"Resubmit all files"}),qe&&e.jsxs("span",{className:"text-xs text-muted",children:["Top level: ",qe.indexes," index",qe.indexes===1?"":"es",", ",qe.files," file",qe.files===1?"":"s"]}),gt&&e.jsxs("span",{className:"text-xs text-secondary",children:["Submitting ",gt.completed,"/",gt.total]})]}),!Ss&&kt&&e.jsxs("div",{className:"mt-2 flex items-center gap-2 text-xs text-caution",children:[e.jsx("span",{children:"Reconnect to let Canonry submit sitemaps. Your current Canonry OAuth grant is read-only."}),e.jsx("button",{type:"button",className:"text-secondary underline hover:text-strong",onClick:Ee(Zr),children:"Reconnect"})]}),It&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:It.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Bs,{value:vt,onChange:b=>{Ft(b),Ht.setPage(1)},label:"Filter sitemaps",placeholder:"Filter sitemaps…"}),e.jsxs("table",{className:"data-table mt-3 w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Sitemap"}),e.jsx("th",{className:"text-left",children:"Type"}),e.jsx("th",{className:"text-left",children:"Google status"}),e.jsx("th",{className:"text-left",children:"Last submitted"}),e.jsx("th",{className:"text-left",children:"Last read"}),e.jsx("th",{className:"text-right",children:"Discovered URLs"}),e.jsx("th",{className:"text-left",children:"Issues"}),e.jsx("th",{className:"text-left",children:"Actions"})]})}),e.jsx("tbody",{children:Ht.rows.flatMap(b=>{const K=ki(b),ce=Ai(b),pe=Pi(b),Qe=et[b.path]??[],Je=Ke.has(b.path),at=e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs text-strong",children:e.jsx(xa,{value:b.path})}),e.jsx("td",{className:"text-secondary",children:b.isSitemapsIndex?e.jsx("button",{type:"button",className:"text-secondary hover:text-strong","aria-expanded":Je,"aria-label":`${Je?"Collapse":"Expand"} files in ${b.path}`,onClick:()=>{$l(b.path)},children:Be.has(b.path)?"Loading…":`${Je?"▾":"▸"} Index${et[b.path]?` (${Qe.length})`:""}`}):"Sitemap"}),e.jsx("td",{className:"text-secondary",children:pe}),e.jsx("td",{className:"text-secondary",children:b.lastSubmitted?b.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:b.lastDownloaded?b.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:K.toLocaleString()}),e.jsx("td",{className:"max-w-48 text-secondary",children:ce||"—"}),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:!Ss||ze,onClick:()=>{fn([b.path])},children:b.lastSubmitted?"Resubmit to Google":"Submit to Google"}),kt?.sitemapUrl===b.path?e.jsx("span",{className:"text-xs text-muted",title:"Used when no sitemap URL is provided for Canonry GSC operations.",children:"Default sitemap"}):e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:je,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{Hr(b.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:In.isPending,onClick:()=>{Wr(b.path)},children:"Inspect URLs"})]})})]},b.path),wt=b.isSitemapsIndex&&Je?Qe.map(rt=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs pl-6 text-secondary",children:e.jsx(xa,{value:rt.path})}),e.jsx("td",{className:"text-secondary",children:"File"}),e.jsx("td",{className:"text-secondary",children:Pi(rt)}),e.jsx("td",{className:"text-secondary",children:rt.lastSubmitted?rt.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:rt.lastDownloaded?rt.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:ki(rt).toLocaleString()}),e.jsx("td",{className:"text-secondary",children:Ai(rt)||"—"}),e.jsx("td",{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:!Ss||ze,onClick:()=>{fn([rt.path])},children:"Resubmit"}),kt?.sitemapUrl===rt.path?e.jsx("span",{className:"text-xs text-muted",title:"Used when no sitemap URL is provided for Canonry GSC operations.",children:"Default sitemap"}):e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:je,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{Hr(rt.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:In.isPending,onClick:()=>{Wr(rt.path)},children:"Inspect URLs"})]})})]},`${b.path}:${rt.path}`)):[];return[at,...wt]})})]}),e.jsx(Rs,{page:Ht.page,pageSize:Cs,visibleRows:Ht.rows.length,totalRows:Ht.totalRows,onPageChange:Ht.setPage,itemLabel:"sitemaps"})]}):e.jsx("p",{className:"text-sm text-muted",children:"No sitemaps found for this property."})})]}),e.jsxs(xe,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Inspection"}),e.jsx("h3",{children:"Inspect a URL"})]})}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"url",placeholder:"https://example.com/page",value:f,onChange:b=>v(b.target.value),onKeyDown:b=>b.key==="Enter"&&void ei()}),e.jsx(A,{type:"button",size:"sm",disabled:Ne||!kt?.propertyId||!f.trim(),onClick:Ee(ei),children:Ne?"Inspecting…":"Inspect URL"})]}),w&&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:w.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:w.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:ti(w.isMobileFriendly??null)})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Last crawl"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:Bt(w.crawlTime)})]})]})]}),e.jsxs(xe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Inspection log"})]}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:F,onClick:()=>{he(!0)},children:F?"Loading…":"Refresh history"})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",type:"text",placeholder:"Filter exact URL",value:Oe,onChange:b=>Fe(b.target.value)}),e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:F,onClick:()=>{he(!0)},children:"Apply filter"})]}),h.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:h.map(b=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:b.url}),e.jsx("td",{className:"text-neutral",children:b.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:b.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:b.coverageState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:ti(b.isMobileFriendly??null)}),e.jsx("td",{className:"text-secondary",children:Bt(b.inspectedAt)})]},b.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No inspection history yet."})]}),e.jsxs(xe,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Deindexed"}),e.jsx("h3",{children:"Recent indexing losses"})]})}),y.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Previous"}),e.jsx("th",{className:"text-left",children:"Current"}),e.jsx("th",{className:"text-left",children:"Changed at"})]})}),e.jsx("tbody",{children:y.map(b=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:b.url}),e.jsx("td",{className:"text-secondary",children:b.previousState??"Unknown"}),e.jsx("td",{className:"text-neutral",children:b.currentState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:Bt(b.transitionDate)})]},`${b.url}:${b.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No deindexed transitions recorded."})]})]}),kt&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-default pt-3",children:e.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 text-left",onClick:()=>ls(b=>!b),children:[e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",className:`h-4 w-4 text-muted transition-transform ${Tt?"rotate-90":""}`,"aria-hidden":"true",children:e.jsx("path",{fillRule:"evenodd",d:"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z",clipRule:"evenodd"})}),e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted",children:"Setup & Configuration"})]})}),Tt&&e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(xe,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Property"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{children:"Pick the Search Console property"}),e.jsx(Me,{text:"The selected property is used for future syncs and URL inspections for this project."})]})]})}),e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:`gsc-property-${t}`,children:"Property URL"}),e.jsx("select",{id:`gsc-property-${t}`,className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none",value:M,disabled:Xe||d.length===0,onChange:b=>C(b.target.value),children:d.length===0?e.jsx("option",{value:"",children:Xe?"Loading properties…":"No properties available"}):d.map(b=>e.jsxs("option",{value:b.siteUrl,children:[b.siteUrl," · ",b.permissionLevel]},b.siteUrl))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:Xe,onClick:()=>{Jn(kt,!0)},children:Xe?"Refreshing…":"Refresh properties"}),e.jsx(A,{type:"button",size:"sm",disabled:!M||Ve,onClick:Ee(Ll),children:Ve?"Saving…":"Save property"})]})]})]}),e.jsxs(xe,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Sync"}),e.jsx("h3",{children:"Import GSC performance data"})]})}),e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-[160px_1fr]",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:`gsc-sync-days-${t}`,children:"Days"}),e.jsx("input",{id:`gsc-sync-days-${t}`,type:"number",min:"1",className:"mt-0.5 w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",value:S,onChange:b=>R(b.target.value)})]}),e.jsxs("label",{className:"flex items-center gap-2 rounded border border-default bg-surface-subtle px-3 py-2 text-sm text-neutral",children:[e.jsx("input",{type:"checkbox",checked:E,onChange:b=>L(b.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(A,{type:"button",size:"sm",disabled:Rn.isPending||!kt.propertyId,onClick:Ee(ql),children:Rn.isPending?"Queueing…":"Queue sync"}),!kt.propertyId&&e.jsx("p",{className:"text-xs text-caution-400",children:"Select a Search Console property before queueing a sync."})]})]})]})})]})]})]})}const Oh=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function Fh({projectName:t,projectId:s}){const n=Ns(),[a,r]=l.useState(null),[o,i]=l.useState(null),[d,c]=l.useState(!1),u=we($r({client:W,path:{name:t}})),m=u.data?.find(H=>H.connectionType==="gbp"),x=!!m,g=a?{locationName:a}:void 0,h=we({...pc({client:W,path:{name:t}}),enabled:x}),p=we({...gc({client:W,path:{name:t},query:g}),enabled:x}),y=we({...fc({client:W,path:{name:t},query:g}),enabled:x}),j=we({...yc({client:W,path:{name:t},query:g}),enabled:x}),w=we({...bc({client:W,path:{name:t},query:g}),enabled:x}),k=we({...vc({client:W,path:{name:t},query:g}),enabled:x}),M=we({queryKey:["gbp-section-insights",t],queryFn:()=>jc(t),enabled:x});function C(){Nt(n,"gbp")}const f=Pt({...Nc(),onSuccess:H=>{Ro({id:H.runId,projectId:s,kind:Qs["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),Se({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),v=l.useSyncExternalStore(Io,ba,ba),S=Object.values(v.runs).some(H=>H.kind===Qs["gbp-sync"]&&H.projectId===s),R=f.isPending||S,E=Pt({...wc(),onSuccess:()=>C()});if(l.useEffect(()=>{if(!a||!h.data)return;const H=h.data.locations.filter(ae=>ae.selected);(H.length<=1||!H.some(ae=>ae.locationName===a))&&r(null)},[a,h.data]),l.useEffect(()=>{if(!o||!h.data)return;(a?[a]:h.data.locations.filter(ae=>ae.selected).map(ae=>ae.locationName)).includes(o)||i(null)},[o,h.data,a]),u.isLoading)return null;if(!m){const H=[{title:"Connect your Google account",command:`canonry gbp connect ${t}`,note:"Opens Google OAuth. Grant Business Profile (business.manage) access."},{title:"Choose the account",command:`canonry gbp accounts ${t}`,note:"Pick which Business Profile account this project tracks."},{title:"Select locations",command:`canonry gbp locations discover ${t}`,note:e.jsxs(e.Fragment,{children:["Then adopt the ones to sync: ",e.jsxs("code",{className:"rounded bg-bg-elevated/80 px-1 py-0.5 font-mono text-[11px] text-secondary",children:["canonry gbp locations select ",t," <location>"]})]})},{title:"Sync, and keep it fresh",command:`canonry gbp sync ${t}`,note:e.jsxs(e.Fragment,{children:["Schedule it: ",e.jsxs("code",{className:"rounded bg-bg-elevated/80 px-1 py-0.5 font-mono text-[11px] text-secondary",children:["canonry schedule set ",t," --kind gbp-sync --preset daily"]})]})}];return e.jsx("section",{className:"page-section-divider",children:e.jsxs(xe,{className:"surface-card",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Local presence"}),e.jsx("h2",{children:"Connect Google Business Profile"}),e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-muted",children:"Track local performance, search terms, place-action CTAs, and how your public Maps listing compares to the profile you control. Four steps from the CLI:"}),e.jsx("ol",{className:"mt-5 space-y-4",children:H.map((ae,ue)=>e.jsxs("li",{className:"grid grid-cols-[1.5rem_1fr] gap-x-3",children:[e.jsx("span",{className:"mt-0.5 inline-flex h-6 w-6 items-center justify-center rounded-full bg-mono-800 text-xs font-medium tabular-nums text-neutral","aria-hidden":"true",children:ue+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:ae.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:ae.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:ae.note})]})]},ae.title))})]})})}const L=p.data,B=h.data?.locations??[],U=B.filter(H=>H.selected),T=y.data?.keywords??[],N=j.data?.lodging??[],D=w.data?.placeActions??[],J=k.data?.places??[],G=B.length>0?B[0].accountName:m.domain,Z=a?B.find(H=>H.locationName===a)?.displayName??null:null,de=a?B.filter(H=>H.locationName===a):U,se=new Set(de.map(H=>H.locationName)),Q=N.filter(H=>se.has(H.locationName)),$=D.filter(H=>se.has(H.locationName)),ie=J.filter(H=>se.has(H.locationName)),O=new Set(U.map(H=>H.locationName)),_=a?T:T.filter(H=>O.has(H.locationName)),X=!a&&U.length>1,ge=(M.data??[]).filter(H=>!H.dismissed&&Oh.has(H.type)&&(!Z||H.query===Z||H.query===a||H.title.startsWith(Z)));return e.jsx("section",{className:"page-section-divider",children:e.jsxs(xe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Local presence"}),e.jsxs("h2",{className:"flex items-center gap-2",children:["Google Business Profile",e.jsx(Me,{text:"How AI answer engines and Maps surface this business: performance, search terms, and how your public listing compares to the profile you control."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(le,{tone:"positive",children:"Connected"}),!te()&&e.jsx(De,{type:"button",variant:"outline",size:"sm",disabled:R,onClick:()=>f.mutate({client:W,path:{name:t},body:{}}),children:R?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-muted",children:[G?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-secondary",children:G})," · "]}):null,h.data?`${h.data.totalSelected} of ${h.data.totalDiscovered} locations tracked`:"Loading locations…"]}),U.length>1&&e.jsxs("div",{className:"mb-5 max-w-xs",children:[e.jsx("label",{htmlFor:"local-presence-location",className:"mb-1 block text-sm font-medium text-secondary",children:"Location"}),e.jsxs("select",{id:"local-presence-location",value:a??"",onChange:H=>r(H.target.value||null),className:"w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-strong focus:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:[e.jsx("option",{value:"",children:"All locations"}),U.map(H=>e.jsx("option",{value:H.locationName,children:H.displayName},H.id))]})]}),U.length===0?e.jsxs("p",{className:"text-sm text-muted",children:["No locations are tracked yet. Open ",e.jsx("span",{className:"font-medium text-neutral",children:"Manage locations"})," below to track the one(s) for this business."]}):e.jsxs(e.Fragment,{children:[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(H=>e.jsx("div",{className:["insight-card",Xh(H.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:[H.title,H.recommendation?.reason&&e.jsx(Me,{text:H.recommendation.reason})]})},H.id))]}),L&&e.jsx(sx,{performance:L.performance,freshness:L.freshness,timeseries:L.timeseries}),L?.profileCompleteness&&e.jsx(Gh,{summary:L.profileCompleteness}),de.length>0&&e.jsx(Kh,{locations:de,lodging:Q,places:ie,placeActions:$,expandedLocation:o,onToggleExpanded:H=>{i(ae=>ae===H?null:H)}}),e.jsxs("div",{className:"mb-2",children:[e.jsxs("div",{className:"section-head section-head-inline mb-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search terms"}),y.data&&y.data.total>0&&e.jsxs("span",{className:"text-[11px] text-faint",children:[y.data.thresholdedPct,"% privacy-thresholded"]})]}),_.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"}),X&&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:_.slice(0,25).map(H=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-neutral",children:H.keyword}),X&&e.jsx("td",{className:"text-muted",children:B.find(ae=>ae.locationName===H.locationName)?.displayName??H.locationName}),e.jsx("td",{className:"text-right font-mono text-strong",children:H.valueCount!==null?H.valueCount.toLocaleString():e.jsxs("span",{className:"text-muted",title:"Privacy floor — Google withheld the exact count",children:["<",H.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-faint",children:[H.periodStart,"–",H.periodEnd]})]},`${H.locationName}:${H.keyword}`))})]})]})]}),e.jsxs("div",{className:"mt-6 border-t border-default pt-4",children:[e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 text-xs font-medium text-secondary hover:text-strong",onClick:()=>c(H=>!H),"aria-expanded":d,children:[e.jsx("span",{"aria-hidden":"true",children:d?"▾":"▸"})," Manage locations (",B.length,")"]}),d&&e.jsx("div",{className:"mt-3",children:B.length===0?e.jsxs("p",{className:"text-sm text-muted",children:["No locations discovered. Run ",e.jsx("span",{className:"font-mono",children:"canonry gbp locations discover"}),"."]}):e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Location"}),e.jsx("th",{className:"text-left",children:"Address"}),e.jsx("th",{className:"text-left",children:"Status"}),!te()&&e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:B.map(H=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:H.displayName}),e.jsx("td",{className:"text-muted",children:H.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(le,{tone:H.selected?"positive":"neutral",children:H.selected?"Tracked":"Not tracked"})}),!te()&&e.jsx("td",{className:"text-right",children:e.jsx(De,{type:"button",variant:"outline",size:"sm",disabled:E.isPending,onClick:()=>E.mutate({client:W,path:{name:t,locationName:H.locationName},body:{selected:!H.selected}}),children:H.selected?"Untrack":"Track"})})]},H.id))})]})})]})]})})}function Gh({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:Mn(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:Mn(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:Mn(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:Mn(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:Mn(t.withSecondaryCategories,s,"caution")},{label:"Closed",value:String(t.permanentlyClosed+t.temporarilyClosed),detail:t.permanentlyClosed||t.temporarilyClosed?`${t.permanentlyClosed} permanent, ${t.temporarilyClosed} temporary`:"reported open",tone:t.permanentlyClosed>0?"negative":t.temporarilyClosed>0?"caution":"positive"}];return e.jsxs("div",{className:"mb-6 border-y border-default py-3",children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Owner profile · Business Information"}),e.jsx(Me,{text:"Counts selected locations where Google Business Information returned the owner-authored field. A missing value means it was not returned by this API response, not that every Google surface is empty."})]}),e.jsx("div",{className:"grid gap-x-5 gap-y-3 sm:grid-cols-2 lg:grid-cols-3",children:n.map(a=>e.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_auto] items-baseline gap-3",children:[e.jsx("span",{className:"text-xs text-muted",children:a.label}),e.jsx("span",{className:`font-mono text-sm tabular-nums ${Jh(a.tone)}`,children:a.value}),a.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-faint",children:a.detail})]},a.label))})]})}function Kh({locations:t,lodging:s,places:n,placeActions:a,expandedLocation:r,onToggleExpanded:o}){const i=new Map(s.map(u=>[u.locationName,u])),d=new Map(n.map(u=>[u.locationName,u])),c=new Map;for(const u of a){const m=c.get(u.locationName)??[];m.push(u),c.set(u.locationName,m)}return e.jsxs("div",{className:"mb-6",children:[e.jsxs("div",{className:"section-head section-head-inline mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Source evidence"}),e.jsx(Me,{text:te()?"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest sync, not that every Google product lacks the information.":"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest Canonry sync, not that every Google product lacks the information."})]}),e.jsxs("span",{className:"text-[11px] text-faint",children:[t.length," location",t.length===1?"":"s"]})]}),e.jsx("div",{className:"data-table-wrapper",children:e.jsxs("table",{className:"data-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"min-w-[14rem]",children:"Location"}),e.jsx("th",{className:"min-w-[15rem]",children:"Owner profile"}),e.jsx("th",{className:"min-w-[11rem]",children:"Hotel data"}),e.jsx("th",{className:"min-w-[11rem]",children:"Public Maps"}),e.jsx("th",{className:"min-w-[10rem]",children:"CTAs"}),e.jsx("th",{className:"text-right",children:"Detail"})]})}),e.jsx("tbody",{children:t.map(u=>{const m=i.get(u.locationName)??null,x=d.get(u.locationName)??null,g=c.get(u.locationName)??[],h=r===u.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:u.displayName}),e.jsx("p",{className:"mt-1 text-xs text-faint",children:u.primaryCategoryDisplayName??"Primary category not returned"}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[e.jsx(le,{tone:u.selected?"positive":"neutral",children:u.selected?"Tracked":"Not tracked"}),u.openStatus&&u.openStatus!=="OPEN"&&e.jsx(le,{tone:u.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:rl(u.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(Uh,{location:u})}),e.jsx("td",{children:e.jsx(Bh,{lodging:m})}),e.jsx("td",{children:e.jsx(zh,{place:x,mapsUri:u.mapsUri})}),e.jsx("td",{children:e.jsx(Hh,{actions:g})}),e.jsx("td",{className:"text-right",children:e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>o(u.locationName),children:h?"Hide":"Details"})})]}),h&&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(Yh,{location:u,lodging:m,place:x,placeActions:g})})})]},u.id)})})]})})]})}function _h(t){return[{label:"Description",tone:cn(t.description)?"positive":"neutral",value:cn(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:cn(t.primaryPhone)?"positive":"neutral",value:cn(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:cn(t.websiteUri)?"positive":"neutral",value:cn(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 Uh({location:t}){const s=_h(t);return e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>e.jsxs(le,{tone:n.tone,children:[n.label," ",n.value]},n.label))})}function Bh({lodging:t}){return e.jsx(Mr,{...Vh(t)})}function Vh(t){return t?t.populatedGroupCount===0?{tone:"neutral",label:"0 groups returned",detail:"Lodging API returned no readable groups; verify Hotel details."}:{tone:"positive",label:`${t.populatedGroupCount} group${t.populatedGroupCount===1?"":"s"} returned`,detail:"Owner lodging attributes."}:{tone:"neutral",label:"No Lodging API snapshot",detail:"Not returned for this scoped location."}}function zh({place:t,mapsUri:s}){return e.jsx(Mr,{...Qh(t,s)})}function Qh(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 Hh({actions:t}){return e.jsx(Mr,{...Wh(t)})}function Wh(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 Mr({tone:t,label:s,detail:n}){return e.jsxs("div",{children:[e.jsx(le,{tone:t,children:s}),e.jsx("p",{className:"mt-1.5 text-xs leading-5 text-faint",children:n})]})}function Yh({location:t,lodging:s,place:n,placeActions:a}){const r=s?ex(s.attributes):[];return e.jsxs("div",{className:"grid gap-5 text-xs lg:grid-cols-3",children:[e.jsxs(za,{title:"Owner profile · Business Information",children:[e.jsx(qt,{label:"Primary category",value:t.primaryCategoryDisplayName??"Not returned"}),e.jsx(qt,{label:"Secondary categories",value:t.additionalCategories.length>0?t.additionalCategories.join(", "):"Not returned"}),e.jsx(qt,{label:"Description",value:cn(t.description)?t.description:"Not returned"}),e.jsx(qt,{label:"Hours",value:t.regularHours?"Returned by Google":"Not returned"}),e.jsx(qt,{label:"Service area",value:t.serviceArea?"Returned by Google":"Not returned"}),e.jsx(qt,{label:"Phone",value:t.primaryPhone??"Not returned"}),e.jsx(qt,{label:"Website",value:t.websiteUri??"Not returned"}),e.jsx(qt,{label:"Open status",value:rl(t.openStatus)}),e.jsx(qt,{label:"Opening date",value:t.openingDate??"Not returned"})]}),e.jsx(za,{title:"Hotel data · Lodging API",children:s?e.jsxs(e.Fragment,{children:[e.jsx(qt,{label:"Last checked",value:Ri(s.syncedAt)}),e.jsx(qt,{label:"Groups returned",value:String(s.populatedGroupCount)}),e.jsx(qt,{label:"Populated groups",value:r.length>0?r.join(", "):"None returned"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Lodging API snapshot was stored for this location."})}),e.jsxs(za,{title:"Public listing + CTAs",children:[n?e.jsxs(e.Fragment,{children:[e.jsx(qt,{label:"Places tier",value:n.tier}),e.jsx(qt,{label:"Last checked",value:Ri(n.syncedAt)}),e.jsx(qt,{label:"Public signals",value:n.amenities.length>0?n.amenities.join(", "):"No supported signals detected"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Places Details snapshot was stored for this location."}),t.mapsUri&&e.jsx("a",{href:t.mapsUri,target:"_blank",rel:"noopener noreferrer",className:"inline-block text-muted hover:text-neutral",children:"View on Google Maps →"}),e.jsx("div",{className:"mt-3 border-t border-default pt-3",children:a.length===0?e.jsx("p",{className:"leading-5 text-muted",children:"No placeActionLinks returned."}):e.jsx("div",{className:"grid gap-2",children:a.map(o=>e.jsxs("div",{className:"grid gap-0.5",children:[e.jsxs("span",{className:"font-medium text-neutral",children:[Sa(o.placeActionType),o.isPreferred?" · preferred":""]}),e.jsxs("span",{className:"text-faint",children:[Sa(o.providerType),o.uri?` · ${Zh(o.uri)}`:""]})]},o.placeActionLinkName))})})]})]})}function za({title:t,children:s}){return e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-[11px] font-semibold uppercase tracking-[0.14em] text-muted",children:t}),e.jsx("div",{className:"grid gap-2",children:s})]})}function qt({label:t,value:s}){return e.jsxs("div",{className:"grid grid-cols-[7.25rem_minmax(0,1fr)] gap-3",children:[e.jsx("span",{className:"text-faint",children:t}),e.jsx("span",{className:"min-w-0 break-words text-secondary",children:s})]})}function Mn(t,s,n){return t===s?"positive":t===0?n:"caution"}function Jh(t){switch(t){case"positive":return"text-positive";case"caution":return"text-caution";case"negative":return"text-negative";case"neutral":return"text-neutral"}}function Xh(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function cn(t){return typeof t=="string"&&t.trim().length>0}function rl(t){return t?Sa(t):"Not returned"}function Sa(t){return t?t.toLowerCase().split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"Unknown"}function Zh(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function Ri(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function ex(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&tx(n)).map(([s])=>Sa(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function tx(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function sx({performance:t,freshness:s,timeseries:n}){const a=t.totals,r=Sc.filter(p=>(a[p]??0)>0),o=Cc.filter(p=>(a[p]??0)>0),i=Object.keys(a).filter(p=>(a[p]??0)>0&&kc(p)==="other").sort((p,y)=>(a[y]??0)-(a[p]??0)),d=Object.keys(a).filter(p=>(a[p]??0)===0).sort(),c=n.map(p=>{const y={date:p.date};for(const[j,w]of Object.entries(p.metrics))y[j]=w;return y}),u=n.find(p=>p.pending)?.date,m=n.length>0?n[n.length-1].date:void 0,x=c.length>0,g=s.dataThroughDate?`Data through ${Ot(s.dataThroughDate)}${s.pendingDays>0?` · ${s.pendingDays}d pending`:""}`:null,h=[...r,...i];return e.jsxs("div",{className:"mb-6 grid gap-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Profile actions · daily"}),g&&e.jsx("span",{className:"text-[11px] text-muted",children:g})]}),!x||r.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No profile action activity yet — run a sync."}):e.jsxs(e.Fragment,{children:[e.jsx(Ii,{data:c,metrics:r,kind:"line",firstPending:u,lastDate:m}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-x-5 gap-y-1",children:h.map(p=>e.jsxs("span",{className:"text-sm text-secondary",children:[va(p)," ",e.jsx("span",{className:"font-mono text-heading",children:(a[p]??0).toLocaleString()})]},p))})]})]}),x&&o.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(Ii,{data:c,metrics:o,kind:"area",firstPending:u,lastDate:m})]}),d.length>0&&e.jsxs("p",{className:"text-xs text-faint",children:["Not active: ",d.map(p=>va(p)).join(", ")]})]})}function Ii({data:t,metrics:s,kind:n,firstPending:a,lastDate:r}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(Ys,{width:"100%",height:"100%",children:e.jsxs(Js,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Vn,{stroke:Bn,vertical:!1}),e.jsx(Xs,{dataKey:"date",tick:Rt,tickLine:!1,axisLine:{stroke:is},tickFormatter:pn,minTickGap:24}),e.jsx(Zs,{tick:Rt,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(en,{...Xt,labelFormatter:Ot,formatter:(o,i)=>[typeof o=="number"?o.toLocaleString():String(o??0),va(String(i??""))]}),e.jsx(wa,{wrapperStyle:{fontSize:11,color:os.text},formatter:o=>va(o)}),a&&r&&e.jsx(xr,{x1:a,x2:r,fill:os.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:os.textDim,fontSize:10}}),s.map((o,i)=>n==="line"?e.jsx(Ps,{type:"monotone",dataKey:o,stroke:nt[i%nt.length],strokeWidth:2,dot:!1,isAnimationActive:!1},o):e.jsx(Gs,{type:"monotone",dataKey:o,stackId:"reach",stroke:nt[i%nt.length],fill:nt[i%nt.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},o))]})})})}function nx(t){return Uo($s(String(t)))}function ax(t){return Vs($s(String(t)))}function Qa({children:t,label:s="More info",placement:n="top",className:a}){const r=l.useId(),[o,i]=l.useState(!1);return e.jsxs("span",{className:`relative inline-flex ${a??""}`,children:[e.jsx("button",{type:"button","aria-label":s,"aria-describedby":o?r:void 0,className:"inline-flex h-4 w-4 items-center justify-center rounded-full text-muted hover:text-strong focus:text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),onFocus:()=>i(!0),onBlur:()=>i(!1),children:e.jsx(cm,{className:"h-3.5 w-3.5","aria-hidden":!0})}),o&&e.jsx("span",{id:r,role:"tooltip",className:`absolute z-50 w-64 rounded border border-strong bg-bg-elevated px-3 py-2 text-xs font-normal leading-relaxed text-strong shadow-lg ${n==="top"?"bottom-full mb-2":"top-full mt-2"} left-1/2 -translate-x-1/2 whitespace-normal`,children:t})]})}const na=Cs;function yn(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function Ha(t){return t.toLocaleString()}function rx(t){const s=Number(t);return Number.isFinite(s)?`${(s*100).toFixed(1)}%`:"—"}function ix(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 ox(t){const s=t.filter(n=>n.kind===Qs["backlink-extract"]&&!$o(n.status));return s.length===0?null:s.reduce((n,a)=>n.createdAt>a.createdAt?n:a)}function lx(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 cx({projectName:t}){const[s,n]=l.useState(null),[a,r]=l.useState(null),[o,i]=l.useState([]),[d,c]=l.useState(null),[u,m]=l.useState(null),[x,g]=l.useState(null),[h,p]=l.useState(Date.now()),[y,j]=l.useState(0),[w,k]=l.useState(!0),[M,C]=l.useState(!1),[f,v]=l.useState(null),S=l.useCallback(async()=>{k(!0),v(null);try{const[G,Z,de,se,Q]=await Promise.all([Ac().catch(()=>null),Pc(t,{excludeCrawlers:!0}).catch(()=>null),Rc(t,{limit:na,offset:y,excludeCrawlers:!0}).catch(ie=>{if(ie instanceof hn&&ie.code==="NOT_FOUND")return null;throw ie}),Ic(t).catch(()=>[]),$c(t).catch(()=>[])]);c(G),n(Z),r(de),i(se);const $=ox(Q);m($)}catch(G){v(G instanceof Error?G.message:"Failed to load backlinks")}finally{k(!1)}},[t,y]);l.useEffect(()=>{S()},[S]),l.useEffect(()=>{if(!u)return;const G=u.id;let Z=!1;const de=async()=>{try{const Q=await hr(G);if(Z)return;$o(Q.status)?(m(null),g(Q),await S()):m($=>$?.id===Q.id?{...$,...Q}:$)}catch{}},se=window.setInterval(()=>{de()},3e3);return()=>{Z=!0,window.clearInterval(se)}},[u,S]),l.useEffect(()=>{if(!u)return;const G=window.setInterval(()=>p(Date.now()),1e3);return()=>window.clearInterval(G)},[u]),l.useEffect(()=>{if(!x||x.status==="failed")return;const G=window.setTimeout(()=>g(null),1e4);return()=>window.clearTimeout(G)},[x]);async function R(){C(!0),v(null);try{const G=await Mc(t);m(G)}catch(G){G instanceof hn&&G.code==="MISSING_DEPENDENCY"?v("DuckDB is not installed. Visit the Backlinks admin page to install it."):v(G instanceof Error?G.message:"Failed to trigger extract")}finally{C(!1)}}const E=l.useMemo(()=>o.slice().sort((G,Z)=>G.queriedAt.localeCompare(Z.queriedAt)).map(G=>({date:G.queriedAt,linkingDomains:G.totalLinkingDomains})),[o]),L=a?.rows??[],B=a?.total??0,U=s?.excludedLinkingDomains??0,T=Math.floor(y/na)+1;return l.useEffect(()=>{y>0&&y>=B&&j(0)},[y,B]),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"})]})}),f&&e.jsx(xe,{className:"surface-card p-4 mb-4 border-negative-800/60",children:e.jsx("p",{className:"text-sm text-negative",children:f})}),u&&e.jsx(xe,{className:"surface-card p-4 mb-4 border-info-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(im,{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(le,{tone:"neutral",children:u.status}),e.jsxs("span",{className:"text-sm text-secondary tabular-nums",children:[lx(u.startedAt??null,u.createdAt)," elapsed · refreshing every 3s"]}),e.jsxs("span",{className:"sr-only",children:["now=",h]})]}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Refreshing this project from the current Common Crawl release."})]})]})}),x&&!u&&e.jsx(xe,{className:`surface-card p-4 mb-4 ${x.status==="failed"?"border-negative-800/60":"border-positive-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[x.status==="failed"?e.jsx("span",{className:"h-5 w-5 shrink-0 mt-0.5 text-negative-400 text-lg leading-none","aria-hidden":!0,children:"!"}):e.jsx(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 ${x.status==="failed"?"text-negative":"text-positive"}`,children:x.status==="failed"?"Extract failed":"Extract complete"}),x.error?e.jsx("p",{className:"text-sm text-secondary mt-1",children:Tc(x.error)}):x.status!=="failed"?e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),N()]});function N(){return w?e.jsx(xe,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading backlinks…"})}):D()}function D(){const G=s!==null&&s.totalLinkingDomains>0,Z=x?.status==="failed",de=s!==null&&s.totalLinkingDomains===0&&!Z,se=d?.status==="ready",Q=d?.status==="failed",$=d&&(d.status==="downloading"||d.status==="querying"||d.status==="queued");return G?J(e.jsxs(e.Fragment,{children:[!te()&&e.jsxs(e.Fragment,{children:[e.jsxs(A,{type:"button",variant:"outline",size:"sm",disabled:M||u!==null,onClick:Ee(R),children:[e.jsx(Oo,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":M?"Queuing…":"Re-run extract"]}),e.jsx(Qa,{label:"About re-running",children:"Re-queries the current release for this project without downloading it again."})]}),!te()&&e.jsx(A,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:yn("/backlinks"),children:"Open admin"})})]})):e.jsx(xe,{className:"surface-card p-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-bg-elevated text-secondary",children:e.jsx(lm,{className:"h-5 w-5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1",children:[!d&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No release sync yet"}),e.jsx("p",{className:"text-sm text-muted mt-1",children:"Run a workspace release sync to populate backlinks for every project in this workspace."}),!te()&&e.jsx("div",{className:"mt-4",children:e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:yn("/backlinks"),children:"Set up backlinks"})})})]}),$&&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 (",d.status,d.phaseDetail?` — ${d.phaseDetail}`:"","). Backlinks will appear here once it finishes."]}),!te()&&e.jsx("div",{className:"mt-4",children:e.jsx(A,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:yn("/backlinks"),children:"View sync status"})})})]}),Q&&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:d.error??"The workspace release sync failed. Retry from the Backlinks admin page."}),!te()&&e.jsx("div",{className:"mt-4",children:e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:yn("/backlinks"),children:"Go to Backlinks admin"})})})]}),se&&!$&&!de&&!Z&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No backlinks yet for this project"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["Release ",e.jsx("code",{className:"text-neutral",children:d.release})," is ready. Run an extract for this project."]}),!te()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(A,{type:"button",size:"sm",disabled:M||u!==null,onClick:Ee(R),children:[e.jsx(Un,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":M?"Queuing…":"Run extract"]}),e.jsx(Qa,{label:"About extraction",children:"Queries the current release for this project without downloading it again."})]})]}),Z&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Last extract failed"}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"See the error above, then check the workspace source before retrying."}),!te()&&e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:yn("/backlinks"),children:"Go to Backlinks admin"})})})]}),de&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No referring domains found"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["The latest release found no referring domains for ",s.targetDomain,". Try a newer release or re-run this extract."]}),!te()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(A,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:yn("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(A,{type:"button",variant:"outline",size:"sm",disabled:M||u!==null,onClick:Ee(R),children:[e.jsx(Un,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),u?"Extract running…":M?"Queuing…":"Re-run extract"]}),e.jsxs(Qa,{label:"What does Re-run extract do?",children:[e.jsxs("span",{className:"block",children:["Re-queries the cached release for ",e.jsx("span",{className:"text-strong",children:s.targetDomain}),". Only useful if the cache files were incomplete last time."]}),e.jsx("span",{className:"mt-2 block text-secondary",children:"No re-download. ~5 min. If the release genuinely has no links for your domain, this won’t help — sync a different release instead."})]})]})]})]})]})})}function J(G){if(!s)return null;const Z="Linking hosts",de="linking hosts",se="release";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"gauge-row",children:[e.jsxs("div",{className:"metric-card",children:[e.jsx("p",{className:"metric-card-eyebrow",children:"Referring domains"}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:Ha(s.totalLinkingDomains)})}),e.jsxs("p",{className:"metric-card-sub",children:["unique domains linking to ",s.targetDomain]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("p",{className:"metric-card-eyebrow",children:["Total ",de]}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:Ha(s.totalHosts)})}),e.jsxs("p",{className:"metric-card-sub",children:["aggregate ",de," 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:rx(s.top10HostsShare)})}),e.jsxs("p",{className:"metric-card-sub",children:["share of ",de," 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"})," · ",se," ",e.jsx("code",{className:"text-secondary",children:s.release})," · queried ",ix(s.queriedAt),U>0&&e.jsxs(e.Fragment,{children:[" · ",U," excluded domain",U===1?"":"s"]})]}),E.length>=2&&e.jsxs(xe,{className:"surface-card p-4 mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Referring domains over time"}),e.jsx("div",{className:"h-40 mt-2",children:e.jsx(Ys,{width:"100%",height:"100%",children:e.jsxs(Js,{data:E,margin:{top:8,right:12,bottom:0,left:12},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"bl-gradient",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:nt[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:nt[0],stopOpacity:0})]})}),e.jsx(Xs,{dataKey:"date",tick:Rt,stroke:is,tickFormatter:nx}),e.jsx(Zs,{tick:Rt,stroke:is,allowDecimals:!1}),e.jsx(en,{contentStyle:Xt.contentStyle,labelStyle:Xt.labelStyle,itemStyle:Xt.itemStyle,labelFormatter:ax}),e.jsx(Gs,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:nt[0],fill:"url(#bl-gradient)",strokeWidth:2})]})})})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Top referring domains"}),e.jsx(xe,{className:"surface-card overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base text-left text-xs uppercase tracking-wide text-faint",children:[e.jsx("th",{className:"px-4 py-2 font-medium",children:"Domain"}),e.jsx("th",{className:"px-4 py-2 text-right font-medium",children:Z})]})}),e.jsxs("tbody",{children:[L.map(Q=>e.jsxs("tr",{className:"border-b border-mono-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-strong",children:Q.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-secondary tabular-nums",children:Ha(Q.numHosts)})]},Q.linkingDomain)),L.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-muted",colSpan:2,children:U>0&&B===0?`Every referring domain in this ${se} was a crawler/proxy host (${U} hidden).`:`No referring domains in this ${se}.`})})]})]})}),e.jsx(Rs,{page:T,pageSize:na,visibleRows:L.length,totalRows:B,onPageChange:Q=>j((Q-1)*na)})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:G})]})}}function dx({projectName:t}){const s=we({...Lc({client:W,path:{name:t}}),staleTime:To}),n=s.data??null,a=s.error;if(s.isLoading&&!n)return null;if(a)return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsx("h2",{children:"Citation + answer-mention coverage"})]})}),e.jsx("p",{className:"text-sm text-negative-400",children:_n(a)})]});if(!n)return null;if(n.status==="no-data")return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsx("h2",{children:"Citation + answer-mention coverage"})]})}),e.jsx("p",{className:Vt()?"text-sm text-secondary":"text-sm text-muted",children:n.reason==="no-queries"?"Add queries to start tracking AI citations.":Vt()?Hs:"Run a sweep to see which engines cite this project."})]});const{providersCiting:r,providersMentioning:o,providersConfigured:i}=n.summary;return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsxs("h2",{className:"flex items-center gap-2",children:["Cited by ",r," of ",i," engines",e.jsx(Me,{text:"An engine is ‘citing’ when our domain appears in its grounding source list (the structured citation/search-result attribution it returns alongside the answer). Counts each configured engine that cites the project on at least one tracked query in the latest snapshot per (query × provider)."})]}),e.jsxs("p",{className:"text-base text-neutral flex items-center gap-2",children:["Mentioned in ",o," of ",i," engine answers",e.jsx(Me,{text:"An engine is ‘mentioning’ when our brand or domain appears inside the prose of the answer text — independent of whether it’s in the citation list. Models often name-drop from training without citing a fresh page."})]})]}),n.summary.latestRunAt&&e.jsxs("p",{className:"supporting-copy",children:["Latest run ",new Date(n.summary.latestRunAt).toLocaleString()]})]}),e.jsx(ux,{data:n}),e.jsx(mx,{data:n}),n.competitorGaps.length>0&&e.jsx(gx,{data:n})]})}function ux({data:t}){const{totalQueries:s,queriesCitedAndMentioned:n,queriesCitedOnly:a,queriesMentionedOnly:r,queriesInvisible:o}=t.summary;return e.jsxs("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4 mb-4",children:[e.jsx(aa,{label:"Cited + mentioned",value:`${n} / ${s}`,helper:"In sources AND named in answer",tone:n>0?"positive":"neutral"}),e.jsx(aa,{label:"Cited only",value:`${a} / ${s}`,helper:"In sources, not named in answer",tone:a>0?"positive-dim":"neutral"}),e.jsx(aa,{label:"Mentioned only",value:`${r} / ${s}`,helper:"Named in answer, no source link",tone:r>0?"caution":"neutral"}),e.jsx(aa,{label:"Invisible",value:`${o} / ${s}`,helper:"No engine cites or mentions",tone:o>0?"negative":"neutral"})]})}function aa({label:t,value:s,helper:n,tone:a}){const r=a==="positive"?"text-positive":a==="positive-dim"?"text-positive-400/70":a==="caution"?"text-caution":a==="negative"?"text-negative":"text-heading";return e.jsxs("div",{className:"rounded-md border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:t}),e.jsx("p",{className:`mt-1 text-2xl font-semibold tabular-nums ${r}`,children:s}),e.jsx("p",{className:"text-[11px] text-muted",children:n})]})}function mx({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(hx,{}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),s.map(n=>e.jsx("th",{className:"text-center",children:e.jsx(Cn,{provider:n})},n)),e.jsx("th",{className:"text-right",children:"Cite"}),e.jsx("th",{className:"text-right",children:"Ment"})]})}),e.jsx("tbody",{children:t.byQuery.map(n=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:n.query}),s.map(a=>{const r=n.providers.find(o=>o.provider===a);return e.jsx("td",{className:"text-center",children:r==null?e.jsx(Fo,{className:"inline h-3.5 w-3.5 text-mono-700","aria-label":"no data"}):e.jsx(xx,{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 hx(){return e.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-3 text-[11px] text-muted",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Nn,{active:!0,tone:"cited"}),e.jsx("span",{children:"cited (in sources)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Nn,{active:!0,tone:"mentioned"}),e.jsx("span",{children:"mentioned (in answer)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Nn,{active:!1,tone:"cited"}),e.jsx(Nn,{active:!1,tone:"mentioned"}),e.jsx("span",{children:"neither"})]})]})}function xx({provider:t}){const s=px(t);return e.jsxs("span",{className:"inline-flex items-center justify-center gap-1",title:s,children:[e.jsx(Nn,{active:t.cited,tone:"cited"}),e.jsx(Nn,{active:t.mentioned,tone:"mentioned"})]})}function px(t){return t.cited&&t.mentioned?"Cited in sources and mentioned in answer":t.cited?"Cited in sources, not mentioned in answer":t.mentioned?"Mentioned in answer, not in sources":"Not cited and not mentioned"}function Nn({active:t,tone:s}){if(!t)return e.jsx("span",{className:"inline-block h-2 w-2 rounded-full border border-strong bg-transparent","aria-hidden":"true"});const n=s==="cited"?"inline-block h-2 w-2 rounded-full bg-positive-400 shadow-[0_0_0_1px_rgba(16,185,129,0.25)]":"inline-block h-2 w-2 rounded-full bg-info-400 shadow-[0_0_0_1px_rgba(56,189,248,0.25)]";return e.jsx("span",{className:n,"aria-hidden":"true"})}function gx({data:t}){return e.jsxs("div",{className:"mt-4",children:[e.jsxs("h3",{className:"text-sm font-semibold text-strong mb-2 flex items-center gap-2",children:["Competitor gaps",e.jsx(Me,{text:"Queries where the project is not cited but a configured competitor is. Each row maps to one (query, engine) pair — the same query may surface for multiple engines."}),e.jsxs("span",{className:"text-[10px] font-normal uppercase tracking-wide text-muted",children:[t.competitorGaps.length," ",t.competitorGaps.length===1?"gap":"gaps"]})]}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Engine"}),e.jsx("th",{children:"Competitors cited"})]})}),e.jsx("tbody",{children:t.competitorGaps.map(s=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:s.query}),e.jsx("td",{children:e.jsx(Cn,{provider:s.provider})}),e.jsx("td",{className:"text-neutral",children:s.citingCompetitors.join(", ")})]},`${s.queryId}::${s.provider}`))})]})})]})}const Wn="__cited__",Yn="__mentioned__",rs="__mentionShare__";function il(t){const s=t,{dataStartDate:n,dataEndDate:a}=s;return typeof n!="string"||typeof a!="string"?null:{start:$s(n),end:$s(a),sweepCount:s.sweepCount??1}}function Ca(t){const s=il(t);if(!s)return"Sweep date unavailable";const n=Vs(s.start),a=Vs(s.end);return n===a?n:`${n} – ${a} · ${s.sweepCount} sweeps combined`}function fx(t){const s=il(t);return s?Uo(s.start):""}function An(t){return t.trim().toLowerCase()}function vr(t){return Math.round(t*1e3)/10}function jr(t){return t.byProvider??{}}function yx(t,s,n){const a=t.buckets.length>0,r=t.buckets.length===1;if(n==="overall"){const c=s==="cited"?Wn:Yn,u=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(x=>({date:x.startDate,[c]:vr(x[u])})),series:[c],hasData:a,singleBucket:r}}const o=s==="mentioned"?"mentionRate":"citationRate",i=[...new Set(t.buckets.flatMap(c=>Object.keys(jr(c))))].sort();return{rows:t.buckets.map(c=>{const u={date:c.startDate},m=jr(c);for(const x of i){const g=m[x];u[x]=g?vr(g[o]):null}return u}),series:i,hasData:a,singleBucket:r}}function ol(t){const s=t;return Object.hasOwn(s,"modelEvidenceByProvider")?s.modelEvidenceByProvider??{}:null}function bx(t){const s=t;return Object.hasOwn(s,"modelAttribution")?s.modelAttribution??{}:null}function vx(t){return t.servedModelAttribution??{}}function jx(t){return t.modelServiceMismatch??{}}function Nx(t){return t.modelPointerChanges??{}}function wx(t){return t.length>0?t.join(", "):null}function $i(t,s){const n=An(s);return Object.entries(t).find(([a])=>An(a)===n)?.[1]}function ks(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 Sx(t,s){for(let n=t.length-1;n>=0;n-=1){const a=t[n];if(!$i(jr(a),s))continue;const r=ol(a);return r?$i(r,s)??null:null}return null}function Cx(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 kx(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:Cx(s),beforeWindow:n.sort((a,r)=>a.event.observedAt.localeCompare(r.event.observedAt)||a.provider.localeCompare(r.provider))}}function Ax(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 Px(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 Rx(t){const s=t.buckets.map(a=>{const r=a.mentionShare;return{date:a.startDate,[rs]:r?.rate==null?null:vr(r.rate)}}),n=s.map(a=>a[rs]).filter(a=>typeof a=="number"&&Number.isFinite(a));return{rows:s,series:[rs],hasData:n.length>0,singleBucket:n.length===1}}function Ix(t,s,n){return s==="mentionShare"?Rx(t):yx(t,s,n)}function Ti(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 Mi(t){const[,s,n]=t.slice(0,10).split("-");return!s||!n?t:`${s}/${n}`}function Li(t){return t>0?`+${t}`:`${t}`}function $x(t){if(t.length===0)return null;if(t.length<=2)return`Query set changed: ${t.map(n=>`${Li(n.delta)} on ${Mi(n.date)}`).join(", ")}`;const s=[...t].sort((n,a)=>a.date.localeCompare(n.date))[0];return`Query set changed ${t.length} times (latest ${Li(s.delta)} on ${Mi(s.date)})`}const Tx=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],Ds={"non-brand":"Non-brand queries",branded:"Branded queries",unknown:"Unclassified queries"},Ks="min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",Nr=new Intl.NumberFormat("en",{style:"percent",maximumFractionDigits:1});function ll(t){return t.kind==="project"?"Whole site":t.kind==="group"?`${t.label} · Group`:t.kind==="market"?`${t.label} · Market`:t.label}function bs({value:t,unit:s}){return t.rate===null?e.jsx("span",{className:"text-sm text-secondary",children:t.reason==="not-applicable"?"Not applicable":"Not measured"}):e.jsxs("span",{className:"inline-flex flex-col gap-1",children:[e.jsx("strong",{className:"tabular-nums text-heading",children:Nr.format(t.rate)}),e.jsxs("span",{className:"text-sm tabular-nums text-secondary",children:[t.numerator," of ",t.denominator,s?` ${s}`:""]})]})}function Mx(t){const s=new Map;for(const n of t){const a=s.get(n.queryKey);a?a.rows.push(n):s.set(n.queryKey,{queryKey:n.queryKey,query:n.query,rows:[n]})}return[...s.values()]}function qi({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(dm,{size:16,"aria-hidden":"true"}):e.jsx(Fo,{size:16,"aria-hidden":"true"}),n?"Yes":"No"]})}return e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(bs,{value:t}),t.reason==="evidence-incomplete"?e.jsx(Me,{text:"The saved evidence is incomplete, so this result cannot be measured. It does not mean the answer had no citation."}):null]})}function Ei({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 Lx({group:t,advanced:s,targetLabels:n,onViewAnswers:a}){const r=t.rows[0],o=u=>JSON.stringify([...u.targetKeys].sort()),i=t.rows.every(u=>o(u)===o(r)),d=t.rows.every(u=>u.location===r.location),c=u=>u===null?"No location targeting":`Search location: ${u}`;return e.jsxs("tbody",{"data-query-key":t.queryKey,children:[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&&i?e.jsx(Ei,{targetKeys:r.targetKeys,labels:n}):null,d?e.jsx("span",{children:c(r.location)}):null]})]})}),t.rows.map(u=>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:vs(u.provider)}),e.jsx("span",{className:"block break-words text-sm text-secondary",children:u.model??"Model not recorded"}),s&&!i?e.jsx("div",{className:"mt-1 text-sm text-secondary",children:e.jsx(Ei,{targetKeys:u.targetKeys,labels:n})}):null,d?null:e.jsx("span",{className:"mt-1 block text-sm text-secondary",children:c(u.location)})]}),e.jsxs("td",{children:[e.jsx("span",{className:"measurement-result-mobile-label","aria-hidden":"true",children:"Mentioned"}),e.jsx(qi,{value:u.mentionCoverage,singleAnswer:u.answerCount===1})]}),e.jsxs("td",{children:[e.jsx("span",{className:"measurement-result-mobile-label","aria-hidden":"true",children:"Cited"}),e.jsx(qi,{value:u.citationCoverage,singleAnswer:u.answerCount===1})]}),e.jsx("td",{className:"measurement-result-action",children:e.jsxs(A,{variant:"ghost",className:"min-h-11","aria-label":`View answers for ${u.query} · ${u.provider}`,onClick:()=>a(u),children:[u.answerCount===1?"View answer":"View answers",e.jsx(Do,{size:16,"aria-hidden":"true"})]})})]},JSON.stringify([u.provider,u.model,u.location])))]})}function qx({population:t}){const s=l.useId();let n=0;const a=t.trend.map((c,u)=>(u>0&&c.continuity.state!=="comparable"&&(n+=1),{createdAt:Date.parse(c.createdAt),[`mentioned-${n}`]:c.mentionCoverage.rate,[`cited-${n}`]:c.citationCoverage.rate})),r=Array.from({length:n+1},(c,u)=>u),o=new Set(t.trend.slice(1).map(c=>c.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(c=>c.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 d=t.trend.some(c=>c.mentionCoverage.rate!==null||c.citationCoverage.rate!==null);return e.jsxs(e.Fragment,{children:[d?e.jsxs(e.Fragment,{children:[e.jsxs("ul",{"aria-label":"Trend legend",className:"flex gap-5 py-3 text-sm text-secondary",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{"aria-hidden":"true",className:"h-0.5 w-5",style:{backgroundColor:nt[1]}}),"Mentioned"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{"aria-hidden":"true",className:"h-0.5 w-5",style:{backgroundColor:Is.positive}}),"Cited"]})]}),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":`${Ds[t.queryClass]} mention and citation trend`,children:e.jsx(Ys,{width:"100%",height:"100%",children:e.jsxs(Js,{data:a,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Vn,{stroke:Bn,vertical:!1}),e.jsx(Xs,{dataKey:"createdAt",type:"number",scale:"time",domain:["dataMin","dataMax"],tick:Rt,tickLine:!1,axisLine:{stroke:is},tickFormatter:c=>new Date(Number(c)).toLocaleDateString(void 0,{month:"short",day:"numeric"}),minTickGap:24}),e.jsx(Zs,{domain:[0,1],tick:Rt,tickLine:!1,axisLine:!1,width:48,tickFormatter:c=>Nr.format(Number(c))}),e.jsx(en,{...Xt,formatter:c=>typeof c=="number"?Nr.format(c):"Not measured",labelFormatter:c=>new Date(Number(c)).toLocaleString()}),r.map(c=>e.jsxs(l.Fragment,{children:[e.jsx(Ps,{type:"linear",dataKey:`mentioned-${c}`,name:"Mentioned",stroke:nt[1],strokeWidth:2,connectNulls:!1,isAnimationActive:!1,dot:{r:3}}),e.jsx(Ps,{type:"linear",dataKey:`cited-${c}`,name:"Cited",stroke:Is.positive,strokeWidth:2,connectNulls:!1,isAnimationActive:!1,dot:{r:3}})]},c))]})})})]}):e.jsx("p",{className:"py-6 text-sm text-secondary",children:"No measured trend for this selection."}),e.jsxs("details",{className:"py-3 text-sm text-secondary",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3",children:"Trend data and comparability"}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"}),e.jsx("th",{children:"Comparison"})]})}),e.jsx("tbody",{children:t.trend.map(c=>e.jsxs("tr",{children:[e.jsx("td",{children:new Date(c.createdAt).toLocaleDateString()}),e.jsx("td",{children:e.jsx(bs,{value:c.mentionCoverage})}),e.jsx("td",{children:e.jsx(bs,{value:c.citationCoverage})}),e.jsx("td",{children:c.continuity.state.replaceAll("-"," ")})]},c.runId))})]})})]})]})}function wr(t,s){return s?t?.populations.find(n=>[...n.queries.items,...n.evidence.items].some(a=>a.queryKey===s)):void 0}function Lr(t,s,n,a){const r=t.selection.queryClass==="all"?n?.queryClass:t.selection.queryClass,o=t.populations.find(u=>u.queryClass===r);if(o)return o;const i=wr(a,s)??wr(t,s),d=t.populations.find(u=>u.queryClass===i?.queryClass);if(d)return d;const c=["non-brand","branded","unknown"].map(u=>t.populations.find(m=>m.queryClass===u));return c.find(u=>u&&(u.summary.queryCount>0||u.trend.some(m=>m.queryCount>0)))??c.find(u=>u!==void 0)??t.populations[0]}function Ex({report:t,onSelectionChange:s,queryClass:n=Lr(t).queryClass}){const[a,r]=l.useState(""),o=l.useRef(null),i=l.useRef(null),d=l.useId(),{selection:c,scopeOptions:u,filterOptions:m}=t,x=ll(c.scope),g=u.filter(p=>`${p.kind==="project"?"Whole site":p.label} ${p.kind}`.toLocaleLowerCase().includes(a.trim().toLocaleLowerCase()));l.useEffect(()=>{const p=y=>{o.current?.open&&y.target instanceof Node&&!o.current.contains(y.target)&&(o.current.open=!1)};return document.addEventListener("pointerdown",p),()=>document.removeEventListener("pointerdown",p)},[]);const h=(p,y,j,w)=>e.jsxs("label",{className:"min-w-0",children:[e.jsx("span",{className:"mb-1 block text-sm font-medium text-heading",children:p}),e.jsx("select",{"aria-label":p,className:Ks,value:j,onChange:k=>s({[y]:k.target.value||void 0,measurementQueryKey:void 0}),children:w.map(k=>e.jsx("option",{value:k.value,children:k.label},k.value))})]});return e.jsx("div",{className:"visibility-filter-container",children:e.jsxs("div",{className:"visibility-report-filters","data-has-scope":u.length>1,role:"group","aria-label":"Visibility filters",children:[u.length>1?e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{id:`${d}-label`,className:"mb-1 block text-sm font-medium text-heading",children:"Measurement scope"}),e.jsxs("details",{ref:o,className:"relative",onToggle:p=>{p.currentTarget.open&&(r(""),i.current?.focus())},onKeyDown:p=>{p.key==="Escape"&&(p.preventDefault(),p.currentTarget.open=!1,p.currentTarget.querySelector("summary")?.focus())},children:[e.jsxs("summary",{id:`${d}-value`,"aria-labelledby":`${d}-label ${d}-value`,className:`${Ks} visibility-scope-trigger`,children:[x,e.jsx(Ws,{size:16,"aria-hidden":"true",className:"shrink-0 text-secondary"})]}),e.jsxs("div",{className:"visibility-scope-menu",children:[e.jsx("input",{ref:i,type:"search","aria-label":"Search scopes",className:Ks,placeholder:"Search groups, markets, properties",value:a,onChange:p=>r(p.target.value)}),e.jsxs("div",{className:"mt-2 max-h-72 overflow-y-auto",children:[g.map(p=>e.jsxs("button",{className:"flex min-h-11 w-full items-center justify-between gap-3 rounded px-2 text-left text-sm text-primary hover:bg-surface-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400","aria-current":c.scope.kind===p.kind&&c.scope.id===p.id?"true":void 0,onClick:()=>{o.current&&(o.current.open=!1,o.current.querySelector("summary")?.focus()),s({measurementScope:p.kind,measurementScopeKey:p.kind==="project"?void 0:p.id})},children:[e.jsx("span",{className:"min-w-0 break-words",children:p.kind==="project"?"Whole site":p.label}),e.jsx("span",{className:"shrink-0 text-right text-xs text-secondary",children:p.kind==="group"?e.jsxs(e.Fragment,{children:["Group",e.jsxs("span",{className:"block",children:[p.targetCount," properties"]})]}):p.kind==="market"?e.jsxs(e.Fragment,{children:["Market",e.jsx("span",{className:"block",children:"query context"})]}):p.kind==="property"?"Property":`${p.targetCount} properties`})]},`${p.kind}:${p.id}`)),g.length===0?e.jsx("p",{className:"py-3 text-sm text-secondary",children:"No matching scopes."}):null]})]})]})]}):null,h("Query type","queryClass",n,[{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"},{value:"unknown",label:"Unclassified"}]),h("Answer engine","measurementProvider",c.provider??"",[{value:"",label:"All engines"},...m.providers.map(p=>({value:p,label:p}))]),h("Search location","measurementLocation",c.location.kind==="exact"?c.location.value:c.location.kind==="none"?"none":"",[{value:"",label:"All locations"},...m.locations.filter(p=>p.kind!=="all").map(p=>({value:p.kind==="exact"?p.value:"none",label:p.kind==="exact"?p.value:"No location"}))])]})})}function Dx({report:t,isRefreshing:s=!1,onSelectionChange:n,onManageQueries:a,onPage:r,onSearch:o,search:i="",queryKey:d,answerSelection:c,evidenceReport:u,isEvidenceLoading:m=!1,evidenceError:x,onRetryEvidence:g,onEvidencePage:h}){const p=l.useRef(null),y=l.useRef(void 0),j=Lr(t,d,c,u),w=u??t,k=w.populations.filter(T=>[...T.queries.items,...T.evidence.items].some(N=>N.queryKey===d)),M=c?[c.queryClass]:(k.length?k:m?[]:[j]).map(T=>T.queryClass),C=d?JSON.stringify([c??d,M]):void 0,f=l.useId();l.useEffect(()=>{if(!C){s||(y.current=void 0);return}if(y.current===C)return;const T=p.current?.querySelectorAll('[aria-label="Measured answers"]');if(T?.length){for(const N of T){const D=N.closest("details[data-query-results]");D&&(D.open=!0)}T[0].focus({preventScroll:!0}),T[0].scrollIntoView?.({block:"start"}),y.current=C}},[C,s]);const{selection:v,filterOptions:S}=t,R=v.measurement,E=ll(v.scope),L=new Map(t.scopeOptions.filter(T=>T.kind==="property").map(T=>[T.id,T.label])),B=T=>{const N=w.populations.find(D=>D.queryClass===T.queryClass)?.evidence;return{items:N?.items.filter(D=>D.queryKey===d&&(!c||D.provider===c.provider&&D.model===c.model&&D.location===c.location&&(c.runId===null||D.runId===c.runId)))??[],nextCursor:N?.nextCursor}},U=(T,N,D,J,G)=>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:`${f}-${N}`,className:"text-sm font-medium text-heading",children:T}),e.jsx(Me,{text:G})]}),e.jsx("select",{id:`${f}-${N}`,className:Ks,value:D,onChange:Z=>n({[N]:Z.target.value||void 0,measurementQueryKey:void 0}),children:J.map(Z=>e.jsx("option",{value:Z.value,children:Z.label},Z.value))})]});return e.jsxs("section",{ref:p,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(le,{tone:R.state==="measured"?"positive":"neutral",children:R.state==="measured"?"Complete":R.state==="partial"?"Partial":"Not measured"}),R.completedAt?e.jsx("span",{className:"text-sm text-secondary",children:new Date(R.completedAt).toLocaleString()}):null,R.awaitingSweep?e.jsxs("span",{role:"status",className:"inline-flex items-center gap-1 text-sm text-secondary",children:[e.jsxs("span",{children:[R.pendingAssignmentCount," query assignments pending across project"]}),e.jsx(Me,{text:`Measured under revision ${R.measuredRevision??"unavailable"}. Project has ${R.pendingAssignmentCount} assignments awaiting sweep. Existing results stay visible until those assignments are measured.`})]}):null]}),a?e.jsx(A,{variant:"outline",onClick:a,children:"Manage queries"}):null]}),v.provenance.kind==="legacy-simple"&&v.queryClass!=="unknown"&&v.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(A,{variant:"outline",onClick:()=>n({queryClass:"all",measurementQueryKey:void 0}),children:"View all saved results"})]}):null,e.jsx(Ex,{report:t,queryClass:j.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:Ks,value:v.time.from?.slice(0,10)??"",onChange:T=>n({measurementFrom:T.target.value?`${T.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:Ks,value:v.time.to?.slice(0,10)??"",onChange:T=>n({measurementTo:T.target.value?`${T.target.value}T23:59:59.999Z`:void 0})})]}),U("AI model","measurementModel",v.model??"",[{value:"",label:"All models"},...Array.from(new Set(S.models.filter(T=>!v.provider||T.provider===v.provider).map(T=>T.model))).map(T=>({value:T,label:T}))],"Filter by the AI model recorded with each answer. This does not change the model used by future sweeps."),U("Results from","measurementRunId",v.run.explicit?v.run.id??"":"",[{value:"",label:"Latest saved sweep"},...[...j.trend].reverse().map(T=>({value:T.runId,label:new Date(T.createdAt).toLocaleString()}))],"Choose a saved AI sweep to view its results. No new sweep starts.")]})]}),[j].map(T=>{const N=Mx(T.queries.items);return e.jsxs("section",{"aria-label":Ds[T.queryClass],className:"py-4",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("h2",{children:Ds[T.queryClass]}),e.jsx(Me,{text:T.queryClass==="non-brand"?"Queries that do not name the measured identity. Geography alone is not a brand.":T.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:v.mode==="advanced"&&v.scope.kind!=="property"?"Answers mentioning a property":"Mentioned answers"}),v.mode==="advanced"?e.jsx(Me,{text:"An answer counts when it mentions any assigned property. This does not mean every property was mentioned."}):null]}),e.jsx(bs,{value:T.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:v.mode==="advanced"&&v.scope.kind!=="property"?"Answers citing a property":"Cited answers"}),v.mode==="advanced"?e.jsx(Me,{text:"An answer counts when it cites a matching URL for any assigned property. This does not mean every property was cited."}):null]}),e.jsx(bs,{value:T.summary.citationCoverage,unit:"answers"})]}),v.mode==="advanced"&&v.scope.kind!=="property"?e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-sm text-secondary",children:"Properties mentioned"}),e.jsx(bs,{value:T.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:T.summary.queryCount})]})]}),e.jsx(qx,{population:T}),v.mode==="advanced"?e.jsxs("details",{className:"border-t border-default text-sm text-secondary","aria-label":`${Ds[T.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(([D,J])=>e.jsxs("div",{children:[e.jsx("strong",{className:"block tabular-nums text-heading",children:T.summary.outcomes[D]}),e.jsx("span",{className:"text-sm text-secondary",children:J}),D==="notMeasured"?e.jsx(Me,{text:"No eligible completed measurement for this selection. This is not the same as a measured answer with neither signal."}):null]},D))})]}):null,v.mode==="advanced"&&v.scope.kind!=="property"&&(T.breakdown.groups.length>0||T.breakdown.properties.length>0)?e.jsx(Ox,{population:T,scope:v.scope.kind,onSelectionChange:n},`${v.scope.kind}:${v.scope.id}`):null,e.jsxs("details",{className:"border-t border-default","data-query-results":T.queryClass,"aria-label":`${Ds[T.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:[T.queries.total," ",T.queries.total===1?"result":"results"," · ",E]})]}),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 ${Ds[T.queryClass]}`,placeholder:"Search queries",className:`${Ks} max-w-sm`,value:i,onChange:D=>o(D.target.value)}):null,e.jsx(Me,{text:v.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":`${Ds[T.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"})})]})}),N.map(D=>e.jsx(Lx,{group:D,advanced:v.mode==="advanced",targetLabels:L,onViewAnswers:J=>n({measurementQueryKey:J.queryKey,measurementAnswer:JSON.stringify({queryKey:J.queryKey,queryClass:T.queryClass,provider:J.provider,model:J.model,location:J.location,runId:v.run.id,revision:v.revision})})},D.queryKey))]})}),T.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:[N.length," ",N.length===1?"query":"queries"," · ",T.queries.items.length," ",T.queries.items.length===1?"engine result":"engine results"," shown of ",T.queries.total," results"]}),T.queries.nextCursor&&r?e.jsx(A,{variant:"outline",onClick:()=>r(T.queries.nextCursor),children:"Next queries"}):null,d&&M.includes(T.queryClass)?e.jsxs("section",{tabIndex:-1,className:"scroll-mt-6 border-t border-default py-5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400","aria-label":"Measured answers","aria-busy":m,children:[e.jsxs("div",{className:"section-head",children:[e.jsx("h3",{children:"Answers"}),e.jsx(A,{variant:"ghost",onClick:D=>{y.current=void 0,D.currentTarget.closest("details[data-query-results]")?.querySelector("summary")?.focus(),n({measurementQueryKey:void 0,measurementAnswer:void 0})},children:"Close answers"})]}),m?e.jsx("p",{role:"status",className:"py-4 text-sm text-secondary",children:"Loading saved answers…"}):x?e.jsxs("div",{role:"alert",className:"py-4 text-sm text-secondary",children:[e.jsxs("p",{children:["Saved answers unavailable: ",x]}),g?e.jsx(A,{variant:"outline",onClick:g,children:"Retry answers"}):null]}):e.jsxs(e.Fragment,{children:[B(T).items.map(D=>e.jsxs("article",{className:"border-b border-default py-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("strong",{className:"text-sm text-heading",children:D.provider}),D.model?e.jsx("span",{className:"text-sm text-secondary",children:D.model}):null,e.jsx("span",{className:"text-sm text-secondary",children:D.location??"No location"}),e.jsx("span",{className:"text-sm text-secondary",children:new Date(D.createdAt).toLocaleString()}),e.jsx(le,{tone:"neutral",children:D.mentioned===null?"Mention not checked":D.mentioned?"Mentioned":"Not mentioned"}),e.jsx(le,{tone:"neutral",children:D.cited===null?"Citation not checked":D.cited?"Cited":"Not cited"})]}),e.jsx("h4",{className:"mt-3 text-sm font-medium text-heading",children:D.query}),e.jsx("p",{className:"mt-3 max-w-prose whitespace-pre-wrap text-sm leading-6 text-primary",children:D.answerText??"Answer text unavailable."}),e.jsx("ul",{className:"mt-3 space-y-2",children:D.sources.map(J=>{const G=Os(J);return e.jsx("li",{className:"break-all text-sm",children:G?e.jsx("a",{href:G,target:"_blank",rel:"noreferrer",className:"text-link hover:underline",children:J}):e.jsx("span",{className:"text-secondary",children:J})},J)})})]},D.answerId)),B(T).items.length===0?e.jsx("p",{className:"py-4 text-sm text-secondary",children:B(T).nextCursor?"No matching answers on this page. Continue to the next answers.":"No matching saved answers on this page."}):null,B(T).nextCursor&&h?e.jsx(A,{variant:"outline",onClick:()=>h(B(T).nextCursor),children:"Next answers"}):null]})]}):null]})]}),e.jsxs("details",{className:"border-t border-default","aria-label":`${Ds[T.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:T.competitorAvailability.state==="unavailable"?"Not available":`${T.competitors.length} measured`})]}),e.jsxs("div",{className:"pb-5",children:[T.competitorAvailability.state==="unavailable"?e.jsx("p",{className:"text-sm text-secondary",children:"Competitor rates unavailable for this historical definition."}):T.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:T.competitors.map(D=>e.jsxs("tr",{children:[e.jsx("td",{children:D.domain}),e.jsx("td",{children:e.jsx(bs,{value:D.mentionCoverage})}),e.jsx("td",{children:e.jsx(bs,{value:D.citationCoverage})})]},D.domain))})]})}),T.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:T.observedCompetitors.map(D=>e.jsxs("li",{className:"flex items-center justify-between gap-4 py-3",children:[e.jsx("span",{children:D.name}),e.jsxs("span",{className:"tabular-nums text-secondary",children:[D.answerCount," ",D.answerCount===1?"answer":"answers"]})]},D.name))}),e.jsx("p",{className:"py-2 text-secondary",children:"Observed names, not additions to your tracked competitors."})]}):null]})]})]},T.queryClass)})]})}function Ox({population:t,scope:s,onSelectionChange:n}){const[a,r]=l.useState(()=>s==="project"&&t.breakdown.groups.length>0?"groups":"properties"),o=xn({rows:t.breakdown[a],getSearchText:i=>i.label});return e.jsxs("section",{className:"border-t border-default py-5","aria-label":"Scope breakdown",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[e.jsx("div",{className:"flex gap-2",children:["groups","properties"].map(i=>e.jsx(A,{variant:a===i?"secondary":"ghost",onClick:()=>{r(i),o.setPage(1)},children:i==="groups"?"Groups":"Properties"},i))}),e.jsx("input",{type:"search","aria-label":"Search breakdown",placeholder:"Search",value:o.query,onChange:i=>o.setQuery(i.target.value),className:`${Ks} max-w-sm`})]}),e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:a==="groups"?"Group":"Property"}),e.jsx("th",{children:"Queries"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"})]})}),e.jsx("tbody",{children:o.rows.map(i=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsx("button",{className:"min-h-11 text-left text-link hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>n({measurementScope:a==="groups"?"group":"property",measurementScopeKey:i.id}),children:i.label})}),e.jsx("td",{children:i.queryCount}),e.jsx("td",{children:e.jsx(bs,{value:i.mentionCoverage})}),e.jsx("td",{children:e.jsx(bs,{value:i.citationCoverage})})]},i.id))})]})}),o.rows.length===0?e.jsxs("p",{className:"py-3 text-sm text-secondary",children:["No ",a," match this search."]}):null,e.jsx(Rs,{page:o.page,pageSize:o.pageSize,visibleRows:o.rows.length,totalRows:o.totalRows,itemLabel:a,onPageChange:o.setPage})]})}function Fx({projectName:t,selection:s,onSelectionChange:n,onManageQueries:a,fallback:r,showUnmeasuredFallback:o=!1}){const[i,d]=l.useState(),[c,u]=l.useState(""),[m,x]=l.useState(),g={scope:s.measurementScope,scopeKey:s.measurementScopeKey,queryClass:s.queryClass,provider:s.provider,model:s.model,location:s.location,from:s.from,to:s.to,revision:s.revision,runId:s.measurementRunId},h=we({...ni({client:W,path:{name:t},query:{...g,limit:25,cursor:i,search:c||void 0}}),retry:!1,placeholderData:Ir}),p={...g,queryKey:s.queryKey,queryClass:s.answer?.queryClass??s.queryClass,provider:s.answer?.provider??s.provider,model:s.answer?s.answer.model??void 0:s.model,location:s.answer?s.answer.location??"none":s.location,runId:s.answer?.runId??h.data?.selection.run.id??s.measurementRunId,revision:s.answer?.revision??h.data?.selection.revision??s.revision,limit:50},y=JSON.stringify(p),j=we({...ni({client:W,path:{name:t},query:{...p,cursor:m?.selection===y?m.cursor:void 0}}),enabled:!!s.queryKey&&!!h.data&&!h.isPlaceholderData,retry:!1});return l.useEffect(()=>{s.queryClass!=="all"||!h.data||h.isPlaceholderData||h.data.selection.availability.state==="unsupported"||h.data.populations.length===0||s.queryKey&&!s.answer&&!wr(h.data,s.queryKey)&&!j.data||n({queryClass:Lr(h.data,s.queryKey,s.answer,j.data).queryClass,...s.queryKey?{measurementQueryKey:s.queryKey,measurementAnswer:s.answer?JSON.stringify(s.answer):void 0}:{}})},[s.queryClass,s.queryKey,s.answer,h.data,h.isPlaceholderData,j.data,n]),h.data?.selection.availability.state==="unsupported"?e.jsx(e.Fragment,{children:r}):o&&h.data?.selection.mode==="simple"&&h.data.selection.measurement.state==="not-measured"?e.jsx(e.Fragment,{children:r}):h.error?e.jsxs("section",{className:"page-section-divider",role:"alert",children:[e.jsx("h2",{children:"AI visibility unavailable"}),e.jsx("p",{className:"my-3 text-sm text-secondary",children:_n(h.error)}),e.jsx(A,{variant:"outline",onClick:()=>{d(void 0),h.refetch()},children:"Retry"})]}):h.data?e.jsx("div",{"aria-busy":h.isFetching,children:e.jsx(Dx,{report:h.data,isRefreshing:h.isFetching,queryKey:s.queryKey,answerSelection:s.answer,evidenceReport:j.data,isEvidenceLoading:j.isFetching||!!s.queryKey&&j.isPending,evidenceError:j.error?_n(j.error):void 0,onRetryEvidence:()=>{j.refetch()},onEvidencePage:j.isFetching?void 0:w=>x({selection:y,cursor:w}),search:c,onSearch:w=>{u(w),d(void 0)},onPage:h.isFetching?void 0:d,onSelectionChange:w=>{(!("measurementQueryKey"in w)||Object.keys(w).some(k=>k!=="measurementQueryKey"&&k!=="measurementAnswer"))&&d(void 0),x(void 0),n(w)},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 Gx=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],Kx=[{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."}],qr=nt[2],_x="var(--chart-tooltip-bg)",Ux={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",local:"Local"};function vs(t){const s=An(t);return Ux[s]??t.charAt(0).toUpperCase()+t.slice(1)}function _s(t){return Math.round(t*10)/10}function Bx(t){return t===Wn||t===Yn||t===rs}function cl(t){return t===Wn?"Cited":t===Yn?"Mentioned":t===rs?"Mention share":vs(t)}function En(t,s){return t===Wn?Is.positive:t===Yn?nt[1]:t===rs?qr:gm(An(t),s)}function Vx(t,s){for(const n of t){const a=n[s];if(typeof a=="number"&&Number.isFinite(a))return a}return null}function zx(t){return t.map(s=>s.trim().toLowerCase()).filter(Boolean).sort().join(`
|
|
2
|
-
`)}function Ia(t){return t==="non-brand"?"non-brand queries":"pooled queries · classification unavailable"}function pa(t,s){return t==="cited"?"Cited":t==="mentionShare"?s?`Mention share · ${Ia(s)}`:"Mention share":"Mentioned"}function zn(t){return t==="cited"?"citationRate":"mentionRate"}function dl(t,s){return s==="cited"?t.cited:t.mentionedCount}function ul(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 ml(t,s){if(s===void 0)return null;const n=String(s);return t.find(a=>a.startDate===n)??null}function Sr(t){const s=ol(t);if(s===null)return"Model attribution unavailable for this bucket.";const n=Object.entries(s).sort(([a],[r])=>An(a).localeCompare(An(r))).map(([a,r])=>`${vs(a)}: ${ks(r)}`);return n.length>0?`Model evidence: ${n.join("; ")}`:"No model evidence in this bucket."}function Qx(t){return t.some(({event:s})=>s.to.status==="mixed")?Is.caution:t.some(({event:s})=>s.to.status==="unknown")?Is.negative:t.every(({event:s})=>s.from.status==="known"&&s.to.status==="known")?nt[4]:Is.positive}function Hx(t,s,n){const a=ml(t,s);return a?Ca(a):Vs($s(n))}function Wx({partition:t,available:s,counts:n,truncated:a,incompleteHistory:r,served:o,mismatch:i,buckets:d}){const c=l.useId(),u=Object.entries(o).sort(([x],[g])=>x.localeCompare(g)),m=t.buckets.length>0||t.beforeWindow.length>0;return!s||!m?null:e.jsxs("aside",{className:"trend-model-evidence","aria-labelledby":"trend-model-evidence-title","aria-describedby":c,children:[e.jsxs("div",{className:"trend-model-evidence-head",children:[e.jsx("p",{id:"trend-model-evidence-title",className:"trend-model-evidence-title",children:"Model evidence changes"}),e.jsx("span",{className:"trend-model-evidence-key","aria-hidden":"true",children:"Dashed chart markers"})]}),e.jsxs("p",{id:c,className:"sr-only",children:["Model evidence is recorded from the exact snapshots that produced each trend bucket. It is not the project’s configured provider model.",n.total>0?` ${n.shown} of ${n.total} recorded changes are listed.`:""]}),t.buckets.length>0&&e.jsx("ul",{className:"trend-model-evidence-list",children:t.buckets.flatMap(({bucketStartDate:x,events:g})=>g.map(({provider:h,event:p})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:Hx(d,x,p.observedAt)}),e.jsxs("span",{children:[vs(h),": ",ks(p.from)," → ",ks(p.to)]})]},`${h}-${p.observedAt}-${p.bucketStartDate}`)))}),t.beforeWindow.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"trend-model-evidence-note",children:"Changed before this date range"}),e.jsx("ul",{className:"trend-model-evidence-list",children:t.beforeWindow.map(({provider:x,event:g})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsxs("span",{className:"trend-model-evidence-date",children:["on or before ",Vs($s(g.observedAt))]}),e.jsxs("span",{children:[vs(x),": ",ks(g.from)," → ",ks(g.to),g.anchorObservedAt?` (last seen ${ks(g.from)} on ${Vs($s(g.anchorObservedAt))})`:""]})]},`before-${x}-${g.observedAt}`))})]}),a.map(x=>e.jsxs("p",{className:"trend-model-evidence-note",children:[vs(x.provider),": showing the most recent ",x.shown," of ",x.total," changes."]},`truncated-${x.provider}`)),r.map(x=>e.jsxs("p",{className:"trend-model-evidence-note",children:["We did not look far enough back to be sure this is every ",vs(x)," change."]},`incomplete-${x}`)),u.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"trend-model-evidence-note",children:"What the engines answered with"}),e.jsx("ul",{className:"trend-model-evidence-list",children:u.map(([x,g])=>{const h=wx(g.latestServedModelIds),p=i[x];return e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:Vs($s(g.latestObservation.observedAt))}),e.jsxs("span",{children:[vs(x),": ",h??ks(g.latestObservation.state),p?` — not the ${ks(p.configured)} you selected`:""]})]},`served-${x}`)})})]})]})}function Di(t){return t===null?"no data":`${t}%`}function Wa(t){return t==null?"undefined":`${_s(t*100)}%`}function Yx({active:t,label:s,payload:n,metric:a,mode:r,buckets:o}){if(!t)return null;const i=ml(o,s);if(!i)return null;if(a==="mentionShare"){const c=i.mentionShare.projectMentionSnapshots,u=i.mentionShare.competitorMentionSnapshots,m=c+u,x=i.mentionShare.rate==null?null:_s(i.mentionShare.rate*100);return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:Ca(i)}),e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch trend-tooltip-swatch-ring",style:{borderColor:qr},"aria-hidden":"true"}),e.jsxs("span",{className:"trend-tooltip-name",children:["Mention share · ",Ia(i.mentionShare.scope)]}),e.jsx("span",{className:"trend-tooltip-value",children:Di(x)})]}),m>0?e.jsxs("p",{className:"trend-tooltip-detail",children:["You ",c," / ",m," brand mentions. Competitors ",u,"."]}):e.jsx("p",{className:"trend-tooltip-detail",children:"No project or competitor brand mentions in this bucket."}),e.jsx("p",{className:"trend-tooltip-detail",children:Sr(i)})]})}const d=r==="byProvider"?(n??[]).filter(c=>c.dataKey!==void 0):[{dataKey:a==="cited"?Wn:Yn,value:_s(i[zn(a)]*100)}];return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:Ca(i)}),d.map((c,u)=>{const m=String(c.dataKey??c.name??""),x=r==="byProvider"?ul(i,m,a):null,g=x?.count??dl(i,a),h=x?.total??i.total,p=typeof c.value=="number"?c.value:_s(x?x.rate*100:i[zn(a)]*100),y=c.color??En(m,u);return e.jsxs("div",{className:"trend-tooltip-block",children:[e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch",style:{backgroundColor:y},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:cl(m)}),e.jsx("span",{className:"trend-tooltip-value",children:Di(p)})]}),e.jsxs("p",{className:"trend-tooltip-detail",children:[g," / ",h," snapshots, ",a==="cited"?"source links":"answer text"]})]},`${m}-${u}`)}),e.jsx("p",{className:"trend-tooltip-detail",children:Sr(i)})]})}function Jx({buckets:t,metric:s,mode:n,series:a}){const r=t[t.length-1]?.mentionShare.scope;return e.jsxs("table",{className:"sr-only",children:[e.jsxs("caption",{children:[pa(s,r)," trend data"]}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Bucket"}),e.jsx("th",{scope:"col",children:"Values"})]})}),e.jsx("tbody",{children:t.map(o=>{let i;if(s==="mentionShare"){const d=o.mentionShare.projectMentionSnapshots,c=o.mentionShare.competitorMentionSnapshots,u=d+c,m=Ia(o.mentionShare.scope);i=u>0?`${Wa(o.mentionShare.rate)} mention share for ${m}, ${d} of ${u} brand mentions were you`:`mention share undefined for ${m}, no project or competitor brand mentions`}else n==="byProvider"?i=a.map(d=>{const c=ul(o,d,s);return c?`${vs(d)} ${Wa(c.rate)} ${pa(s).toLowerCase()}, ${c.count} of ${c.total} snapshots`:`${vs(d)} no data`}).join("; "):i=`${Wa(o[zn(s)])} ${pa(s).toLowerCase()}, ${dl(o,s)} of ${o.total} snapshots`;return i+=`; ${Sr(o)}`,e.jsxs("tr",{children:[e.jsx("th",{scope:"row",children:Ca(o)}),e.jsx("td",{children:i})]},o.startDate)})})]})}function Ya({options:t,value:s,onChange:n,ariaLabel:a,className:r}){const o=l.useId();return e.jsx("div",{role:"group","aria-label":a,className:`segmented ${r??""}`,children:t.map(i=>{const d=s===i.value,c=i.description?`${o}-${i.value}-description`:void 0;return e.jsxs(l.Fragment,{children:[e.jsx("button",{type:"button","aria-pressed":d,"aria-describedby":c,className:`segmented-option ${d?"segmented-option-active":""}`,onClick:()=>n(i.value),children:i.label}),i.description&&e.jsx("span",{id:c,className:"sr-only",children:i.description})]},i.value)})})}function Xx({projectName:t,competitorDomains:s=[],analyticsRevision:n="none"}){const[a,r]=l.useState("all"),[o,i]=l.useState("mentioned"),[d,c]=l.useState("byProvider"),u=l.useMemo(()=>zx(s),[s]),m=we({queryKey:["analytics-metrics",t,a,u,n],queryFn:()=>qc(t,a),staleTime:To}),x=m.data??null,g=m.error,h=o==="mentionShare"?"overall":d,p=l.useMemo(()=>x?Ix(x,o,h):null,[x,o,h]),y=x?bx(x):null,j=l.useMemo(()=>kx(y??{}),[y]),w=l.useMemo(()=>Ax(y??{}),[y]),k=l.useMemo(()=>Px(y??{}),[y]),M=l.useMemo(()=>Object.entries(y??{}).filter(([,Q])=>Q.anchorUnavailable).map(([Q])=>Q).sort(),[y]),C=l.useMemo(()=>x?vx(x):{},[x]),f=l.useMemo(()=>x?jx(x):{},[x]),v=l.useMemo(()=>x?Ec(Nx(x)):null,[x]),S=o!=="mentionShare"&&h==="byProvider",R=x?.buckets??[],E=R[R.length-1]?.mentionShare.scope??x?.mentionShareScope??"pooled",L=pa(o,E),B=o==="cited"?Is.positive:o==="mentionShare"?qr:nt[1],U=S?os.textDim:B,T=l.useMemo(()=>{const Q=new Map(R.map($=>[$.startDate,fx($)]));return $=>Q.get(String($))??""},[R]),N=o==="mentionShare"?p?Ti(p.rows,rs):null:R.length>0?_s(R[R.length-1][zn(o)]*100):null,D=o==="mentionShare"?p?Vx(p.rows,rs):null:R.length>0?_s(R[0][zn(o)]*100):null,J=o==="mentionShare"?p?.rows.filter(Q=>typeof Q[rs]=="number").length??0:R.length,G=N!==null&&D!==null&&J>1?_s(N-D):null,Z=s.length,de=e.jsxs(e.Fragment,{children:[v?.kind==="change"&&e.jsx("p",{className:"mb-3 rounded-lg border border-caution-800/60 bg-caution-950/20 px-3 py-2 text-[11px] leading-snug text-secondary",children:v.text}),e.jsxs("div",{className:"visibility-trend-head",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsxs("h2",{className:"visibility-trend-title",children:["Answer-engine trend",e.jsx(Me,{text:"Three separate signals over sweep buckets: answer text mentions, source citations, and your answer-text mention share against tracked competitors. Mentioned and Cited use all query-provider snapshots. Mention share uses non-brand queries when classification is available; pooled means the project has no usable brand identity for a split."})]})]}),N!==null&&e.jsxs("div",{className:"visibility-trend-current",children:[e.jsx("span",{className:"visibility-trend-current-dot",style:{backgroundColor:U},"aria-hidden":"true"}),e.jsx("span",{className:"visibility-trend-current-label",children:L}),S&&e.jsx("span",{className:"visibility-trend-current-qualifier",children:"avg"}),e.jsxs("span",{className:"visibility-trend-current-value",children:[N,"%"]}),G!==null&&e.jsxs("span",{className:`visibility-trend-current-delta ${G>0?"text-positive-400":G<0?"text-negative-400":"text-muted"}`,children:[G>0?"+":"",G.toFixed(1)," pts"]})]})]}),e.jsxs("div",{className:"visibility-trend-controls",children:[e.jsx(Ya,{options:Kx,value:o,onChange:i,ariaLabel:"Metric",className:"visibility-trend-metric-control"}),o!=="mentionShare"&&e.jsx(Ya,{options:Gx,value:d,onChange:c,ariaLabel:"Series"}),e.jsx(Ya,{options:Tx,value:a,onChange:r,ariaLabel:"Time window",className:"sm:ml-auto"})]})]});let se;if(g)se=e.jsx("p",{className:"text-sm text-negative-400",children:_n(g)});else if(m.isLoading&&!x)se=e.jsx("div",{className:"visibility-trend-chart animate-pulse rounded-lg bg-bg-elevated/40","aria-hidden":"true"});else if(o==="mentionShare"&&Z===0)se=e.jsx("p",{className:"text-sm text-secondary",children:"Add tracked competitors to measure mention share over time."});else if(!x||!p)se=null;else{const{rows:Q,series:$,hasData:ie}=p,O=$x(x.queryChanges);if(!ie)se=e.jsx("p",{className:"text-sm text-secondary",children:o==="mentionShare"?`No answer-text brand mentions for you or tracked competitors on ${Ia(E)} in this window yet.`:Vt()?Hs:"Run a sweep to start tracking citations and mentions over time."});else if(S&&$.length===0)se=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 _=`${L} rate across ${Q.length} ${Q.length===1?"sweep":"sweeps"}. Latest ${N}%${G!==null?`, ${G>=0?"up":"down"} ${Math.abs(G).toFixed(1)} points over the period`:""}.`;se=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"sr-only",children:_}),e.jsx(Jx,{buckets:R,metric:o,mode:h,series:$}),S&&$.length>0&&e.jsx("ul",{className:"trend-legend","aria-label":"Engines",children:$.map((X,ge)=>{const H=Ti(Q,X),ae=Sx(R,X),ue=y===null?"Attribution unavailable":ae?ks(ae):"No observed model evidence";return e.jsxs("li",{className:"trend-legend-item",children:[e.jsx("span",{className:"trend-legend-swatch",style:{backgroundColor:En(X,ge)},"aria-hidden":"true"}),e.jsxs("span",{className:"trend-legend-label",children:[e.jsx("span",{className:"trend-legend-name",children:cl(X)}),e.jsxs("span",{className:"trend-legend-model",children:[e.jsx("span",{"aria-hidden":"true",children:"· "}),ue]})]}),H!==null&&e.jsxs("span",{className:"trend-legend-value",children:[H,"%"]})]},X)})}),e.jsx("div",{className:"visibility-trend-chart",role:"img","aria-label":`${L} trend chart over ${Q.length} ${Q.length===1?"bucket":"buckets"}`,children:e.jsx(Ys,{width:"100%",height:"100%",children:e.jsxs(Js,{data:Q,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Vn,{stroke:Bn,vertical:!1}),e.jsx(Xs,{dataKey:"date",tick:Rt,tickLine:!1,axisLine:{stroke:is},tickFormatter:T,minTickGap:24}),e.jsx(Zs,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:X=>`${X}%`,tick:Rt,tickLine:!1,axisLine:!1,width:40}),e.jsx(en,{cursor:{stroke:is,strokeWidth:1},content:e.jsx(Yx,{metric:o,mode:h,buckets:R})}),j.buckets.map(({bucketStartDate:X,events:ge})=>e.jsx(Nm,{x:X,stroke:Qx(ge),strokeDasharray:"4 4",strokeWidth:1.5,ifOverflow:"extendDomain"},`model-evidence-${X}`)),$.map((X,ge)=>e.jsx(Ps,{type:"monotone",dataKey:X,name:X,stroke:En(X,ge),strokeDasharray:X===rs?"5 4":void 0,strokeWidth:Bx(X)?2.5:2,dot:X===rs?{r:2.75,fill:"var(--chart-tooltip-bg)",stroke:En(X,ge),strokeWidth:1.5}:{r:2.5,fill:En(X,ge),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:_x},connectNulls:X!==rs,isAnimationActive:!1},X))]})})}),e.jsx(Wx,{partition:j,available:y!==null,counts:w,truncated:k,incompleteHistory:M,served:C,mismatch:f,buckets:R}),O&&e.jsx("p",{className:"visibility-trend-note",children:O})]})}}return e.jsxs("section",{className:"visibility-trend",children:[de,se]})}const Oi=new Set([Gn.queued,Gn.running]);function Fi({projectName:t,onReviewForTracking:s,viewerResearchConfig:n=null}){const a=Ns(),{account:r,canWrite:o}=Hn(),i=r?.role==="viewer"&&n!==null,[d,c]=l.useState(""),[u,m]=l.useState(""),[x,g]=l.useState(""),[h,p]=l.useState(""),[y,j]=l.useState(null),w=l.useRef(null),k=l.useRef(!1),M=we({...Dc({client:W,path:{name:t}}),staleTime:6e4}),C=we({...Oc({client:W}),enabled:!i,staleTime:6e4}),f=we({...Fc({client:W,path:{name:t},query:{limit:20}}),refetchInterval:O=>O.state.data?.runs.some(_=>Oi.has(_.status))?3e3:!1}),v=f.isError?[]:f.data?.runs??[];l.useEffect(()=>{!y&&v[0]&&j(v[0].id)},[v,y]);const S=v.find(O=>O.id===y)??null,R=we({...Gc({client:W,path:{name:t,runId:y??""}}),enabled:!f.isError&&!!y,refetchInterval:S&&Oi.has(S.status)?3e3:!1}),E=f.isError||R.isError?null:R.data??null,L=l.useMemo(()=>tp(d),[d]),B=M.data?.locations??[],U=l.useMemo(()=>{if(i)return(f.data?.providers??[]).map(_=>({..._,catalog:_}));const O=new Map((C.data?.providerCatalog??[]).map(_=>[_.name,_]));return(C.data?.providers??[]).filter(_=>_.configured&&O.get(_.name)?.mode==="api").map(_=>({..._,catalog:O.get(_.name)}))},[i,f.data?.providers,C.data]),T=!(i?f.isPending:C.isPending)&&U.length===0,N=U.find(O=>O.name===u)??null;l.useEffect(()=>{if(!u&&M.data&&!M.isError&&!C.isError){const O=M.data.providers.find(_=>U.some(X=>X.name===_));m(O??U[0]?.name??"")}},[u,U,M.data,M.isError,C.isError]),l.useEffect(()=>{!h&&M.data&&!M.isError&&p(M.data.defaultLocation??"__none__")},[h,M.data,M.isError]);const D=h==="__none__"?null:B.find(O=>O.label===h),J=N?.catalog.modelConfigurable??!1,G=(J?x.trim():"")||(N?M.data?.providerModels[N.name]:"")||N?.catalog.defaultModel,Z=D===void 0?null:N&&G?{queries:L,provider:N.name,...J?{model:G}:{},location:D}:null,de=N?[...new Map([{id:N.catalog.defaultModel,displayName:N.catalog.defaultModel},...N.catalog.knownModels].map(O=>[O.id,O])).values()]:[],se=Z?JSON.stringify({projectName:t,...Z}):null,Q=(o||i)&&!te()&&Z!==null&&!M.isPending&&!M.isError&&!M.isFetching&&(i?!f.isPending&&!f.isError:!C.isPending&&!C.isError&&!C.isFetching)&&L.length>0&&L.length<=50;l.useEffect(()=>{w.current?.fingerprint!==se&&(w.current=null)},[se]);const $=Pt({...Kc(),onSuccess:async O=>{w.current=null,j(O.id),c(""),g(""),await rp(a),Se({title:"Research batch saved",detail:`${O.totalQueries} quer${O.totalQueries===1?"y is":"ies are"} in research history. Nothing was added to tracked queries.`,tone:"positive",dedupeKey:`research:start:${O.id}`,dedupeMode:"replace"})},onError:O=>{Se({title:"Could not start research",detail:O instanceof Error?O.message:"Check the provider, model, and location, then try again.",tone:"negative"})},onSettled:()=>{k.current=!1}});function ie(){!Q||$.isPending||k.current||!Z||!se||(k.current=!0,w.current?.fingerprint!==se&&(w.current={fingerprint:se,key:crypto.randomUUID()}),$.mutate({client:W,path:{name:t},body:{...Z,idempotencyKey:w.current.key}}))}return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.85fr)_minmax(360px,1.15fr)]",children:[e.jsxs(xe,{className:"surface-card min-w-0",children:[e.jsx("div",{className:"section-head",children:e.jsx("div",{children:e.jsx("h3",{children:"Test queries"})})}),e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("label",{className:"block",htmlFor:"research-queries",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Queries"}),e.jsx("textarea",{id:"research-queries",className:"mt-1 min-h-36 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:`one query per line
|
|
3
|
-
e.g. What is the best way to choose an AEO platform?`,value:d,"aria-label":"Queries",onChange:O=>c(O.target.value),"aria-describedby":"research-query-count"}),e.jsxs("span",{id:"research-query-count",className:`mt-1 block text-sm ${L.length>50?"text-negative":"text-secondary"}`,children:[L.length," ",L.length===1?"query":"queries",", duplicates and blank lines are removed. Maximum 50."]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"block",htmlFor:"research-provider",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Answer engine"}),e.jsxs("select",{id:"research-provider",className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none",value:u,onChange:O=>{m(O.target.value),g("")},children:[e.jsx("option",{value:"",disabled:!0,children:"Choose a provider"}),U.map(O=>e.jsx("option",{value:O.name,children:O.displayName??O.name},O.name))]})]}),e.jsxs("label",{className:"block",htmlFor:"research-location",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Location"}),e.jsxs("select",{id:"research-location",className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none",value:h,onChange:O=>p(O.target.value),children:[e.jsx("option",{value:"",disabled:!0,children:"Choose a location"}),e.jsx("option",{value:"__none__",children:"No location"}),B.map(O=>e.jsx("option",{value:O.label,children:O.label},O.label))]})]})]}),i?e.jsxs("label",{className:"block",htmlFor:"research-model",children:[e.jsx("span",{className:"text-sm font-medium text-secondary",children:"Model"}),e.jsxs("select",{id:"research-model","aria-label":"Model",className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none",value:G??"",disabled:!N||!J,onChange:O=>g(O.target.value),children:[!N&&e.jsx("option",{value:"",children:"Choose an answer engine"}),de.map(O=>e.jsxs("option",{value:O.id,children:[O.displayName,O.id===N?.catalog.defaultModel?" (default)":""]},O.id))]})]}):e.jsxs("label",{className:"block",htmlFor:"research-model",children:[e.jsxs("span",{className:"text-xs font-medium text-secondary",children:["Exact model ",e.jsx("span",{className:"font-normal text-muted",children:"(optional)"})]}),e.jsx("input",{id:"research-model",list:"research-known-models",className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none disabled:cursor-not-allowed disabled:opacity-50",placeholder:G?`Current: ${G}`:"Choose a provider to select an exact model",value:x,disabled:!N||!J,onChange:O=>g(O.target.value)}),e.jsx("datalist",{id:"research-known-models",children:(N?.catalog.knownModels??[]).map(O=>e.jsx("option",{value:O.id,children:O.displayName},O.id))})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 border-t border-default pt-4",children:[!te()&&(i?e.jsxs(A,{type:"button",size:"sm",disabled:!Q||$.isPending,onClick:ie,children:[e.jsx(Un,{size:14}),$.isPending?"Starting research…":`Run ${L.length||""} research ${L.length===1?"query":"queries"}`]}):e.jsxs(De,{type:"button",size:"sm",disabled:!Q||$.isPending,onClick:ie,children:[e.jsx(Un,{size:14}),$.isPending?"Starting research…":`Run ${L.length||""} research ${L.length===1?"query":"queries"}`]})),e.jsx("p",{className:"text-sm leading-5 text-secondary",children:"Saved to research history. Nothing is added to tracked queries."}),L.length===0&&e.jsx("p",{className:"text-sm text-secondary",children:"Enter at least one query to enable Run."})]}),Z&&e.jsxs("p",{className:"text-sm text-secondary",children:[N?.displayName??Z.provider," · ",G," · ",D?.label??"No location"]}),i&&e.jsxs("p",{className:"text-sm text-secondary",children:["Up to ",n.viewerDailyRunLimit," research batches per project each day. Each batch can contain up to 50 queries."]}),!i&&C.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load API providers."}),e.jsx(A,{variant:"outline",onClick:()=>{C.refetch()},children:"Retry providers"})]}):null,M.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load project locations."}),e.jsx(A,{variant:"outline",onClick:()=>{M.refetch()},children:"Retry locations"})]}):null,!(i?f.isError:C.isError)&&T&&e.jsx("p",{className:"rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2 text-sm text-caution",children:i?"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."})]})]}),e.jsxs(xe,{className:"surface-card min-w-0",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Saved research batches"})]}),f.isFetching&&e.jsx(le,{tone:"neutral",children:"Loading"})]}),f.isError?e.jsxs("div",{role:"alert",className:"mt-4 text-sm text-negative",children:[e.jsx("p",{children:"Could not load research history."}),e.jsx(A,{variant:"outline",onClick:()=>{f.refetch()},children:"Retry history"})]}):f.isPending?e.jsx("p",{role:"status",children:"Loading research history…"}):v.length===0?e.jsx("p",{className:"mt-4 text-sm text-muted",children:"No research batches yet. Add one or more queries to begin."}):e.jsx("div",{className:"mt-4 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[680px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Run"}),e.jsx("th",{children:"Model"}),e.jsx("th",{children:"Location"}),e.jsx("th",{children:"Progress"}),e.jsx("th",{children:"Status"})]})}),e.jsx("tbody",{children:v.map(O=>e.jsxs("tr",{className:y===O.id?"bg-bg-elevated/40":void 0,children:[e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-left font-medium text-heading hover:text-link focus:outline-none focus:underline",onClick:()=>j(O.id),children:sp(O.createdAt)})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:O.provider}),e.jsx("span",{className:"font-mono text-[11px] text-muted",children:O.requestedModel??O.resolvedModel})]}),e.jsx("td",{className:"text-secondary",children:O.location?.label??"No location"}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[O.completedQueries+O.failedQueries,"/",O.totalQueries]}),e.jsx("td",{children:e.jsx(le,{tone:hl(O.status),children:O.status})})]},O.id))})]})})]})]}),!f.isError&&R.isError?e.jsxs("div",{role:"alert",className:"text-sm text-negative",children:[e.jsx("p",{children:"Could not load saved research results."}),e.jsx(A,{variant:"outline",onClick:()=>{R.refetch()},children:"Retry results"})]}):f.isError?null:e.jsx(Zx,{detail:E,isLoading:R.isFetching,onReviewForTracking:s})]})}function Zx({detail:t,isLoading:s,onReviewForTracking:n}){const[a,r]=l.useState(null);l.useEffect(()=>{r(t?.queries[0]?.id??null)},[t?.id]);const o=t?.queries.find(i=>i.id===a)??t?.queries[0]??null;return e.jsxs(xe,{className:"surface-card min-w-0",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 ${np(t.id)}`:"Choose a research batch"})]}),t&&e.jsx(le,{tone:hl(t.status),children:t.status})]}),t?e.jsxs("div",{className:"mt-4 grid gap-4 xl:grid-cols-[minmax(0,1.15fr)_minmax(320px,0.85fr)]",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[680px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"})]})}),e.jsx("tbody",{children:t.queries.map(i=>e.jsxs("tr",{className:o?.id===i.id?"bg-bg-elevated/40":void 0,children:[e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-left font-medium text-heading hover:text-link focus:outline-none focus:underline",onClick:()=>r(i.id),children:i.query})}),e.jsx("td",{children:e.jsx(le,{tone:ap(i.status),children:i.status})}),e.jsx("td",{children:e.jsx(le,{tone:i.answerMentioned===!0?"positive":i.answerMentioned===!1?"neutral":i.status===mn.failed?"negative":"caution",children:i.answerMentioned===null?i.status===mn.failed?"Unavailable":"Pending":i.answerMentioned?"Mentioned":"Not mentioned"})}),e.jsx("td",{children:e.jsx(le,{tone:i.citationState==="cited"?"positive":i.citationState==="not-cited"?"neutral":i.status===mn.failed?"negative":"caution",children:i.citationState===null?i.status===mn.failed?"Unavailable":"Pending":i.citationState==="cited"?"Cited":"Not cited"})})]},i.id))})]})}),e.jsx(ep,{query:o,isLoading:s,onReviewForTracking:n})]}):e.jsx("p",{className:"mt-4 text-sm text-muted",children:"Select a saved batch to inspect each answer and its source links."})]})}function ep({query:t,isLoading:s,onReviewForTracking:n}){return t?e.jsxs("div",{className:"space-y-4 border-t border-default pt-4 xl:border-t-0 xl:border-l xl:pl-4 xl:pt-0",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Selected query"}),e.jsx("p",{className:"mt-1 text-sm font-medium leading-6 text-heading",children:t.query})]}),!te()&&n&&e.jsxs("div",{className:"rounded-md border border-default bg-surface-subtle px-3 py-3",children:[e.jsx(De,{type:"button",size:"sm",onClick:()=>n({researchRunQueryId:t.id}),children:"Review for tracking"}),e.jsx("p",{className:"mt-2 text-xs leading-5 text-muted",children:"Only this saved query text enters tracking review. Its answer remains research evidence."})]}),t.error?e.jsx("div",{className:"rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:t.error}):t.answerText?e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Answer"}),e.jsx("p",{className:"mt-1 whitespace-pre-wrap text-sm leading-6 text-secondary",children:t.answerText})]}):e.jsx("p",{className:"text-sm text-muted",children:t.status===mn.failed?"This query did not return an answer.":"The answer will appear here when this query finishes."}),t.namedCompetitors.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Named in answer"}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:t.namedCompetitors.map(a=>e.jsx("span",{className:"mention-chip mention-chip--competitor",children:a},a))})]}),t.citedCompetitorDomains.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Cited competitor domains"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:"Cited as a source, not merely named in the answer."}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:t.citedCompetitorDomains.map(a=>e.jsx("span",{className:"mention-chip mention-chip--competitor",children:a.replace(/^www\./,"")},a))})]}),t.groundingSources.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Source links"}),e.jsx("ul",{className:"mt-2 space-y-1",children:t.groundingSources.map((a,r)=>{const o=Os(a.uri),i=a.title||a.uri;return e.jsxs("li",{className:"flex min-w-0 items-start gap-1.5 text-sm",children:[o?e.jsx("a",{href:o,target:"_blank",rel:"noopener noreferrer",className:"truncate text-secondary hover:text-link focus:outline-none focus:underline",children:i}):e.jsx("span",{className:"truncate text-secondary",children:i}),o&&e.jsx(um,{className:"mt-0.5 size-3 shrink-0 text-muted","aria-hidden":"true"})]},`${a.uri}-${r}`)})})]})]}):e.jsx("p",{className:"text-sm text-muted",children:s?"Loading saved answers…":"Select a query to inspect its answer."})}function tp(t){const s=new Set;return t.split(/\r?\n/).map(n=>n.trim()).filter(n=>{const a=n.toLocaleLowerCase();return!n||s.has(a)?!1:(s.add(a),!0)})}function sp(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 np(t){return t.length>8?t.slice(0,8):t}function hl(t){return t===Gn.completed?"positive":t===Gn.partial?"caution":t===Gn.failed?"negative":"neutral"}function ap(t){return t===mn.completed?"positive":t===mn.failed?"negative":"neutral"}async function rp(t){await Nt(t,"researchRuns")}const Cr=new Set(["queued","seeding","probing"]);function ip({projectName:t,queryWorkspace:s,onQueryWorkspaceChange:n,researchMode:a,onResearchModeChange:r,selection:o={measurementScope:"project",queryClass:"all"},onSelectionChange:i,trackingQueryId:d,onTrackingQueryIdChange:c}){const{account:u}=Hn(),[m,x]=l.useState("tracked"),[g,h]=l.useState("find"),[p,y]=l.useState(null),j=u?.role==="viewer"?_c():null,w=u?.role!=="viewer"||j!==null,k=s??m,M=k==="research"&&!w?"tracked":k,C=a??g,f=R=>{s===void 0&&x(R),n?.(R)},v=R=>{a===void 0&&h(R),r?.(R)},S=R=>{y({...R,trackingSelection:{...o}}),f("tracked")};return e.jsxs("section",{className:"page-section-divider","aria-labelledby":"queries-heading",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"queries-heading",children:"Queries"})}),e.jsxs("div",{className:"mt-3 flex border-b border-default",role:"tablist","aria-label":"Query workspace",children:[e.jsx(ka,{active:M==="tracked",label:"Tracked",onClick:()=>f("tracked")}),w?e.jsx(ka,{active:M==="research",label:"Research",onClick:()=>f("research")}):null]}),e.jsx("div",{className:"mt-4",children:M==="tracked"?e.jsx(Cp,{projectName:t,selection:o,onSelectionChange:i,trackingQueryId:d,onTrackingQueryIdChange:c,pendingTrackingSource:p,onPendingTrackingSourceHandled:()=>y(null)}):e.jsx(op,{projectName:t,selection:o,mode:C,onModeChange:v,onReviewSavedSource:S,viewerResearchConfig:j})})]})}function ka({active:t,label:s,onClick:n}){return e.jsx("button",{type:"button",role:"tab","aria-selected":t,className:`-mb-px border-b-2 px-3 py-2 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500 focus-visible:ring-inset ${t?"border-mono-400 text-heading":"border-transparent text-muted hover:border-strong hover:text-strong"}`,onClick:n,children:s})}function op({projectName:t,selection:s,mode:n,onModeChange:a,onReviewSavedSource:r,viewerResearchConfig:o}){const i=we({...Mo({client:W,path:{name:t}}),enabled:o===null&&s.measurementScope!=="project"}),d=i.data?fa(s,i.data):s.measurementScope==="project"?"Whole site":`${s.measurementScopeKey??"Selected scope"} · ${s.measurementScope==="group"?"Group":s.measurementScope==="market"?"Market":"Property"}`,c=i.data&&s.measurementScope==="property"?`${d} · Property`:d;return o?e.jsx(Fi,{projectName:t,viewerResearchConfig:o}):e.jsxs("div",{children:[e.jsxs("p",{className:"mb-3 text-sm text-secondary",children:["Tracking destination: ",c]}),e.jsxs("div",{className:"flex border-b border-default",role:"tablist","aria-label":"Research workspace",children:[e.jsx(ka,{active:n==="find",label:"Find queries",onClick:()=>a("find")}),e.jsx(ka,{active:n==="test",label:"Test queries",onClick:()=>a("test")})]}),e.jsx("div",{className:"mt-4",children:n==="find"?e.jsx(kp,{projectName:t,onReviewDiscoveryProbe:u=>r({source:"discovery",discoveryProbeId:u})}):e.jsx(Fi,{projectName:t,onReviewForTracking:({researchRunQueryId:u})=>r({source:"research",researchRunQueryId:u})})})]})}function lp({workspace:t,selection:s,onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:o,onPendingTrackingSourceHandled:i,templates:d,preview:c,isPreviewing:u,isCommitting:m,onPreview:x,onCommit:g}){const[h,p]=l.useState(null),[y,j]=l.useState(()=>ga(s)),[w,k]=l.useState(null),M=l.useRef(null),C=l.useRef(null),f=l.useMemo(()=>mp(t.tracked,s),[s,t.tracked]),v=xn({rows:f,getSearchText:N=>`${N.queryText} ${N.provenance?.source??"legacy"} ${N.assignments.map(D=>D.queryClass??"unknown").join(" ")}`});l.useEffect(()=>{if(!a){C.current=null;return}const N=`${a}:${ya(s)}`;if(C.current===N)return;const D=t.tracked.find(J=>J.queryId===a);D&&(C.current=N,p({kind:"edit",row:D,audience:t.mode==="advanced"?Ja(s):void 0,scopeLabel:fa(s,t)}),j(Gi(D,s)),k(null))},[s,a,t]),l.useEffect(()=>{if(!o)return;const N=ga(o.trackingSelection??s);p({kind:"add"}),j(o.source==="research"?{...N,source:"research",researchRunQueryId:o.researchRunQueryId}:{...N,source:"discovery",discoveryProbeId:o.discoveryProbeId}),k(null),i()},[i,o,s]),l.useEffect(()=>{if(!h||h.kind==="remove")return;const N=M.current;N&&(N.scrollIntoView?.({block:"start"}),N.focus({preventScroll:!0}))},[h]);function S(N="manual"){p({kind:"add"}),j({...ga(s),source:N}),k(null),r?.(void 0)}function R(N){C.current=`${N.queryId}:${ya(s)}`,p({kind:"edit",row:N,audience:t.mode==="advanced"?Ja(s):void 0,scopeLabel:fa(s,t)}),j(Gi(N,s)),k(null),r?.(N.queryId)}function E(N){C.current=`${N.queryId}:${ya(s)}`,p({kind:"remove",row:N,audience:t.mode==="advanced"?Ja(s):void 0,scopeLabel:fa(s,t)}),k(null),r?.(N.queryId)}function L(){p(null),k(null),r?.(void 0)}const B=h?cp(h,y,t.mode):null,U=h!==null&&h.kind==="add"&&t.mode==="advanced"&&!Er(y),T=B!==null&&(!U||y.contexts.length>0)&&!u;return e.jsxs("div",{className:"query-tracking-workspace space-y-4",children:[e.jsxs("section",{"aria-label":"Tracked queries",children:[e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsx(xp,{workspace:t,selection:s,onSelectionChange:n}),e.jsx(Bs,{value:v.query,onChange:v.setQuery,label:"Filter tracked queries",placeholder:"Search tracked queries",className:"min-w-64 flex-[2]"}),!te()&&e.jsxs(De,{type:"button",size:"sm",onClick:()=>S(),children:[e.jsx(mm,{"aria-hidden":"true",size:14}),"Add query"]})]}),t.active?null:e.jsx("p",{className:"mt-3 text-sm text-caution",children:"No published measurement yet."}),v.rows.length===0?e.jsx("p",{className:"mt-5 text-sm text-muted",children:v.hasQuery?"No tracked queries match that search.":"No tracked queries in this scope yet."}):e.jsx("div",{className:"mt-5 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table measurement-responsive-table min-w-[760px] table-auto",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Scope"}),e.jsx("th",{children:"Class"}),e.jsx("th",{children:"Source"}),e.jsx("th",{children:"Measurement"}),e.jsx("th",{className:"measurement-table-actions",children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{children:v.rows.map(N=>e.jsxs("tr",{children:[e.jsx("td",{className:"tracking-query-cell break-words font-medium text-heading",children:N.queryText}),e.jsx("td",{className:"tracking-scope-cell text-secondary",children:xl(N,t,s)}),e.jsx("td",{className:"whitespace-nowrap",children:e.jsx(gp,{row:N})}),e.jsx("td",{className:"whitespace-nowrap text-secondary",children:pp(N)}),e.jsx("td",{className:"whitespace-nowrap",children:e.jsx(fp,{row:N})}),e.jsx("td",{className:"measurement-table-actions whitespace-nowrap text-right",children:!te()&&e.jsxs("div",{className:"tracking-row-actions flex min-w-max justify-end gap-2",children:[e.jsxs(De,{type:"button",variant:"ghost",size:"sm","aria-label":`Edit ${N.queryText}`,onClick:()=>R(N),children:[e.jsx(hm,{"aria-hidden":"true",size:13})," Edit"]}),e.jsxs(De,{type:"button",variant:"ghost",size:"sm","aria-label":`Remove ${N.queryText}`,onClick:()=>E(N),children:[e.jsx(Go,{"aria-hidden":"true",size:13})," Remove"]})]})})]},N.queryId))})]})}),e.jsx(Rs,{page:v.page,pageSize:v.pageSize,visibleRows:v.rows.length,totalRows:v.totalRows,itemLabel:"queries",onPageChange:v.setPage})]}),h&&!te()&&e.jsx(yp,{workspace:t,templates:d,action:h,draft:y,onDraftChange:N=>{j(N),k(null)},onClose:L,canReview:T,isPreviewing:u,editorHeadingRef:M,onReview:()=>{B&&(k(B),x(B))}}),c&&w&&h&&e.jsx(Np,{preview:c,workspace:t,isCommitting:m,onConfirm:()=>{g({...w,expectedWorkspaceVersion:c.workspaceVersion,previewToken:c.previewToken,reviewedAt:c.reviewedAt})}})]})}function ga(t){return{source:"manual",text:"",templateId:"",templateVersion:"",template:"",researchRunQueryId:"",discoveryProbeId:"",wholeSite:t.measurementScope==="project"||!t.measurementScopeKey,targetKeys:t.measurementScope==="property"&&t.measurementScopeKey?[t.measurementScopeKey]:[],groupKeys:t.measurementScope==="group"&&t.measurementScopeKey?[t.measurementScopeKey]:[],marketKeys:t.measurementScope==="market"&&t.measurementScopeKey?[t.measurementScopeKey]:[],contexts:[],queryClass:"auto"}}function Gi(t,s){return{...ga(s),text:t.queryText,queryClass:"keep"}}function cp(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=dp(s);if(!a||kr(s)||!s.wholeSite&&s.targetKeys.length+s.groupKeys.length+s.marketKeys.length===0)return null;const r=up(s);return{additions:[{input:a,...r?{audience:r}:{},...n==="advanced"&&!Er(s)&&s.contexts.length>0?{contexts:s.contexts}:{},...n==="advanced"&&s.queryClass!=="auto"&&s.queryClass!=="keep"?{queryClass:s.queryClass}:{}}],removals:[]}}function dp(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 up(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 Er(t){return t.marketKeys.length>0&&t.targetKeys.length===0&&t.groupKeys.length===0}function kr(t){return t.source==="template"&&t.template.includes("{market}")&&(t.wholeSite||t.marketKeys.length===0)}function Ja(t){if(t.measurementScopeKey){if(t.measurementScope==="property")return{targetKeys:[t.measurementScopeKey]};if(t.measurementScope==="group")return{groupKeys:[t.measurementScopeKey]};if(t.measurementScope==="market")return{marketKeys:[t.measurementScopeKey]}}}function fa(t,s){const a=(t.measurementScope==="property"?s.targets:t.measurementScope==="group"?s.groups:t.measurementScope==="market"?s.markets:[]).find(r=>r.stableKey===t.measurementScopeKey)?.label;return a?t.measurementScope==="group"?`${a} · Group`:t.measurementScope==="market"?`${a} · Market`:a:"Whole site"}function mp(t,s){return s.measurementScope==="project"||!s.measurementScopeKey?[...t]:t.filter(n=>n.assignments.some(a=>s.measurementScope==="property"?a.targetKey===s.measurementScopeKey:s.measurementScope==="group"?a.groupKeys.includes(s.measurementScopeKey):a.marketKeys.includes(s.measurementScopeKey)))}function ya(t){return t.measurementScopeKey&&t.measurementScope!=="project"?`${t.measurementScope}:${t.measurementScopeKey}`:"project"}function hp(t){if(t==="project")return{measurementScope:"project",measurementScopeKey:void 0};const[s,n]=t.split(":",2);return{measurementScope:s,measurementScopeKey:n}}function xp({workspace:t,selection:s,onSelectionChange:n}){const[a,r]=l.useState(""),o=l.useRef(null),i=l.useRef(null);l.useEffect(()=>{const g=h=>{o.current?.open&&h.target instanceof Node&&!o.current.contains(h.target)&&(o.current.open=!1)};return document.addEventListener("pointerdown",g),()=>document.removeEventListener("pointerdown",g)},[]);const d=l.useMemo(()=>[{value:"project",label:"Whole site",detail:"Project"},...t.groups.map(g=>({value:`group:${g.stableKey}`,label:g.label,detail:"Group"})),...t.markets.map(g=>({value:`market:${g.stableKey}`,label:g.label,detail:"Market"})),...t.targets.map(g=>({value:`property:${g.stableKey}`,label:g.label,detail:"Property"}))],[t.groups,t.markets,t.targets]),c=ya(s),u=d.find(g=>g.value===c)??d[0],m=a.trim().toLocaleLowerCase(),x=m?d.filter(g=>`${g.label} ${g.detail}`.toLocaleLowerCase().includes(m)):d;return e.jsxs("div",{className:"min-w-64 flex-1",children:[e.jsx("span",{id:"tracking-scope-label",className:"mb-1 block text-xs font-medium text-secondary",children:"Measurement scope"}),e.jsxs("details",{ref:o,className:"relative",onToggle:g=>{g.currentTarget.open&&i.current?.focus()},onKeyDown:g=>{g.key==="Escape"&&(g.preventDefault(),g.currentTarget.open=!1,g.currentTarget.querySelector("summary")?.focus())},children:[e.jsxs("summary",{"aria-labelledby":"tracking-scope-label",className:"visibility-scope-trigger min-h-11 rounded-md border border-default bg-surface px-3 text-sm text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500",children:[u.detail==="Group"||u.detail==="Market"?`${u.label} · ${u.detail}`:u.label,e.jsx(Ws,{size:16,"aria-hidden":"true",className:"shrink-0 text-secondary"})]}),e.jsxs("div",{className:"visibility-scope-menu",children:[e.jsx("p",{className:"mb-2 text-sm leading-5 text-secondary",children:"Group: properties grouped together. Market: search context."}),e.jsxs("label",{children:[e.jsx("span",{className:"sr-only",children:"Search scopes"}),e.jsx("input",{ref:i,type:"search","aria-label":"Search scopes",className:"h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",placeholder:"Search groups, markets, properties",value:a,onChange:g=>r(g.target.value)})]}),e.jsx("div",{className:"mt-2 max-h-72 overflow-y-auto",children:x.length===0?e.jsx("p",{className:"py-3 text-sm text-secondary",children:"No matching scopes."}):x.map(g=>e.jsxs("button",{type:"button",className:"flex min-h-11 w-full items-center justify-between gap-3 rounded px-2 text-left text-sm text-primary hover:bg-surface-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500","aria-label":`${g.label}, ${g.detail}`,"aria-current":g.value===c?"true":void 0,onClick:h=>{const p=h.currentTarget.closest("details");p&&(p.open=!1,p.querySelector("summary")?.focus()),n?.(hp(g.value))},children:[e.jsx("span",{children:g.label}),e.jsx("span",{className:"text-secondary",children:g.detail})]},g.value))})]})]})]})}function pp(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 xl(t,s,n){const a=new Map(s.targets.map(h=>[h.stableKey,h.label])),r=new Map(s.groups.map(h=>[h.stableKey,h.label])),o=new Map(s.markets.map(h=>[h.stableKey,h.label])),i=new Set,d=new Set,c=new Set;for(const h of t.assignments)i.add(h.targetKey),(n?.measurementScope!=="property"||h.targetKey===n.measurementScopeKey)&&(h.groupKeys.forEach(p=>d.add(p)),h.marketKeys.forEach(p=>c.add(p)));if(i.size===0)return"Whole site";const m=n?.measurementScope==="property"&&i.has(n.measurementScopeKey??"")?i.size===1?["This property only"]:["This property",`Shared with ${i.size-1} other ${i.size===2?"property":"properties"}`]:[i.size===1?a.get([...i][0])??[...i][0]:`${i.size} properties`],x=d.size===1?r.get([...d][0])??[...d][0]:null,g=c.size===1?o.get([...c][0])??[...c][0]:null;return x&&g&&x===g?m.push(`${x} (group and market)`):(x?m.push(`Group: ${x}`):d.size>1&&m.push(`${d.size} groups`),g?m.push(`Market: ${g}`):c.size>1&&m.push(`${c.size} markets`)),m.join(" · ")}function gp({row:t}){const s=[...new Set(t.assignments.map(a=>a.queryClass??"unknown"))],n=s.join(", ");return e.jsx(le,{tone:s.includes("unknown")?"caution":"neutral",children:n||"Unknown"})}function fp({row:t}){return t.state==="tracked"?e.jsx(le,{tone:"positive",children:"Measured"}):e.jsx(le,{tone:"caution",children:"Awaiting sweep"})}function yp({workspace:t,templates:s,action:n,draft:a,onDraftChange:r,onClose:o,canReview:i,isPreviewing:d,editorHeadingRef:c,onReview:u}){return n.kind==="remove"?e.jsxs(xe,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{children:"Remove query"}),e.jsxs("p",{className:"mt-1 text-sm leading-6 text-secondary",children:["Remove “",n.row.queryText,"” from future tracking?"]}),e.jsxs("p",{className:"mt-1 text-sm leading-5 text-secondary",children:[n.audience?`Only assignments in ${n.scopeLabel} will be removed.`:"All assignments will be removed."," Earlier results stay unchanged."]})]})}),e.jsx(Xa,{canReview:i,isPreviewing:d,onCancel:o,onReview:u})]}):n.kind==="edit"?e.jsxs(xe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline gap-4",children:[e.jsx("h3",{ref:c,tabIndex:-1,children:"Edit query"}),e.jsx(A,{type:"button",variant:"ghost",size:"sm",onClick:o,children:"Cancel"})]}),e.jsxs("p",{className:"mt-3 text-sm leading-6 text-secondary",children:[n.audience?`Changes apply only to assignments in ${n.scopeLabel}.`:"Changes apply to every assignment of this query."," Earlier results stay unchanged."]}),e.jsxs("div",{className:"mt-4 max-w-2xl space-y-4",children:[e.jsxs("label",{className:"block",htmlFor:"tracking-query-text",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Query text"}),e.jsx("textarea",{id:"tracking-query-text",className:"mt-1 min-h-28 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:a.text,onChange:m=>r({...a,text:m.target.value})})]}),t.mode==="advanced"&&e.jsxs("label",{className:"block",htmlFor:"tracking-query-class",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Classification"}),e.jsxs("select",{id:"tracking-query-class",className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:a.queryClass,onChange:m=>r({...a,queryClass:m.target.value}),children:[e.jsx("option",{value:"keep",children:"Keep existing classifications"}),e.jsx("option",{value:"auto",children:"Automatic"}),e.jsx("option",{value:"branded",children:"Branded"}),e.jsx("option",{value:"non-brand",children:"Non-brand"})]})]}),e.jsx("p",{className:"text-sm leading-6 text-secondary",children:"Existing locations and engines are preserved. Use Add query to create assignments in another scope."})]}),e.jsx(Xa,{canReview:i,isPreviewing:d,onCancel:o,onReview:u})]}):e.jsxs(xe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline gap-4",children:[e.jsx("h3",{ref:c,tabIndex:-1,children:"Add query"}),e.jsx(A,{type:"button",variant:"ghost",size:"sm",onClick:o,children:"Cancel"})]}),e.jsxs("div",{className:"mt-4 grid gap-4 lg:grid-cols-[minmax(250px,0.8fr)_minmax(0,1.2fr)]",children:[e.jsxs("div",{className:"space-y-4",children:[a.source==="manual"?e.jsxs("label",{className:"block",htmlFor:"tracking-query-text",children:[e.jsx("span",{className:"text-sm font-medium text-secondary",children:"Question"}),e.jsx("textarea",{id:"tracking-query-text",className:"mt-1 min-h-28 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",placeholder:"e.g. How do teams compare AEO platforms?",value:a.text,onChange:m=>r({...a,text:m.target.value})})]}):null,a.source==="template"?e.jsx(bp,{templates:s,draft:a,onDraftChange:r}):null,a.source==="research"?e.jsx(Ki,{id:"tracking-research-source",label:"Saved research query",value:a.researchRunQueryId,options:t.savedSources.research.map(m=>({id:m.researchRunQueryId,label:m.queryText,detail:m.researchRunId})),onChange:m=>r({...a,researchRunQueryId:m})}):null,a.source==="discovery"?e.jsx(Ki,{id:"tracking-discovery-source",label:"Discovery query",value:a.discoveryProbeId,options:t.savedSources.discovery.map(m=>({id:m.discoveryProbeId,label:m.queryText,detail:m.discoverySessionId})),onChange:m=>r({...a,discoveryProbeId:m})}):null,e.jsxs("label",{className:"block",htmlFor:"tracking-query-source",children:[e.jsx("span",{className:"text-sm font-medium text-secondary",children:"Query source"}),e.jsxs("select",{id:"tracking-query-source",className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:a.source,onChange:m=>r({...a,source:m.target.value}),children:[e.jsx("option",{value:"manual",children:"Write a question"}),e.jsxs("option",{value:"template",disabled:s.length===0,children:["Saved template",s.length===0?" (none available)":""]}),e.jsxs("option",{value:"research",disabled:t.savedSources.research.length===0,children:["Saved research",t.savedSources.research.length===0?" (none available)":""]}),e.jsxs("option",{value:"discovery",disabled:t.savedSources.discovery.length===0,children:["Discovery result",t.savedSources.discovery.length===0?" (none available)":""]})]})]})]}),e.jsx(jp,{workspace:t,draft:a,onDraftChange:r})]}),t.mode==="advanced"&&!Er(a)?e.jsx("div",{className:"mt-4",children:e.jsx(vp,{workspace:t,draft:a,onDraftChange:r})}):null,e.jsxs("details",{className:"mt-4 border-t border-default text-sm text-secondary",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3",children:"Measurement options"}),e.jsx("div",{className:"grid gap-4 pb-3 sm:grid-cols-2",children:t.mode==="advanced"?e.jsxs("div",{className:"block",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",htmlFor:"tracking-query-class",children:"Classification"}),e.jsxs("select",{id:"tracking-query-class",className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:a.queryClass,onChange:m=>r({...a,queryClass:m.target.value}),children:[e.jsx("option",{value:"auto",children:"Automatic"}),e.jsx("option",{value:"branded",children:"Branded"}),e.jsx("option",{value:"non-brand",children:"Non-brand"})]})]}):e.jsxs("div",{className:"rounded-md border border-default bg-surface-subtle px-3 py-2",children:[e.jsx("p",{className:"text-xs font-medium text-secondary",children:"Classification"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:"Automatic"})]})})]}),a.source==="research"&&e.jsx("p",{className:"mt-4 rounded-md border border-default bg-surface-subtle px-3 py-2 text-sm text-secondary",children:"Only the saved query is added."}),e.jsx(Xa,{canReview:i,isPreviewing:d,onCancel:o,onReview:u})]})}function bp({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":kr(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]}),kr(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 Ki({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 Dr(t){return{providers:[...t.providers],models:{...t.models},location:t.location?.label??null}}function Dn(t){return JSON.stringify({providers:[...t.providers].sort(),models:Object.fromEntries(Object.entries(t.models).sort(([s],[n])=>s.localeCompare(n))),location:t.location})}function pl(t){return[...new Map(t.map(s=>[Dn(s),s])).values()]}function Or(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 vp({workspace:t,draft:s,onDraftChange:n}){const a=l.useMemo(()=>pl([...t.defaultContexts.map(Dr),...s.contexts]),[s.contexts,t.defaultContexts]),r=s.contexts.length===1?Dn(s.contexts[0]):s.contexts.length>1?"__existing__":"";return e.jsxs("label",{className:"block",htmlFor:"tracking-query-context",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Location and engines"}),e.jsxs("select",{id:"tracking-query-context","aria-label":"Location and engines",className:"mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-sm text-strong focus:border-mono-500 focus:outline-none focus:ring-1 focus:ring-mono-500",value:r,onChange:o=>{const i=a.find(c=>Dn(c)===o.target.value),d=o.target.value==="__existing__"?s.contexts:i?[i]:[];n({...s,contexts:d})},children:[e.jsx("option",{value:"",children:"Choose a location and engines"}),s.contexts.length>1?e.jsxs("option",{value:"__existing__",children:["Keep ",s.contexts.length," existing contexts"]}):null,a.map(o=>e.jsx("option",{value:Dn(o),children:Or(o)},Dn(o)))]}),e.jsx("span",{className:"mt-1 block text-xs leading-5 text-secondary",children:a.length===0?"No configured measurement context is available.":"Choose where this query will be measured."})]})}function jp({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),d=l.useMemo(()=>[...t.targets.map(h=>({kind:"target",key:h.stableKey,label:h.label,detail:"Property"})),...t.groups.map(h=>({kind:"group",key:h.stableKey,label:h.label,detail:"Group"})),...t.markets.map(h=>({kind:"market",key:h.stableKey,label:h.label,detail:"Market"}))],[t.groups,t.markets,t.targets]),c=a.trim().toLocaleLowerCase(),u=c?d.filter(h=>`${h.label} ${h.detail}`.toLocaleLowerCase().includes(c)):d,m=s.targetKeys.length+s.groupKeys.length+s.marketKeys.length>0;function x(h,p,y){const j=h==="target"?"targetKeys":h==="group"?"groupKeys":"marketKeys",w=s[j];n({...s,wholeSite:!1,[j]:y?[...w,p]:w.filter(k=>k!==p)})}function g(h,p){return(h==="target"?s.targetKeys:h==="group"?s.groupKeys:s.marketKeys).includes(p)}if(!o){const h=t.targets.find(p=>p.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: ",h?.label??s.targetKeys[0]]}),e.jsx(A,{type:"button",variant:"ghost",size:"sm","aria-label":"Change tracking destination",onClick:()=>i(!0),children:"Change"})]})]})}return e.jsxs("fieldset",{className:"rounded-md border border-default bg-surface-subtle p-3",children:[e.jsx("legend",{className:"px-1 text-xs font-medium text-secondary",children:"Apply to"}),e.jsx("p",{className:"text-sm leading-6 text-secondary",children:"Choose where this question should be tracked."}),e.jsxs("label",{className:"mt-3 flex min-h-9 items-center gap-2 rounded px-1 text-sm text-strong",children:[e.jsx("input",{type:"checkbox",checked:s.wholeSite,onChange:h=>{n({...s,wholeSite:h.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(Bs,{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:u.length===0?e.jsx("p",{className:"px-1 py-2 text-sm text-muted",children:"No assignment matches that search."}):u.map(h=>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":`${h.label}, ${h.detail}`,checked:g(h.kind,h.key),onChange:p=>x(h.kind,h.key,p.target.checked)}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:h.label}),e.jsx("span",{className:"text-xs text-muted",children:h.detail})]},`${h.kind}:${h.key}`))})]})}function Xa({canReview:t,isPreviewing:s,onCancel:n,onReview:a}){return e.jsxs("div",{className:"mt-5 flex flex-wrap items-center gap-3 border-t border-default pt-4",children:[e.jsx(De,{type:"button",size:"sm",disabled:!t,onClick:a,children:s?"Reviewing…":"Review changes"}),e.jsx(A,{type:"button",variant:"ghost",size:"sm",onClick:n,children:"Cancel"}),e.jsx("p",{className:"text-sm leading-5 text-secondary",children:"Publishing does not run a sweep."})]})}function Np({preview:t,workspace:s,isCommitting:n,onConfirm:a}){const r=l.useRef(null);l.useEffect(()=>{const d=r.current;d&&(typeof d.scrollIntoView=="function"&&d.scrollIntoView({block:"start"}),d.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(d=>d.rows.length>0);return e.jsxs(xe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{ref:r,tabIndex:-1,children:o?"Confirm tracked query changes":"No tracking changes"}),e.jsx("p",{className:"mt-1 text-sm leading-6 text-secondary",children:o?"Changes apply to future sweeps. Earlier results stay unchanged.":"This request leaves tracking unchanged."})]}),e.jsx(le,{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(d=>e.jsx(_i,{label:d.label,rows:d.rows,workspace:s,tracked:t.tracked},d.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(_i,{label:"Unchanged",rows:t.diff.unchanged,workspace:s,tracked:t.tracked})]}):null,e.jsxs("details",{className:"mt-4 border-t border-default text-sm text-secondary",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3",children:"Next sweep workload"}),e.jsxs("p",{className:"leading-6",children:["Next sweep: ",t.workload.nextSweepProviderCalls," provider requests (+",t.workload.addedProviderCalls,", −",t.workload.removedProviderCalls,")."]})]}),e.jsx("div",{className:"mt-5 flex flex-wrap items-center gap-3 border-t border-default pt-4",children:e.jsx(De,{type:"button",size:"sm",disabled:!o||n,onClick:a,children:n?"Confirming…":"Confirm changes"})})]})}function _i({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`:Sp(r,a,n)}),t==="Added"||t==="Reused"?e.jsx(wp,{row:a.find(o=>o.queryId===r.queryId),workspace:n}):null]},`${t}:${r.queryId}`))})]})}function wp({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(c=>c.stableKey===a.targetKey)?.label??a.targetKey,i=a.queryClass==="branded"?"Branded":a.queryClass==="non-brand"?"Non-brand":"Unknown",d=a.contexts.map(c=>Or(Dr(c))).join("; ");return e.jsx("li",{children:[o,i,d].filter(Boolean).join(" · ")},`${a.targetKey}:${r}`)})})]})}function Sp(t,s,n){const a=s.find(i=>i.queryId===t.queryId);if(!a)return`${t.assignmentCount} ${t.assignmentCount===1?"assignment":"assignments"}`;const r=pl(a.assignments.flatMap(i=>i.contexts).map(Dr)),o=r.length===1?Or(r[0]):r.length>1?`${r.length} contexts`:null;return[xl(a,n),o].filter(i=>i!==null).join(" · ")}function Cp({projectName:t,selection:s={measurementScope:"project",queryClass:"all"},onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:o,onPendingTrackingSourceHandled:i}){const d=Ns(),[c,u]=l.useState(null),m=we({...Mo({client:W,path:{name:t}})}),x=we({...Uc({client:W,path:{name:t}}),staleTime:6e4}),g=Pt({...Vc(),onSuccess:p=>u(p),onError:async p=>{u(null),await d.invalidateQueries({queryKey:Bc({client:W,path:{name:t}})}),Se({title:"Could not review tracking changes",detail:p instanceof Error?p.message:"Update the draft and review it again.",tone:"negative"})}}),h=Pt({...zc(),onSuccess:async p=>{u(null),r?.(void 0),await ai(d,t),Se({title:p.committed?"Tracked queries updated":"No tracked-query change",detail:p.active?`Measurement revision ${p.active.revision}.`:"No measurement revision is published yet.",tone:p.committed?"positive":"neutral",dedupeKey:`query-tracking:commit:${t}`,dedupeMode:"replace"})},onError:async p=>{u(null),await ai(d,t),Se({title:"Could not confirm tracking changes",detail:p instanceof Error?p.message:"The review may be stale. Review the changes again.",tone:"negative"})}});return m.isLoading?e.jsx(xe,{className:"surface-card",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading tracked queries…"})}):m.isError||!m.data?e.jsxs(xe,{className:"surface-card",children:[e.jsx("p",{className:"text-sm text-negative",children:"Could not load tracked queries."}),e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:()=>{m.refetch()},children:"Try again"})]}):e.jsx(lp,{workspace:m.data,selection:s,onSelectionChange:n,trackingQueryId:a,onTrackingQueryIdChange:r,pendingTrackingSource:o,onPendingTrackingSourceHandled:i,templates:x.data?.templates??[],preview:c,isPreviewing:g.isPending,isCommitting:h.isPending,onPreview:p=>{u(null),g.mutate({client:W,path:{name:t},body:{...p,expectedWorkspaceVersion:m.data.workspaceVersion}})},onCommit:p=>h.mutate({client:W,path:{name:t},body:p})})}function kp({projectName:t,onReviewDiscoveryProbe:s}){const n=Ns(),[a,r]=l.useState(null),[o,i]=l.useState(""),[d,c]=l.useState("100"),u=we({...Qc({client:W,path:{name:t},query:{limit:"10"}}),refetchInterval:k=>k.state.data?.some(C=>Cr.has(C.status))?3e3:!1}),m=u.data??[];l.useEffect(()=>{!a&&m[0]&&r(m[0].id)},[a,m]);const x=m.find(k=>k.id===a)??null,g=we({...Hc({client:W,path:{name:t,id:a??""}}),enabled:!!a,refetchInterval:x&&Cr.has(x.status)?3e3:!1}),h=g.data??null,p=Pt({mutationFn:()=>{const k={},M=o.trim();M&&(k.icpDescription=M);const C=Number.parseInt(d,10);return Number.isFinite(C)&&C>0&&(k.maxProbes=C),Wc(t,k)},onSuccess:async k=>{r(k.sessionId),i(""),await Ip(n,t,k.sessionId),Se({title:"Discovery started",detail:`Run ${Za(k.sessionId)} is testing questions your customers might ask.`,tone:"neutral",dedupeKey:`discovery:start:${k.sessionId}`,dedupeMode:"replace"})},onError:k=>{Se({title:"Discovery failed to start",detail:k instanceof Error?k.message:"Could not start discovery.",tone:"negative"})}}),y=h??x,j=l.useMemo(()=>(h?.probes??[]).slice(0,30),[h?.probes]);async function w(){try{const k=await u.refetch();if(k.error)throw k.error;const M=k.data?.length??0;Se({title:"Discovery sessions refreshed",detail:`${M} recent session${M===1?"":"s"} loaded.`,tone:"positive",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}catch(k){Se({title:"Discovery refresh failed",detail:k instanceof Error?k.message:"Could not reload discovery sessions.",tone:"negative",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}}return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 1"}),e.jsx("h2",{children:"Generate and check questions"}),e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-secondary",children:te()?"Generate customer questions and check whether your site is already visible.":"Generate customer questions, check current visibility, then choose what to track."})]}),e.jsxs(A,{type:"button",variant:"outline",size:"sm",disabled:u.isFetching,onClick:()=>{w()},children:[e.jsx(Na,{className:`size-3.5 ${u.isFetching?"animate-spin":""}`,"aria-hidden":"true"}),"Refresh"]})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[360px_minmax(0,1fr)]",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs(xe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 1"}),e.jsx("h3",{children:"Describe your customer"})]}),e.jsx(le,{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:k=>i(k.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:d,onChange:k=>c(k.target.value)}),e.jsx("span",{className:"mt-1 block text-sm text-secondary",children:"More questions means broader coverage but a longer run. 100 is a good default."})]}),!te()&&e.jsxs(De,{type:"button",size:"sm",disabled:p.isPending,onClick:()=>p.mutate(),children:[e.jsx(Un,{size:14}),p.isPending?"Starting…":"Find queries"]})]})]}),e.jsxs(xe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Recent runs"})]}),u.isFetching&&e.jsx(le,{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(k=>e.jsxs("button",{type:"button",className:`w-full rounded-md border px-3 py-2 text-left transition-colors ${a===k.id?"border-mono-600 bg-bg-elevated/70":"border-default bg-bg/40 hover:border-strong hover:bg-bg-elevated/40"}`,onClick:()=>r(k.id),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:Za(k.id)}),e.jsx(le,{tone:Ui(k.status),children:k.status})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-sm text-secondary",children:[e.jsxs("span",{children:["Cited queries ",k.citedCount??0]}),e.jsxs("span",{children:["Worth tracking ",k.aspirationalCount??0]}),e.jsxs("span",{children:["Skip ",k.wastedCount??0]})]})]},k.id))})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(xe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Run detail"}),e.jsx("h3",{children:y?Za(y.id):"No run selected"})]}),y&&e.jsx(le,{tone:Ui(y.status),children:y.status})]}),y?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(ra,{label:"Questions tested",value:y.probeCount??0}),e.jsx(ra,{label:"Cited queries",value:y.citedCount??0,tone:"positive"}),e.jsx(ra,{label:"Worth tracking",value:y.aspirationalCount??0,tone:"caution"}),e.jsx(ra,{label:"Skip",value:y.wastedCount??0,tone:"negative"})]}),y.error&&e.jsx("div",{className:"rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:y.error}),y.warning&&e.jsx("div",{className:"rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2 text-sm text-caution",children:y.warning}),y.icpDescription&&e.jsxs("div",{className:"rounded-md border border-default bg-surface px-3 py-2",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Customer profile"}),e.jsx("p",{className:"mt-1 text-sm text-neutral",children:y.icpDescription})]}),y.competitorMap.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-sm font-medium text-secondary",children:"Sites that keep getting cited"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:y.competitorMap.slice(0,8).map(k=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[k.domain," ",e.jsx("span",{className:"text-muted",children:k.hits})]},k.domain))})]})]}):e.jsx("p",{className:"text-sm text-secondary",children:"Start a run above, or pick one from Recent runs to see its progress."})]}),y?.status==="completed"&&e.jsxs(xe,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 2"}),e.jsx("h3",{children:"Review a discovery question for tracking"}),e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-secondary",children:"Choose a Cited query or Worth tracking result below. Tracking opens with the saved discovery source, where you choose its scope and review the exact next-sweep change."})]})}),e.jsx("p",{className:"mt-3 text-xs leading-5 text-muted",children:"Discovery remains research. This review does not add competitors or start a sweep."})]}),e.jsxs(xe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"All results"}),e.jsx("h3",{children:"Every question we tested"})]}),g.isFetching&&e.jsx(le,{tone:"neutral",children:"Loading"})]}),j.length===0?e.jsx("p",{className:"text-sm text-muted",children:"Results show up here once the run starts testing questions."}):e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Question"}),e.jsx("th",{children:"Result"}),e.jsx("th",{children:"Sites cited"}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Tracking review"})})]})}),e.jsx("tbody",{children:j.map(k=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:k.query}),e.jsx("td",{children:e.jsx(le,{tone:Ap(k.bucket),children:Rp(k.bucket)})}),e.jsx("td",{className:"text-secondary",children:k.citedDomains.length>0?k.citedDomains.slice(0,3).join(", "):"-"}),e.jsx("td",{className:"whitespace-nowrap text-right",children:!te()&&s&&(k.bucket==="cited"||k.bucket==="aspirational")&&e.jsx(De,{type:"button",variant:"ghost",size:"sm",onClick:()=>s(k.id),children:"Review for tracking"})})]},k.id))})]})})]})]})]})]})}function ra({label:t,value:s,tone:n="neutral"}){const a=n==="positive"?"text-positive":n==="caution"?"text-caution":n==="negative"?"text-negative":"text-heading";return e.jsxs("div",{className:"rounded-md border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:t}),e.jsx("p",{className:`mt-1 text-2xl font-semibold tabular-nums ${a}`,children:s})]})}function Ui(t){return t==="completed"?"positive":t==="failed"?"negative":Cr.has(t)?"caution":"neutral"}function Ap(t){return t==="cited"?"positive":t==="aspirational"?"caution":t==="wasted-surface"?"negative":"neutral"}const Pp={cited:"Cited queries",aspirational:"Worth tracking","wasted-surface":"Skip"};function Rp(t){return t?Pp[t]:"Not classified"}function Za(t){return t.length>8?t.slice(0,8):t}async function Ip(t,s,n){await Promise.all([Nt(t,"discovery"),t.invalidateQueries({queryKey:Yc({client:W})})])}function Bi(t){return`${(t*100).toFixed(1)}%`}function $p({projectName:t}){const[s,n]=l.useState("changes"),[a,r]=l.useState(null),[o,i]=l.useState(null),d=we({...Jc({client:W,path:{name:t},query:{limit:30}}),enabled:s==="health"}),c=we({...Xc({client:W,path:{name:t},query:{kind:"answer-visibility",limit:100}}),enabled:s==="compare"}),u=(c.data??[]).filter(j=>(j.status==="completed"||j.status==="partial")&&j.trigger!=="probe").reverse(),m=o??u[0]?.id??"",x=a??u.find(j=>j.id!==m)?.id??"",g=!!(x&&m&&x!==m),h=we({...Zc({client:W,path:{name:t},query:{run1:x,run2:m}}),enabled:s==="compare"&&g}),p=d.data??[],y=h.data?.diff.filter(j=>j.changed||j.visibilityChanged)??[];return e.jsxs("div",{className:"mt-6",children:[e.jsx("div",{className:"filter-row",role:"tablist","aria-label":"Project history views",children:[["changes","Changes"],["health","Coverage history"],["compare","Compare runs"]].map(([j,w])=>e.jsx("button",{type:"button",role:"tab","aria-selected":s===j,className:`filter-chip ${s===j?"filter-chip-active":""}`,onClick:()=>n(j),children:w},j))}),s==="changes"?e.jsx(wm,{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."})]}),d.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Loading coverage history…"}):null,!d.isLoading&&p.length===0?e.jsxs(xe,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No coverage history yet"}),e.jsx("p",{children:Vt()?Hs:"Complete an answer visibility sweep to create the first snapshot."})]}):null,p.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:p.map(j=>e.jsxs("tr",{children:[e.jsx("td",{className:"whitespace-nowrap tabular-nums text-secondary",children:new Date(j.createdAt).toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[j.mentionedPairs,"/",j.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:Bi(j.overallMentionRate)}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[j.citedPairs,"/",j.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:Bi(j.overallCitedRate)})]},j.id))})]})}):null]}):null,s==="compare"?e.jsxs("section",{className:"mt-6","aria-labelledby":"compare-runs-heading",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Evidence diff"}),e.jsx("h2",{id:"compare-runs-heading",children:"Compare answer visibility runs"}),e.jsx("p",{className:"supporting-copy mt-1",children:"See which tracked queries changed mention or citation state between two sweeps."})]}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"text-xs text-muted",children:["Earlier run",e.jsx("select",{value:x,onChange:j=>r(j.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:u.map(j=>e.jsx("option",{value:j.id,children:new Date(j.createdAt).toLocaleString()},j.id))})]}),e.jsxs("label",{className:"text-xs text-muted",children:["Later run",e.jsx("select",{value:m,onChange:j=>i(j.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:u.map(j=>e.jsx("option",{value:j.id,children:new Date(j.createdAt).toLocaleString()},j.id))})]})]}),c.isLoading||h.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Comparing runs…"}):null,!c.isLoading&&u.length<2?e.jsxs(xe,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"Two completed sweeps are required"}),e.jsx("p",{children:Vt()?Hs:"Run another answer visibility sweep before comparing historical evidence."})]}):null,h.data&&y.length===0?e.jsxs(xe,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No mention or citation changes"}),e.jsx("p",{children:"The selected sweeps have the same states for every comparable tracked query."})]}):null,y.length>0?e.jsx("div",{className:"evidence-table-wrap mt-4",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Citation"}),e.jsx("th",{children:"Mention"})]})}),e.jsx("tbody",{children:y.map(j=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:j.query??"Archived query"}),e.jsx("td",{children:e.jsxs(le,{tone:j.changed?"caution":"neutral",children:[j.run1State??"none"," → ",j.run2State??"none"]})}),e.jsx("td",{children:e.jsxs(le,{tone:j.visibilityChanged?"caution":"neutral",children:[j.run1MentionState??"none"," → ",j.run2MentionState??"none"]})})]},j.queryId??j.query??"unknown"))})]})}):null]}):null]})}const Vi={state:"not-connected",selection:null,snapshotCount:0,evidence:"No stored evidence yet.",lastSnapshotAt:null},Tp={contract:null,assessment:null,googleAds:Vi,gtm:Vi,snapshots:[]};function Mp(t){return t.contractSelectionRequired?"contract-selection-required":t.assessmentState==="loading"?"assessment-loading":t.assessmentState==="unavailable"?"assessment-unavailable":Dp(t)?"static-mismatch":t.assessment?.status??(t.contract?"configured":"not-configured")}function Lp(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 qp(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 Ep(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 gl(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"&&Op(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 Dp(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome==="fail")}function Op(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome!=="pass")}function fl(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 Fp(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 Gp(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 an(t){return t.length<=12?t:`…${t.slice(-10)}`}function Kp(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 _p(t){const s=[];return t.runtime.requireTransactionId&&s.push("transaction ID"),t.runtime.requireValue&&s.push("value"),t.runtime.requireCurrency&&s.push("currency"),s.length>0?s.join(", "):"No additional event fields required"}const er={"ads-connection-missing":"Google Ads connection is available","ads-conversion-action-missing":"Google Ads conversion action exists and is enabled","ads-goal-missing":"Google Ads goal includes the conversion action","ads-goal-not-biddable":"Google Ads goal is available for bidding","ads-action-not-primary":"Google Ads action is primary","gtm-connection-missing":"Tag Manager connection is available","gtm-live-graph-missing":"Tag Manager configuration is available","gtm-tag-missing":"Required Tag Manager tag exists","gtm-tag-unrecognized":"Tag Manager tag type is supported","gtm-tag-paused":"Tag Manager tag is active","gtm-trigger-missing":"Required Tag Manager trigger is linked","gtm-variable-missing":"Required Tag Manager variable is linked","gtm-event-mismatch":"Tag Manager event matches the declaration","gtm-hostname-mismatch":"Tag Manager host matches the production site","gtm-value-mapping-missing":"Conversion value mapping is present","gtm-transaction-id-mapping-missing":"Transaction ID mapping is present","gtm-currency-mapping-missing":"Currency mapping is present","gtm-conversion-id-mismatch":"Google conversion ID matches","gtm-conversion-label-mismatch":"Google conversion label matches","runtime-event-not-observed":"Website event was observed","runtime-gtm-not-observed":"Tag Manager firing was observed","runtime-ads-not-observed":"Google Ads conversion was observed"};function zi(t){return t.outcome==="pass"?{label:er[t.code],tone:"positive",outcome:"Pass"}:t.outcome==="fail"?{label:er[t.code],tone:"negative",outcome:"Fail"}:{label:er[t.code],tone:"caution",outcome:"Unknown"}}function Up(t){return t.runtime.productionHosts.length>0?t.runtime.productionHosts.join(", "):"the declared production site"}function Bp(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 Vp(t){return t.provider==="google-ads"?"Google Ads":"Tag Manager"}function Qi({label:t,connection:s,changeSelectionLabel:n,onChangeSelection:a,actionPending:r}){const o=fl(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(le,{tone:o.tone,children:o.label})}),e.jsx("td",{className:"text-secondary",children:s.selection??"No selection"}),e.jsxs("td",{children:[e.jsx("p",{className:"text-secondary",children:s.evidence}),i?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:i}):e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:[s.snapshotCount," stored ",s.snapshotCount===1?"snapshot":"snapshots",s.lastSnapshotAt?`, latest ${Bt(s.lastSnapshotAt)}`:""]}),s.snapshotError?e.jsx("p",{role:"alert",className:"mt-1 text-sm text-negative",children:s.snapshotError}):null]}),e.jsx("td",{children:n&&a?e.jsx(De,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:a,children:n}):e.jsx("span",{className:"text-sm text-secondary",children:"Use the next step above"})})]})}const zp="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.",Qp="Available once Google Ads and Tag Manager are connected.",Hp="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 Wp({workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:n,onChangeGtmSelection:a,actionPending:r,actionError:o}){const i=t.googleAds.state==="connected",d=t.gtm.state==="connected",c=t.googleAds.state==="unavailable",u=t.gtm.state==="unavailable",m=c||u||t.gtm.state==="unavailable",x={id:"retry-connection-status",label:"Retry connection status",detail:"Retry the stored connection reads before starting another provider action."},g=!i&&!d,h=[{title:"Google Ads",state:t.googleAds.state,ready:i,summary:t.googleAds.selection,changeLabel:"Change Google Ads account",onChange:n,action:c?x:qp(t)},{title:"Tag Manager",state:t.gtm.state,ready:d,summary:t.gtm.selection,changeLabel:"Change Tag Manager container",onChange:a,action:u?x:Ep(t)}],p=i&&d&&!m?gl(t):null;return e.jsxs("section",{className:"page-section","aria-labelledby":"conversion-integrity-title",children:[e.jsx("div",{className:"section-head mb-4",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx("h2",{id:"conversion-integrity-title",className:"text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsx(Me,{text:"Canonry reads your Google configuration and never changes or publishes it. Connect Google Ads and Tag Manager, then choose one website conversion to check across both."})]}),g?e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-secondary",children:Hp}):null]})}),e.jsxs("div",{className:"max-w-3xl",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 border-y border-default py-4",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Conversion to check"}),e.jsx(Me,{text:zp})]}),p&&s?e.jsx(De,{type:"button",disabled:r,onClick:()=>s(p.id),children:r?"Working…":p.label}):e.jsx("p",{className:"text-sm text-secondary",children:Qp})]}),e.jsx("ul",{className:"flex flex-wrap items-center gap-x-6 gap-y-2 border-b border-default py-3",children:h.map(y=>{const j=y.ready?{label:"Ready",tone:"positive"}:fl(y.state),w=y.action;return e.jsxs("li",{className:"flex min-w-0 flex-wrap items-center gap-2 text-sm",children:[e.jsx("span",{className:"font-medium text-heading",children:y.title}),e.jsx(le,{tone:j.tone,children:j.label}),y.summary?e.jsx("span",{className:"min-w-0 truncate text-secondary",children:y.summary}):null,w&&s?w.id==="retry-connection-status"?e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(w.id),children:r?"Working…":w.label}):e.jsx(De,{type:"button",variant:"outline",size:"sm",disabled:r,onClick:()=>s(w.id),children:r?"Working…":w.label}):null,y.summary&&y.onChange?e.jsx(De,{type:"button",variant:"ghost",size:"sm","aria-label":y.changeLabel,disabled:r,onClick:y.onChange,children:"Change"}):null]},y.title)})}),o?e.jsx("p",{role:"alert",className:"mt-3 text-sm text-negative",children:o}):null]})]})}function Yp({workspace:t=Tp,onPrimaryAction:s,actionPending:n=!1,actionError:a=null,contracts:r=[],selectedContractId:o=null,onSelectContract:i,contractError:d=null,onRetryContracts:c,onRetryEvidence:u,onChangeGoogleAdsSelection:m,onChangeGtmSelection:x,onAddContract:g}){const h=Mp(t),p=Lp(h),y=gl(t),j=t.assessment?.findings??[],w=j.filter(f=>f.outcome!=="pass"),k=j.filter(f=>f.outcome==="pass"),M=w.some(f=>f.outcome==="fail")?"negative":"caution";return r.length===0&&t.contract===null&&!t.contractSelectionRequired&&d===null?e.jsx(Wp,{workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:m,onChangeGtmSelection:x,actionPending:n,actionError:a}):e.jsxs("section",{className:"page-section","aria-labelledby":"conversion-integrity-title",children:[e.jsx("div",{className:"section-head mb-5",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsx("h2",{id:"conversion-integrity-title",className:"mt-1 text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsx("p",{className:"lede mt-2",children:"Follow one declared website event through Tag Manager, Google Ads, and the evidence Canonry can verify."})]})}),e.jsxs("div",{className:"flex flex-col gap-4 border-y border-default py-5 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(le,{tone:p.tone,children:p.label}),t.assessment?.evaluatedAt?e.jsxs("span",{className:"text-[11px] text-muted",children:["Assessed ",Bt(t.assessment.evaluatedAt)]}):null]}),e.jsx("p",{className:"supporting-copy mt-2 max-w-2xl",children:p.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(f=>e.jsxs("li",{className:"break-words",children:[Vp(f)," ",f.kind,", captured ",Bt(f.capturedAt),e.jsxs("span",{className:"ml-1 font-mono text-[11px] text-muted",children:["(",f.id,")"]})]},f.id))})]}):null]}),e.jsxs("div",{className:"shrink-0 lg:max-w-xs",children:[s?y.id==="review-findings"||y.id==="review-runtime-verification"||y.id==="retry-connection-status"||y.id==="select-contract"||y.id==="retry-integrity"||y.id==="waiting-for-integrity"?e.jsx(A,{type:"button",disabled:n||y.id==="waiting-for-integrity",onClick:()=>s(y.id),children:n?"Working…":y.label}):e.jsx(De,{type:"button",disabled:n,onClick:()=>s(y.id),children:n?"Working…":y.label}):y.id==="review-findings"?e.jsx(A,{asChild:!0,type:"button",children:e.jsx("a",{href:"#conversion-integrity-findings",children:"Review findings"})}):h==="runtime-unverified"?e.jsx(A,{asChild:!0,type:"button",children:e.jsx("a",{href:"#conversion-integrity-runtime-guidance",children:"Review runtime verification"})}):null,e.jsx("p",{className:"mt-2 text-sm leading-5 text-secondary",children:y.detail}),a?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:a}):null]})]}),e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-contract-title",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Declared conversion"}),e.jsx("h3",{id:"conversion-integrity-contract-title",className:"min-w-0 break-words text-base font-semibold text-heading",children:t.contract?.name??(t.contractSelectionRequired?"Choose a conversion":"No conversion declared")})]}),r.length>0&&g?e.jsx(De,{type:"button",variant:"outline",size:"sm",disabled:n,onClick:g,children:"Add conversion"}):null]}),r.length>1?e.jsxs("label",{htmlFor:"conversion-integrity-contract-select",className:"mb-5 block max-w-xl text-sm font-medium text-secondary",children:["Conversion to inspect",e.jsxs("select",{id:"conversion-integrity-contract-select",className:"mt-1 w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-heading outline-none transition-colors focus:border-mono-500 focus:ring-2 focus:ring-mono-500/30",value:o??"",onChange:f=>i?.(f.target.value),children:[e.jsx("option",{value:"",children:"Choose a declared conversion"}),r.map(f=>e.jsx("option",{value:f.id,children:f.name},f.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:Kp(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:_p(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:an(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:an(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:an(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:an(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."}),d?e.jsxs("div",{role:"alert",className:"mt-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:d}),c?e.jsx(A,{type:"button",variant:"outline",onClick:c,children:"Retry contracts"}):null]}):null,t.assessmentError?e.jsx("p",{role:"alert",className:"mt-4 text-sm text-negative",children:t.assessmentError}):null]}),w.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(le,{tone:M,children:[w.length," ",w.length===1?"check":"checks"]})]}),e.jsx("ul",{className:"divide-y divide-default border-y border-default",children:w.map(f=>{const v=zi(f);return e.jsxs("li",{className:"py-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"min-w-0 break-words text-sm font-medium text-heading",children:v.label}),e.jsx(le,{tone:v.tone,children:v.outcome})]}),e.jsxs("p",{className:"mt-1 break-words text-sm text-secondary",children:["Related item: ",f.subject]}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",f.code]}),f.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",f.evidenceIds.join(", ")]}):null]},`${f.code}:${f.subject}`)})})]}):null,e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-progression-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h3",{id:"conversion-integrity-progression-title",className:"text-base font-semibold text-heading",children:"Evidence progression"}),e.jsx(Me,{text:"Configured means a contract exists. Static configuration is checked only against saved Google Ads and Tag Manager evidence. Observed requires separate runtime evidence."})]})}),e.jsx("ol",{className:"divide-y divide-default border-y border-default",children:[{key:"configured",title:"Declared",detail:"The event and provider identifiers are recorded in one project contract."},{key:"static",title:"Static configuration",detail:"Sanitized Google Ads and Tag Manager snapshots are compared with that contract."},{key:"runtime",title:"Runtime observation",detail:"A real browser event, tag firing, and recorded conversion are verified separately."}].map(f=>{const v=Fp(f.key,h);return e.jsxs("li",{className:"grid gap-3 py-3 sm:grid-cols-[minmax(10rem,0.7fr)_minmax(0,1fr)_auto] sm:items-center",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{"aria-hidden":"true",className:`size-2 rounded-full ${v==="positive"?"bg-positive-fill":v==="caution"?"bg-caution-fill":v==="negative"?"bg-negative-fill":"bg-neutral-fill"}`}),e.jsx("span",{className:"text-sm font-medium text-heading",children:f.title})]}),e.jsx("p",{className:"text-sm text-secondary",children:f.detail}),e.jsx(le,{tone:v,children:Gp(f.key,h)})]},f.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:[Qi({label:"Google Ads",connection:t.googleAds,...t.googleAds.state==="connected"||t.googleAds.state==="stale"?{changeSelectionLabel:"Change Google Ads account",onChangeSelection:m}:{},actionPending:n}),Qi({label:"Google Tag Manager",connection:t.gtm,...t.gtm.state==="connected"||t.gtm.state==="stale"?{changeSelectionLabel:"Change Tag Manager container",onChangeSelection:x}:{},actionPending:n})]})]})}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-caution",children:"Static API evidence does not prove that a browser tag fired or that Google Ads recorded a conversion."}),(t.googleAds.snapshotError||t.gtm.snapshotError)&&u?e.jsx(A,{type:"button",variant:"outline",className:"mt-3",onClick:u,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(f=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:f.provider==="google-ads"?"Google Ads":"Google Tag Manager"}),e.jsx("td",{className:"text-secondary",children:f.kind}),e.jsx("td",{className:"text-secondary",children:Bt(f.capturedAt)}),e.jsx("td",{className:"font-mono text-[11px] text-muted",children:an(f.id)})]},f.id))})]})})]}):null,k.length>0?e.jsxs("details",{className:"inline-disclosure mt-8",children:[e.jsxs("summary",{children:[k.length," ",k.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:k.map(f=>{const v=zi(f);return e.jsxs("tr",{children:[e.jsxs("td",{className:"text-secondary",children:[e.jsx("p",{children:v.label}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",f.code]}),f.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",f.evidenceIds.join(", ")]}):null]}),e.jsx("td",{children:e.jsx(le,{tone:v.tone,children:v.outcome})}),e.jsx("td",{className:"break-words text-secondary",children:f.subject})]},`${f.code}:${f.subject}`)})})]})})]}):null,h==="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 ",Up(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:an(t.contract.gtm.tagId)})," fires with ",Bp(t.contract),"."]}),e.jsxs("li",{children:["Confirm Google Ads records the matching conversion action ",e.jsx("span",{className:"font-mono text-heading",children:an(t.contract.googleAds.conversionActionId)}),". Do not change the account or publish a Tag Manager version just to verify it."]})]})]}):null]})}const rn=3e4,Hi={name:"",eventName:"",conversionActionId:"",conversionId:"",conversionLabel:"",campaignIds:"",tagId:"",triggerIds:"",variableIds:"",productionHosts:"",requireBiddableGoal:!0,requirePrimaryAction:!0,verificationRequired:!0,requireTransactionId:!0,requireValue:!0,requireCurrency:!0},At="mt-1 w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-heading outline-none transition-colors placeholder-mono-600 focus:border-mono-500 focus:ring-2 focus:ring-mono-500/30",as="text-sm font-medium text-secondary";function Wi(t,s,n,a){return n?{snapshotCount:t,snapshotState:"unavailable",snapshotError:mt(a)}:s?{snapshotCount:t,snapshotState:"loading"}:{snapshotCount:t}}function ia(t){return[...new Set(t.split(/[\n,]/).map(s=>s.trim()).filter(Boolean))]}function Jp(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 Xp(t,s,n){const a=[`Container ${t}`,`account ${s}`];return n&&a.push(`workspace ${n}`),a.join(" · ")}function Zp(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:Xp(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 eg(t,s,n){return{name:t.name.trim(),eventName:t.eventName.trim(),googleAds:{customerId:s,conversionActionId:t.conversionActionId.trim(),...t.conversionId.trim()?{conversionId:t.conversionId.trim()}:{},...t.conversionLabel.trim()?{conversionLabel:t.conversionLabel.trim()}:{},campaignIds:ia(t.campaignIds),requireBiddableGoal:t.requireBiddableGoal,requirePrimaryAction:t.requirePrimaryAction},gtm:{accountId:n.accountId,containerId:n.containerId,tagId:t.tagId.trim(),triggerIds:ia(t.triggerIds),variableIds:ia(t.variableIds)},runtime:{verificationRequired:t.verificationRequired,requireTransactionId:t.requireTransactionId,requireValue:t.requireValue,requireCurrency:t.requireCurrency,productionHosts:ia(t.productionHosts)}}}function Yi(t,s){const n=window.open(t,"_blank","width=600,height=700");if(!n){window.location.assign(t);return}const a=window.setInterval(()=>{n.closed&&(window.clearInterval(a),s())},1e3)}function oa(t,s,n){if(!s)return null;const a=s.totalAccessible===1?t:`${t}s`;return s.truncated?`Incomplete result: showing ${n} of ${s.totalAccessible} accessible ${a}. Use the CLI or API if the resource is not shown.`:`${s.totalAccessible} accessible ${a} found.`}function la(t,s,n){return t?"no longer accessible":n?"access not verified":s?"not in the current result":"checking access"}function ca({id:t,label:s,value:n,onChange:a,children:r,disabled:o=!1}){return e.jsxs("label",{htmlFor:t,className:as,children:[s,e.jsx("select",{id:t,className:At,value:n,onChange:i=>a(i.target.value),disabled:o,children:r})]})}function bn({id:t,checked:s,onChange:n,children:a}){return e.jsxs("label",{htmlFor:t,className:"flex items-start gap-2 text-sm text-secondary",children:[e.jsx("input",{id:t,type:"checkbox",checked:s,onChange:r=>n(r.target.checked),className:"mt-0.5 size-4 rounded border-base bg-bg accent-mono-100"}),e.jsx("span",{children:a})]})}function Ji({providerLabel:t,disabled:s,onDisconnect:n}){const[a,r]=l.useState(!1),[o,i]=l.useState(!1),[d,c]=l.useState(null),u=l.useRef(null),m=l.useRef(null),x=l.useRef(!1);l.useEffect(()=>{const y=x.current;x.current=a,a?m.current?.focus():y&&u.current?.querySelector("button")?.focus()},[a]);function g(){c(null),r(!0)}function h(){c(null),r(!1)}async function p(){i(!0),c(null);try{await n()}catch(y){c(mt(y)),i(!1)}}return e.jsx("div",{ref:u,className:"mt-5 border-t border-subtle pt-4",children:a?e.jsxs("div",{role:"group","aria-label":`Confirm disconnect ${t}`,className:"max-w-2xl",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"Remove Canonry's stored access and selection?"}),e.jsx("p",{className:"mt-1 text-sm leading-6 text-secondary",children:"Saved evidence and conversion contracts remain. New checks stop until you reconnect."}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(A,{ref:m,type:"button",variant:"outline",size:"sm",className:"min-h-11",disabled:o,onClick:h,children:"Keep connected"}),e.jsx(De,{type:"button",variant:"destructive",size:"sm",className:"min-h-11",disabled:s||o,onClick:()=>{p()},children:o?"Disconnecting…":`Disconnect ${t}`})]}),d?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:d}):null]}):e.jsxs(De,{type:"button",variant:"ghost",size:"sm",className:"min-h-11 text-negative hover:text-negative",disabled:s,onClick:g,children:["Disconnect ",t]})})}function Xi({id:t,label:s,options:n,synced:a,loading:r,failed:o,onRetry:i,emptyHint:d,value:c,onChange:u}){const m=n.some(y=>y.id===c),[x,g]=l.useState(!1),h=x||c!==""&&!m&&n.length>0,p=e.jsx("label",{htmlFor:t,className:as,children:s});return r?e.jsxs("div",{children:[p,e.jsx("select",{id:t,className:At,disabled:!0,children:e.jsx("option",{children:"Loading…"})})]}):o?e.jsxs("div",{children:[p,e.jsx("input",{id:t,required:!0,className:At,value:c,onChange:y=>u(y.target.value)}),e.jsxs("p",{className:"mt-1 text-xs text-negative",children:["Could not load the list."," ",e.jsx("button",{type:"button",className:"text-link underline",onClick:i,children:"Retry"})]})]}):!a||n.length===0?e.jsxs("div",{children:[p,e.jsx("input",{id:t,required:!0,className:At,value:c,onChange:y=>u(y.target.value)}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:a?"Synced, but nothing to choose from yet.":d})]}):e.jsxs("div",{children:[p,h?e.jsx("input",{id:t,required:!0,className:At,value:c,onChange:y=>u(y.target.value)}):e.jsxs("select",{id:t,required:!0,className:At,value:c,onChange:y=>u(y.target.value),children:[e.jsxs("option",{value:"",children:["Select ",s.toLowerCase()]}),n.map(y=>e.jsxs("option",{value:y.id,children:[y.name,y.detail?` (${y.detail})`:"",y.active?"":" — inactive"]},y.id))]}),e.jsx("button",{type:"button",className:"mt-1 text-xs text-link",onClick:()=>{g(!h),u("")},children:h?"Choose from synced list":"Enter an ID manually"})]})}function tg({projectId:t,projectName:s}){const n=Hn(),[a,r]=l.useState(null),[o,i]=l.useState(null),[d,c]=l.useState(!1),[u,m]=l.useState(""),[x,g]=l.useState(null),[h,p]=l.useState(!1),[y,j]=l.useState(!1),[w,k]=l.useState(""),[M,C]=l.useState(""),[f,v]=l.useState(""),[S,R]=l.useState(""),[E,L]=l.useState(""),[B,U]=l.useState(!1),[T,N]=l.useState(Hi),[D,J]=l.useState(null),G=l.useRef(null),Z=we({...ed({client:W,path:{name:s}}),staleTime:rn}),de=we({...td({client:W,path:{name:s}}),staleTime:rn}),se=we({...sd({client:W,path:{name:s}}),staleTime:rn}),Q=we({...nd({client:W,path:{name:s}}),staleTime:rn}),$=Q.data,ie=we({...ad({client:W,path:{name:s},query:{limit:5}}),staleTime:rn}),O=we({...rd({client:W,path:{name:s},query:{limit:5}}),staleTime:rn}),_=se.data??[],ge=(D?_.find(P=>P.id===D)??null:null)??(_.length===1?_[0]??null:null),H=_.length>1&&!ge,ae=we({...id({client:W,path:{name:s,contractId:ge?.id??""}}),enabled:!!ge,staleTime:rn}),ue=we({...od({client:W,path:{name:s}}),enabled:x==="google-ads"&&Z.data?.connected===!0,staleTime:0}),Oe=we({...ld({client:W,path:{name:s}}),enabled:x==="gtm"&&de.data?.connected===!0,staleTime:0}),Fe=we({...cd({client:W,path:{name:s,accountId:f}}),enabled:x==="gtm"&&!!f,staleTime:0}),Pe=we({...dd({client:W,path:{name:s,accountId:f,containerId:S}}),enabled:x==="gtm"&&!!f&&!!S,staleTime:0}),tt=Pt(ud({client:W})),it=Pt(md({client:W})),ke=Pt(hd({client:W})),Xe=Pt(xd({client:W})),_e=Pt(pd({client:W})),Ve=Pt(gd({client:W})),He=Pt(fd({client:W})),Te=Pt(yd({client:W})),V=Pt(bd({client:W}));l.useEffect(()=>{if(x!=="google-ads"||h||!Z.isSuccess)return;const P=Z.data.connection?.selection;k(P?.customerId??""),C(P?.loginCustomerId??""),p(!0)},[h,Z.data,Z.isSuccess,x]),l.useEffect(()=>{if(x!=="gtm"||y||!de.isSuccess)return;const P=de.data.selection;v(P?.accountId??""),R(P?.containerId??""),L(P?.workspaceId??""),j(!0)},[y,de.data,de.isSuccess,x]),l.useEffect(()=>{!D||!se.data||se.data.some(P=>P.id===D)||J(null)},[se.data,D]);const F=l.useMemo(()=>{const P=ie.data?.snapshots??[],me=O.data?.snapshots??[],st=[...P.map(_t=>({id:_t.id,provider:"google-ads",kind:_t.kind,capturedAt:_t.capturedAt})),...me.map(_t=>({id:_t.id,provider:"gtm",kind:_t.kind,capturedAt:_t.capturedAt}))].sort((_t,Yt)=>Yt.capturedAt.localeCompare(_t.capturedAt)).slice(0,5),Ae=[],ut=ae.data?.googleAdsSnapshot,ds=ae.data?.gtmSnapshot;return ut&&Ae.push({id:ut.id,provider:"google-ads",kind:ut.kind,capturedAt:ut.capturedAt}),ds&&Ae.push({id:ds.id,provider:"gtm",kind:ds.kind,capturedAt:ds.capturedAt}),{contract:ae.data?.assessment.contract??ge,assessment:ae.data?.assessment??null,contractSelectionRequired:H,assessmentState:ge?ae.isError?"unavailable":ae.isLoading?"loading":void 0:void 0,assessmentError:ae.isError?mt(ae.error):null,googleAds:Jp(Z.data,Wi(ie.data?.total??0,ie.isLoading,ie.isError,ie.error),Z.isError),gtm:Zp(de.data,Wi(O.data?.total??0,O.isLoading,O.isError,O.error),de.isError),snapshots:st,assessmentEvidenceSnapshots:Ae}},[ge,H,ie.data,ie.error,ie.isError,ie.isLoading,Z.data,Z.isError,O.data,O.error,O.isError,O.isLoading,de.data,de.isError,ae.data,ae.error,ae.isError,ae.isLoading]),z=l.useSyncExternalStore(Io,ba,ba),Ne=Object.values(z.runs).some(P=>P.projectId===t&&(P.kind===Qs["google-ads-sync"]||P.kind===Qs["gtm-sync"])),Ie=tt.isPending||it.isPending||ke.isPending||Xe.isPending||_e.isPending||Ve.isPending||He.isPending||Te.isPending||V.isPending||Ne;async function ee(){await Promise.all([Z.refetch(),de.refetch(),se.refetch(),ie.refetch(),O.refetch(),Q.refetch(),ge?ae.refetch():Promise.resolve()])}async function We(P){await ee();for(let me=0;me<10&&!P();me+=1)await new Promise(st=>setTimeout(st,1500)),await ee()}function ht(){const P=document.activeElement;G.current=P instanceof HTMLElement?P:null}function Ze(P){if(typeof window<"u"&&typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame(P);return}globalThis.setTimeout(P,0)}function ye(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Ge(P){if(!P)return;!P.matches('a[href], button, input, select, textarea, [contenteditable="true"]')&&!P.hasAttribute("tabindex")&&(P.tabIndex=-1),P.focus({preventScroll:!0})}function It(P,me=P){const st=document.getElementById(P);st instanceof HTMLDetailsElement&&(st.open=!0);const Ae=st?.scrollIntoView;typeof Ae=="function"&&Ae.call(st,{behavior:ye()?"auto":"smooth",block:"start"}),Ge(document.getElementById(me)??st)}function xt(P,me){ht(),Ze(()=>It(P,me))}function qe(){const P=G.current;G.current=null,P&&Ze(()=>{P.isConnected&&P.focus({preventScroll:!0})})}function Ye(){r(null),c(!1),qe()}function pt(){r(null),g(null),qe()}function St(){r(null),U(!1),qe()}function Ke(){r(null),g(null),c(!0),xt("google-ads-connect-panel","google-ads-connect-title")}function Le(){r(null),k(""),C(""),p(!1),g("google-ads"),c(!1),xt("google-ads-selection-panel","google-ads-selection-title")}function et(){r(null),v(""),R(""),L(""),j(!1),g("gtm"),c(!1),xt("gtm-selection-panel","gtm-selection-title")}function Ue(){r(null),U(!0),xt("conversion-integrity-contract-form","conversion-integrity-contract-form-title")}function Be(P,me){Ro({id:P.id,projectId:P.projectId,kind:P.kind,projectLabel:s,sourceAction:me}),Se({title:me==="google-ads-sync"?"Google Ads sync queued":"Tag Manager sync queued",detail:`${s} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`google-marketing-sync:${P.id}`,dedupeMode:"replace"})}async function $t(){fs(n),r(null);try{const P=await tt.mutateAsync({path:{name:s},body:{provider:"google-ads",...u.trim()?{developerToken:u.trim()}:{}}});m(""),c(!1),i("Finish the Google Ads consent flow in the new window. Canonry will refresh stored status after it closes."),Yi(P.authorizationUrl,()=>{ee(),i(null),qe()})}catch(P){r(mt(P))}}async function vt(){fs(n),r(null);try{const P=await it.mutateAsync({path:{name:s},body:{provider:"gtm"}});i("Finish the Tag Manager consent flow in the new window. Canonry will refresh stored status after it closes."),Yi(P.authorizationUrl,()=>{ee(),i(null),qe()})}catch(P){r(mt(P))}}async function Ft(){if(fs(n),!w){r("Select a Google Ads customer before saving.");return}r(null);try{await ke.mutateAsync({path:{name:s},body:{customerId:w,...M.trim()?{loginCustomerId:M.trim()}:{}}}),g(null),qe(),await We(()=>Z.data?.selectedCustomer!=null)}catch(P){r(mt(P))}}async function gt(){if(fs(n),!f||!S){r("Select a Tag Manager account and container before saving.");return}r(null);try{await Xe.mutateAsync({path:{name:s},body:{accountId:f,containerId:S,...E?{workspaceId:E}:{}}}),g(null),qe(),await We(()=>de.data?.status==="connected")}catch(P){r(mt(P))}}async function Y(){fs(n),r(null),await He.mutateAsync({path:{name:s}}),g(null),c(!1),k(""),C(""),p(!1),i(null),await ee(),Se({title:"Google Ads disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`google-ads-disconnected:${t}`,dedupeMode:"replace"}),G.current=null,Ze(()=>Ge(document.getElementById("conversion-integrity-title")))}async function Re(){fs(n),r(null),await Te.mutateAsync({path:{name:s}}),g(null),v(""),R(""),L(""),j(!1),i(null),await ee(),Se({title:"Tag Manager disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`gtm-disconnected:${t}`,dedupeMode:"replace"}),G.current=null,Ze(()=>Ge(document.getElementById("conversion-integrity-title")))}async function be(){fs(n),r(null);try{const P=await _e.mutateAsync({path:{name:s}});Be(P,"google-ads-sync")}catch(P){r(mt(P))}}async function je(){fs(n),r(null);try{const P=await Ve.mutateAsync({path:{name:s}});Be(P,"gtm-sync")}catch(P){r(mt(P))}}async function Gt(){fs(n),r(null);try{const P=await Promise.allSettled([_e.mutateAsync({path:{name:s}}),Ve.mutateAsync({path:{name:s}})]),[me,st]=P;me.status==="fulfilled"&&Be(me.value,"google-ads-sync"),st.status==="fulfilled"&&Be(st.value,"gtm-sync");const Ae=P.find(ut=>ut.status==="rejected");if(Ae?.status==="rejected")throw Ae.reason}catch(P){r(mt(P))}}async function ze(){fs(n);const P=Z.data?.connection?.selection.customerId,me=de.data?.selection;if(!P||!me?.accountId||!me.containerId){r("Select Google Ads and Tag Manager resources before declaring a conversion.");return}r(null);try{const st=await V.mutateAsync({path:{name:s},body:eg(T,P,{accountId:me.accountId,containerId:me.containerId})});N(Hi),U(!1),qe(),(await se.refetch()).data?.some(ut=>ut.id===st.id)&&J(st.id)}catch(st){r(mt(st))}}function ft(P){switch(P){case"connect-google-ads":Ke();return;case"connect-gtm":ht(),vt();return;case"select-google-ads":Le();return;case"select-gtm":et();return;case"sync-google-ads":be();return;case"sync-gtm":je();return;case"sync-static-evidence":Gt();return;case"declare-contract":Ue();return;case"review-findings":xt("conversion-integrity-findings","conversion-integrity-findings");return;case"review-runtime-verification":xt("conversion-integrity-runtime-guidance","conversion-integrity-runtime-title");return;case"retry-connection-status":ee();return;case"select-contract":xt("conversion-integrity-contract-select","conversion-integrity-contract-select");return;case"retry-integrity":ae.refetch();return;case"waiting-for-integrity":return}}const Tt=ue.data?.customers??[],ls=Oe.data?.accounts??[],Mt=Fe.data?.containers??[],Kt=Pe.data?.workspaces??[],ot=!!w&&!Tt.some(P=>P.customerId===w),cs=!!f&&!ls.some(P=>P.id===f),Ct=!!S&&!Mt.some(P=>P.id===S),Ts=!!E&&!Kt.some(P=>P.id===E),zt=ot&&ue.isSuccess&&ue.data.truncated===!1,Zt=cs&&Oe.isSuccess&&Oe.data.truncated===!1,Qt=Ct&&Fe.isSuccess&&Fe.data.truncated===!1,dt=Ts&&Pe.isSuccess&&Pe.data.truncated===!1,ws=Zt||Qt||dt,Ht=Zt?"The saved Tag Manager account is no longer accessible. Choose an available account before saving.":Qt?"The saved Tag Manager container is no longer accessible. Choose an available container before saving.":dt?"The saved draft workspace is no longer accessible. Choose an available workspace or No draft workspace before saving.":null,ct=la(zt,ue.data,ue.isError),ms=la(Zt,Oe.data,Oe.isError),jt=la(Qt,Fe.data,Fe.isError),es=la(dt,Pe.data,Pe.isError),hs=ue.isError?mt(ue.error):null,xs=Oe.isError?mt(Oe.error):Fe.isError?mt(Fe.error):Pe.isError?mt(Pe.error):null,Lt=x==="google-ads"?hs:x==="gtm"?xs:null,q=oa("customer",ue.data,Tt.length),ne=oa("account",Oe.data,ls.length),fe=oa("container",Fe.data,Mt.length),re=oa("draft workspace",Pe.data,Kt.length),oe=Oe.isError||Fe.isError||Pe.isError&&!!E,$e=d||x!==null||B;function Wt(){ue.refetch()}function yt(){if(Oe.isError){Oe.refetch();return}if(Fe.isError){Fe.refetch();return}Pe.isError&&Pe.refetch()}return Z.isLoading||de.isLoading||se.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(P=>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"})]},P))}),e.jsx("p",{role:"status",className:"sr-only",children:"Loading conversion setup…"})]}):se.isError&&!se.data?e.jsxs("section",{className:"page-section","aria-labelledby":"conversion-integrity-title",children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsx("h2",{id:"conversion-integrity-title",className:"mt-1 text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsxs("p",{role:"alert",className:"mt-3 text-sm text-negative",children:["Could not load conversion contracts: ",mt(se.error)]}),e.jsx(A,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{se.refetch()},children:"Retry contracts"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Yp,{workspace:F,onPrimaryAction:ft,actionPending:Ie,actionError:$e?null:a,contracts:_,selectedContractId:ge?.id??null,onSelectContract:P=>J(P||null),contractError:se.isError?mt(se.error):null,onRetryContracts:()=>{se.refetch()},onRetryEvidence:()=>{Promise.all([ie.refetch(),O.refetch()])},onChangeGoogleAdsSelection:Le,onChangeGtmSelection:et,onAddContract:()=>ft("declare-contract")}),o?e.jsx("p",{role:"status",className:"page-section text-sm text-secondary",children:o}):null,d?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:Ee(async P=>{P.preventDefault(),await $t()}),children:[e.jsxs("label",{htmlFor:"google-ads-developer-token",className:as,children:["Developer token",e.jsx("input",{id:"google-ads-developer-token",type:"password",autoComplete:"off",value:u,onChange:P=>m(P.target.value),className:At,placeholder:"Required only when this project has no saved token"})]}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-secondary",children:"Canonry stores this securely. It never appears in saved evidence."}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(De,{type:"submit",disabled:tt.isPending,children:tt.isPending?"Starting…":"Continue to Google"}),e.jsx(A,{type:"button",variant:"outline",onClick:Ye,children:"Cancel"})]})]})]}):null,x==="google-ads"?e.jsxs("section",{id:"google-ads-selection-panel",className:"page-section-divider","aria-labelledby":"google-ads-selection-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Google Ads"}),e.jsx("h3",{id:"google-ads-selection-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Select customer context"})]})}),Lt?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:Lt}),e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:Wt,children:"Retry customer list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,zt?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:"The saved customer is no longer accessible. Choose another customer before saving."}):null,e.jsxs("div",{className:"grid max-w-2xl gap-4 sm:grid-cols-2",children:[e.jsxs(ca,{id:"google-ads-customer",label:"Customer account",value:w,onChange:P=>{p(!0),k(P);const me=Tt.find(st=>st.customerId===P);C(me?.parentCustomerId??"")},disabled:ue.isLoading,children:[e.jsx("option",{value:"",children:ue.isLoading?"Loading accessible customers…":"Select a customer"}),ot?e.jsxs("option",{value:w,disabled:zt,children:["Saved customer ",w," (",ct,")"]}):null,Tt.map(P=>e.jsx("option",{value:P.customerId,children:P.descriptiveName??`Customer ${P.customerId}`},P.customerId))]}),e.jsxs("label",{htmlFor:"google-ads-login-customer",className:as,children:["Manager account ID (optional)",e.jsx("input",{id:"google-ads-login-customer",className:At,value:M,onChange:P=>{p(!0),C(P.target.value)},placeholder:"Use only when a manager context is required"})]})]}),q?e.jsx("p",{role:"status",className:`mt-3 text-sm ${ue.data?.truncated?"text-caution":"text-secondary"}`,children:q}):null,e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(De,{type:"button",disabled:ke.isPending||ue.isLoading||ue.isError||zt||!w,onClick:Ee(Ft),children:ke.isPending?"Saving…":"Save customer selection"}),e.jsx(A,{type:"button",variant:"outline",onClick:pt,children:"Cancel"})]}),Z.data?.connected?e.jsx(Ji,{providerLabel:"Google Ads",disabled:Ie,onDisconnect:Y}):null]}):null,x==="gtm"?e.jsxs("section",{id:"gtm-selection-panel",className:"page-section-divider","aria-labelledby":"gtm-selection-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Google Tag Manager"}),e.jsx("h3",{id:"gtm-selection-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Select container context"})]})}),Lt?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:Lt}),e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:yt,children:Oe.isError?"Retry account list":Fe.isError?"Retry container list":"Retry workspace list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,Ht?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:Ht}):null,e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-3",children:[e.jsxs(ca,{id:"gtm-account",label:"Account",value:f,onChange:P=>{j(!0),P!==f&&(R(""),L("")),v(P)},disabled:Oe.isLoading,children:[e.jsx("option",{value:"",children:Oe.isLoading?"Loading accounts…":"Select an account"}),cs?e.jsxs("option",{value:f,disabled:Zt,children:["Saved account ",f," (",ms,")"]}):null,ls.map(P=>e.jsx("option",{value:P.id,children:P.name},P.id))]}),e.jsxs(ca,{id:"gtm-container",label:"Container",value:S,onChange:P=>{j(!0),P!==S&&L(""),R(P)},disabled:!f||Fe.isLoading,children:[e.jsx("option",{value:"",children:Fe.isLoading?"Loading containers…":"Select a container"}),Ct?e.jsxs("option",{value:S,disabled:Qt,children:["Saved container ",S," (",jt,")"]}):null,Mt.map(P=>e.jsx("option",{value:P.id,children:P.name},P.id))]}),e.jsxs(ca,{id:"gtm-workspace",label:"Draft workspace (optional)",value:E,onChange:P=>{j(!0),L(P)},disabled:!S||Pe.isLoading,children:[e.jsx("option",{value:"",children:Pe.isLoading?"Loading workspaces…":"No draft workspace"}),Ts?e.jsxs("option",{value:E,disabled:dt,children:["Saved draft workspace ",E," (",es,")"]}):null,Kt.map(P=>e.jsx("option",{value:P.id,children:P.name},P.id))]})]}),e.jsxs("div",{className:"mt-3 grid max-w-3xl gap-2 text-sm sm:grid-cols-3",children:[ne?e.jsx("p",{role:"status",className:Oe.data?.truncated?"text-caution":"text-secondary",children:ne}):null,fe?e.jsx("p",{role:"status",className:Fe.data?.truncated?"text-caution":"text-secondary",children:fe}):null,re?e.jsx("p",{role:"status",className:Pe.data?.truncated?"text-caution":"text-secondary",children:re}):null]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(De,{type:"button",disabled:Xe.isPending||Oe.isLoading||Fe.isLoading||Pe.isLoading&&!!E||oe||ws||!f||!S,onClick:Ee(gt),children:Xe.isPending?"Saving…":"Save container selection"}),e.jsx(A,{type:"button",variant:"outline",onClick:pt,children:"Cancel"})]}),de.data?.connected?e.jsx(Ji,{providerLabel:"Tag Manager",disabled:Ie,onDisconnect:Re}):null]}):null,B?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:Ee(async P=>{P.preventDefault(),await ze()}),children:[e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-2",children:[e.jsxs("label",{htmlFor:"contract-name",className:as,children:["Conversion name",e.jsx("input",{id:"contract-name",required:!0,maxLength:120,className:At,value:T.name,onChange:P=>N(me=>({...me,name:P.target.value})),placeholder:"Booking completed"})]}),e.jsxs("label",{htmlFor:"contract-event-name",className:as,children:["Website event",e.jsx("input",{id:"contract-event-name",required:!0,className:At,value:T.eventName,onChange:P=>N(me=>({...me,eventName:P.target.value})),placeholder:"booking_complete"})]}),e.jsx(Xi,{id:"contract-conversion-action",label:"Google Ads conversion action",options:$?.googleAds.conversionActions??[],synced:$?.googleAds.syncedAt!=null,loading:Q.isLoading,failed:Q.isError,onRetry:()=>{Q.refetch()},emptyHint:"Run a Google Ads sync to list conversion actions.",value:T.conversionActionId,onChange:P=>N(me=>({...me,conversionActionId:P}))}),e.jsx(Xi,{id:"contract-gtm-tag",label:"Tag Manager tag",options:$?.gtm.tags??[],synced:$?.gtm.syncedAt!=null,loading:Q.isLoading,failed:Q.isError,onRetry:()=>{Q.refetch()},emptyHint:"Run a Tag Manager sync to list tags.",value:T.tagId,onChange:P=>N(me=>({...me,tagId:P}))})]}),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:as,children:["Google conversion ID (optional)",e.jsx("input",{id:"contract-conversion-id",className:At,value:T.conversionId,onChange:P=>N(me=>({...me,conversionId:P.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-conversion-label",className:as,children:["Google conversion label (optional)",e.jsx("input",{id:"contract-conversion-label",className:At,value:T.conversionLabel,onChange:P=>N(me=>({...me,conversionLabel:P.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-trigger-ids",className:as,children:["Trigger IDs",e.jsx("input",{id:"contract-trigger-ids",className:At,value:T.triggerIds,onChange:P=>N(me=>({...me,triggerIds:P.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-variable-ids",className:as,children:["Variable IDs",e.jsx("input",{id:"contract-variable-ids",className:At,value:T.variableIds,onChange:P=>N(me=>({...me,variableIds:P.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-campaign-ids",className:as,children:["Campaign IDs",e.jsx("input",{id:"contract-campaign-ids",className:At,value:T.campaignIds,onChange:P=>N(me=>({...me,campaignIds:P.target.value})),placeholder:"Optional campaign-specific goal checks"})]}),e.jsxs("label",{htmlFor:"contract-production-hosts",className:as,children:["Production hosts",e.jsx("input",{id:"contract-production-hosts",className:At,value:T.productionHosts,onChange:P=>N(me=>({...me,productionHosts:P.target.value})),placeholder:"example.com"})]})]}),e.jsxs("fieldset",{className:"mt-5 border-t border-subtle pt-4",children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:"Required evidence"}),e.jsxs("div",{className:"mt-3 grid gap-3 sm:grid-cols-2",children:[e.jsx(bn,{id:"contract-primary-action",checked:T.requirePrimaryAction,onChange:P=>N(me=>({...me,requirePrimaryAction:P})),children:"Google Ads action is primary"}),e.jsx(bn,{id:"contract-biddable-goal",checked:T.requireBiddableGoal,onChange:P=>N(me=>({...me,requireBiddableGoal:P})),children:"Google Ads goal is biddable"}),e.jsx(bn,{id:"contract-runtime-verification",checked:T.verificationRequired,onChange:P=>N(me=>({...me,verificationRequired:P})),children:"Runtime proof is required"}),e.jsx(bn,{id:"contract-transaction-id",checked:T.requireTransactionId,onChange:P=>N(me=>({...me,requireTransactionId:P})),children:"Transaction ID is required"}),e.jsx(bn,{id:"contract-value",checked:T.requireValue,onChange:P=>N(me=>({...me,requireValue:P})),children:"Conversion value is required"}),e.jsx(bn,{id:"contract-currency",checked:T.requireCurrency,onChange:P=>N(me=>({...me,requireCurrency:P})),children:"Currency is required"})]})]})]}),e.jsx("p",{className:"mt-4 max-w-2xl text-sm leading-6 text-secondary",children:"This creates a Canonry contract only. It does not alter a Google Ads conversion action or create, edit, or publish a Tag Manager version."}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(De,{type:"submit",disabled:V.isPending,children:V.isPending?"Saving…":"Save conversion contract"}),e.jsx(A,{type:"button",variant:"outline",onClick:St,children:"Cancel"})]})]})]}):null]})}const sg=6e4,ng=["7d","14d","30d"],Fr="not available",ag='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%.',rg="No Google Ads snapshot stored yet",ig="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.",og="No closed days yet",lg="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.",cg={"insufficient-history":"Period change is hidden: the stored snapshot does not cover a prior period of equal length yet."},Es=new Intl.NumberFormat(void 0,{maximumFractionDigits:0}),tr=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}),yl=new Intl.NumberFormat(void 0,{maximumFractionDigits:1}),dg=new Intl.NumberFormat(void 0,{minimumFractionDigits:2,maximumFractionDigits:2});function vn(t,s){return t===null||!Number.isFinite(t)?Fr:s===null?dg.format(t/1e6):Dm(t,s)}function sr(t){if(t===null||!Number.isFinite(t))return Fr;const s=t*100;return s>0&&s<.1?"<0.1%":`${yl.format(s)}%`}function ug(t,s){if(t===null||!Number.isFinite(t))return`${Fr} 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%":`${yl.format(n)}%`;return`${t>0?"↑":"↓"} ${a} vs prior ${s}d`}function mg(t){return t==="enabled"?"positive":t==="paused"?"caution":"neutral"}function hg(t){return t==="enabled"?"Enabled":t==="paused"?"Paused":t==="removed"?"Removed":"Unknown"}function xg(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 pg({projectName:t}){const[s,n]=l.useState("14d"),[a,r]=l.useState(()=>new Set(["costMicros","conversions"])),o=we({...vd({client:W,path:{name:t},query:{window:s}}),staleTime:sg}),i=o.data,d=e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Google Ads"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("h2",{id:"google-ads-performance-title",className:"text-xl font-semibold tracking-[-0.02em] text-heading",children:"Ad performance"}),e.jsx(Me,{text:ag})]}),i?.source?e.jsxs("p",{className:"text-xs text-muted",children:[Ot(i.startDate)," to ",Ot(i.endDate)," · ",i.days," closed ",i.days===1?"day":"days"]}):null]}),e.jsx(Ra,{windows:ng,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:[d,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(f=>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"})]},f))}),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:[d,e.jsxs("p",{role:"alert",className:"mt-4 text-sm text-negative",children:["Could not load Google Ads performance: ",mt(o.error)]}),e.jsx(A,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{o.refetch()},children:"Retry performance"})]});const{totals:c,daily:u,campaigns:m,comparison:x,comparisonUnavailableReason:g,source:h}=i;if(!h){const f=g==="insufficient-history";return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[d,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:f?og:rg}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-secondary",children:f?lg:ig})]})]})}const p=h.currencyCode,y=h.campaignsInInventory>0&&h.campaignsQueried<h.campaignsInInventory?{queried:h.campaignsQueried,inInventory:h.campaignsInInventory}:null,j=c.costMicros>0&&c.conversions===0,w=[{key:"spend",comparable:!0,label:"Spend",value:vn(c.costMicros,p),change:x?.change.costMicros??null,direction:"none",seriesKey:"costMicros"},{key:"conversions",comparable:!0,label:"Conversions",value:tr.format(c.conversions),change:x?.change.conversions??null,direction:"up-good",seriesKey:"conversions"},{key:"cost-per-conversion",label:"Cost / conv.",value:j?"no conversions":vn(c.costPerConversionMicros,p),change:null,comparable:!1,direction:"down-good",seriesKey:null},{key:"conversion-rate",comparable:!0,label:"Conv. rate",value:sr(c.conversionRate),change:x?.change.conversionRate??null,direction:"up-good",seriesKey:null}],k=[{key:"clicks",label:"Clicks",value:Es.format(c.clicks),seriesKey:"clicks"},{key:"impressions",label:"Impressions",value:Es.format(c.impressions),seriesKey:"impressions"},{key:"ctr",label:"CTR",value:sr(c.ctr),seriesKey:null},{key:"cpc",label:"CPC",value:vn(c.cpcMicros,p),seriesKey:null}],M={costMicros:{label:"Spend",color:nt[1],axisId:"spend",formatValue:f=>vn(f,p)},conversions:{label:"Conversions",color:nt[0],axisId:"conversions",formatValue:f=>tr.format(f)},clicks:{label:"Clicks",color:nt[2],axisId:"clicks",formatValue:f=>Es.format(f)},impressions:{label:"Impressions",color:nt[3],axisId:"impressions",formatValue:f=>Es.format(f)}},C=[...a].map(f=>({dataKey:f,...M[f]}));return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[d,y!==null?e.jsxs("p",{role:"status",className:"mt-3 text-sm text-caution",children:["Totals cover ",Es.format(y.queried)," of"," ",Es.format(y.inInventory)," campaigns, so they are a subset of the account."]}):null,h.truncated?e.jsx("p",{role:"status",className:"mt-3 text-sm text-caution",children:"The provider returned a bounded result, so some rows are missing from the figures below."}):null,!x&&g==="insufficient-history"?e.jsx("p",{className:"mt-3 text-sm text-secondary",children:cg["insufficient-history"]}):null,e.jsx("div",{className:"mt-4 grid grid-cols-2 gap-2 lg:grid-cols-4",children:w.map(f=>{const v=f.seriesKey!==null&&a.has(f.seriesKey),S=v&&a.size===1,R=e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[f.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:v?M[f.seriesKey].color:"var(--color-mono-600)"}}):null,f.label]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:f.value}),x&&f.comparable?e.jsx("span",{className:`block text-[11px] tabular-nums ${xg(f.change,f.direction)}`,children:ug(f.change,x.days)}):e.jsx("span",{className:"block text-[11px] text-muted",children:f.comparable?`no prior ${s} period stored`:" "})]});return f.seriesKey===null?e.jsx("div",{className:"rounded-md border border-subtle bg-surface-subtle px-3 py-2",children:R},f.key):e.jsx("button",{type:"button","aria-pressed":v,disabled:S,onClick:()=>r(E=>{const L=new Set(E);return L.has(f.seriesKey)?L.delete(f.seriesKey):L.add(f.seriesKey),L.size===0?E:L}),className:`rounded-md border px-3 py-2 text-left transition-colors ${v?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${S?"cursor-default":""}`,children:R},f.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:k.map(f=>{const v=f.seriesKey!==null&&a.has(f.seriesKey),S=v&&a.size===1,R=e.jsxs(e.Fragment,{children:[e.jsxs("dt",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[f.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:v?M[f.seriesKey].color:"var(--color-mono-600)"}}):null,f.label]}),e.jsx("dd",{className:"text-sm tabular-nums text-strong",children:f.value})]});return f.seriesKey===null?e.jsx("div",{className:"flex items-baseline gap-1.5",children:R},f.key):e.jsx("button",{type:"button","aria-pressed":v,disabled:S,onClick:()=>r(E=>{const L=new Set(E);return L.has(f.seriesKey)?L.delete(f.seriesKey):L.add(f.seriesKey),L.size===0?E:L}),className:`flex items-baseline gap-1.5 rounded px-1 -mx-1 ${S?"cursor-default":"hover:bg-surface-hover"}`,children:R},f.key)})}),e.jsxs("div",{className:"mt-4",children:[e.jsx(_o,{data:u,xKey:"date",series:C,xTickFormatter:pn,labelFormatter:Ot}),e.jsx("ul",{className:"sr-only",children:u.map(f=>e.jsxs("li",{children:[Ot(f.date),":"," ",C.map(v=>`${v.label} ${M[v.dataKey].formatValue(f[v.dataKey])}`).join(", "),f.origin==="filled"?", no delivery reported":""]},f.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(f=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs truncate text-strong",title:f.name??f.campaignId,children:f.name??e.jsx("span",{className:"font-mono text-secondary",children:f.campaignId})}),e.jsx("td",{children:e.jsx(le,{tone:mg(f.status),children:hg(f.status)})}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Es.format(f.totals.impressions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:Es.format(f.totals.clicks)}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:vn(f.totals.costMicros,p)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:tr.format(f.totals.conversions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:sr(f.totals.ctr)}),e.jsx("td",{className:"text-right tabular-nums",children:f.totals.costMicros>0&&f.totals.conversions===0?e.jsx(le,{tone:"caution",children:"no conversions"}):e.jsx("span",{className:"text-secondary",children:vn(f.totals.costPerConversionMicros,p)})})]},f.campaignId))})]})}),e.jsxs("p",{className:"mt-3 text-[11px] text-muted",children:["Snapshot ",Vs($s(h.capturedAt))," · ","customer ",h.customerId," · ","latest closed day ",Ot(h.asOfDate),h.openDate?e.jsxs(e.Fragment,{children:[" · ",Ot(h.openDate)," still open, excluded"]}):null,h.timeZone?e.jsxs(e.Fragment,{children:[" · ","days close in ",h.timeZone]}):null]})]})]})}const nr=20,As=50,gg=50,fg=50;function Gr(t){return t==="viewer"}function Kr(t){return t?.status==="unavailable"}function bl(t,s,n){return n?t.includes(s)?[...t]:[...t,s]:t.filter(a=>a!==s)}function vl(t,s){const n=new Map(s.map(r=>[r.id,r.label])),a=t.map(r=>n.get(r)).filter(r=>!!r);return a.length===0?"Not applied":a.length>3?`${a.length} Properties`:a.join(", ")}function da(t,s,n){if(t.kind==="all")return s.map(o=>o.id);if(t.kind==="specific")return s.filter(o=>t.propertyIds.includes(o.id)).map(o=>o.id);const a=new Set(t.groupIds),r=new Set(n.filter(o=>a.has(o.id)).flatMap(o=>o.propertyIds));return s.filter(o=>r.has(o.id)).map(o=>o.id)}function yg(t,s,n){if(t.kind==="all")return`all ${n} ${n===1?"Property":"Properties"}`;if(t.kind==="specific")return n===1?"1 Property":`${n} Properties`;const a=t.groupIds.map(r=>s.find(o=>o.id===r)?.name).filter(r=>!!r);return a.length===0?"selected groups":a.join(" + ")}function ar(t,s){const n=new Set(s.map(r=>r.id)),a=t.propertyIds.filter(r=>n.has(r)).length;return`${t.name} · ${a===1?"1 Property":`${a} Properties`}`}function Zi(t){return t==="matched"?"positive":t==="duplicate"?"neutral":t==="ambiguous"||t==="proposed"||t==="excluded"?"caution":"negative"}function eo(t){return t==="matched"?"Matched":t==="duplicate"?"Duplicate":t==="ambiguous"?"Ambiguous":t==="proposed"?"Property needs review":t==="excluded"?"Property excluded":t==="invalid"?"Invalid row":"Not matched"}function ua(t){return t.status==="duplicate"&&t.duplicateOfRow?`Duplicates row ${t.duplicateOfRow}.`:t.status==="matched"?null:t.reason==="group-label-ambiguous"?`More than one group matches “${t.group}”. Rename duplicate groups, then preview again.`:t.status==="ambiguous"?"More than one Property matches this row. Add an exact URL to choose one.":t.status==="unmatched"?"No included Property matches this row.":t.reason==="group-key-conflict"?`The group name “${t.group}” conflicts with an existing setup identity. Rename the group, then preview again.`:t.status==="invalid"?"Check the Property, group, and optional URL fields.":t.status==="proposed"?"Review this proposed Property before importing it.":t.status==="excluded"?"Include this Property before importing it.":t.reason??null}function Ar(t){return t.state==="missing"||t.source==="unavailable-tracked-query"||!t.source}function rr(t){return Ar(t)?"Unavailable tracked query":t.text?.trim()||"Unavailable tracked query"}function Pr({properties:t,selectedPropertyIds:s,onSelectedPropertyIdsChange:n,legend:a,showBulkActions:r=!0}){const[o,i]=l.useState(""),[d,c]=l.useState(!1),u=o.trim().toLocaleLowerCase(),m=u?t.filter(p=>p.label.toLocaleLowerCase().includes(u)):t,x=d?m:m.slice(0,gg),g=x.length<m.length;function h(){const p=new Set([...s,...x.map(y=>y.id)]);n(t.filter(y=>p.has(y.id)).map(y=>y.id))}return e.jsxs("fieldset",{children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:a}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-end justify-between gap-3",children:[e.jsxs("label",{className:"block min-w-48 flex-1",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Search Properties"}),e.jsx("input",{type:"search",value:o,onChange:p=>i(p.currentTarget.value),className:"mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400"})]}),r?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:x.length===0,onClick:h,children:"Select all shown"}),e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:s.length===0,onClick:()=>n([]),children:"Clear selection"})]}):null]}),m.length===0?e.jsx("p",{className:"mt-3 text-sm text-secondary",children:"No Properties match this search."}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"mt-3 text-sm text-secondary",children:["Showing ",x.length," of ",m.length," Properties"]}),e.jsx("div",{className:"mt-2 max-h-96 divide-y divide-default overflow-y-auto border-y border-default",children:x.map(p=>{const y=s.includes(p.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 ${p.label}`,checked:y,type:"checkbox",onChange:j=>n(bl(s,p.id,j.currentTarget.checked))}),e.jsx("span",{children:p.label})]}),p.urlCount===void 0?null:e.jsxs("span",{className:"tabular-nums text-secondary",children:[p.urlCount," URLs"]})]},p.id)})}),g?e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",onClick:()=>c(!0),children:"Show all Properties"}):null]})]})}function _r(){return e.jsxs("div",{className:"flex items-center gap-2 text-sm text-secondary",children:[e.jsx(le,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]})}function Ur({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(le,{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 bg({value:t}){const[s,n]=l.useState(0),[a,r]=l.useState(0),[o,i]=l.useState(null),d=t.preview,c=d?.counts.needsAttention??0,u=d?.rows.filter(S=>S.status==="matched")??[],m=d?.rows??[],x=m.filter(S=>S.status!=="matched"),g=Math.max(1,Math.ceil(m.length/As)),h=Math.min(s,g-1),p=m.slice(h*As,(h+1)*As),y=Math.max(1,Math.ceil(x.length/As)),j=Math.min(a,y-1),w=x.slice(j*As,(j+1)*As),k=t.csv.trim().length>0&&!t.isReviewing&&!t.isApplying,M=u.length>0&&!t.isApplying,C=d!==null&&o===d.previewChecksum,f=x.length>0&&j===y-1;l.useEffect(()=>{n(0),r(0),i(null)},[d?.previewChecksum]);async function v(S){if(S)try{t.onCsvChange(await S.text())}catch{}}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-group-import-title",className:"border-y border-default py-4",children:[e.jsxs("div",{className:"max-w-2xl",children:[e.jsx("h4",{id:"advanced-measurement-group-import-title",className:"text-sm font-medium text-heading",children:"Import groups from CSV"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Import market membership once instead of selecting the same Properties for every group."})]}),e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"CSV file"}),e.jsx("input",{"aria-label":"Group membership CSV file",type:"file",accept:".csv,text/csv",disabled:t.isReviewing||t.isApplying,onChange:S=>{v(S.currentTarget.files?.[0])},className:"mt-1 block min-h-11 w-full text-sm text-secondary file:mr-3 file:min-h-11 file:rounded-md file:border file:border-default file:bg-surface file:px-3 file:text-sm file:font-medium file:text-primary"})]}),e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Or paste CSV"}),e.jsx("textarea",{"aria-label":"Group membership CSV",rows:5,value:t.csv,disabled:t.isReviewing||t.isApplying,onChange:S=>t.onCsvChange(S.currentTarget.value),placeholder:`property,group,url
|
|
4
|
-
Harbor House,Dallas,https://example.com/harbor-house`,className:"mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!k,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]}),d?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:[d.counts.matchedRows," matched · ",d.counts.groupsReady," group",d.counts.groupsReady===1?"":"s"," ready",c>0?` · ${c} need${c===1?"s":""} attention`:""]}),d.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:d.groupChanges.map(S=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:S.label}),e.jsx("td",{className:"text-secondary",children:S.action==="create"?"Create group":"Add to existing group"}),e.jsx("td",{className:"tabular-nums text-secondary",children:S.targetKeys.length}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[S.addedTargetKeys.length,S.unchangedTargetKeys.length>0?` · ${S.unchangedTargetKeys.length} already members`:""]})]},S.groupKey))})]})}):null,d.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 (",d.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:p.map(S=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:S.dataRow}),e.jsx("td",{className:"text-heading",children:S.property}),e.jsx("td",{className:"text-secondary",children:S.group}),e.jsxs("td",{children:[e.jsx(le,{tone:Zi(S.status),children:eo(S.status)}),ua(S)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:ua(S)}):null]})]},S.dataRow))})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Page ",h+1," of ",g," · ",d.rows.length," rows"]}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:h===0,onClick:()=>n(S=>Math.max(0,S-1)),children:"Previous 50 rows"}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:h===g-1,onClick:()=>n(S=>Math.min(g-1,S+1)),children:"Next 50 rows"})]})]}):null,c>0?e.jsxs("details",{className:"mt-3 border-y border-caution-800/30 py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Fix ",c," row",c===1?"":"s"," before applying"]}),e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Correct these rows, or explicitly continue with only the reviewed matches. Rows needing attention are not added."}),e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"CSV rows that need attention"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Row"}),e.jsx("th",{children:"Property"}),e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Issue"})]})}),e.jsx("tbody",{children:w.map(S=>e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:S.dataRow}),e.jsx("td",{className:"text-heading",children:S.property}),e.jsx("td",{className:"text-secondary",children:S.group}),e.jsxs("td",{children:[e.jsx(le,{tone:Zi(S.status),children:eo(S.status)}),ua(S)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:ua(S)}):null]})]},S.dataRow))})]})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Exception page ",j+1," of ",y]}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:j===0,onClick:()=>r(S=>Math.max(0,S-1)),children:"Previous 50 exceptions"}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:j===y-1,onClick:()=>r(S=>Math.min(y-1,S+1)),children:"Review next 50 exceptions"})]}),e.jsxs("label",{className:"mt-3 flex min-h-11 max-w-xl items-center gap-3 text-sm text-heading",children:[e.jsx("input",{type:"checkbox",checked:C,disabled:t.isApplying||!f,onChange:S=>i(S.currentTarget.checked?d.previewChecksum:null),className:"size-4 rounded border-default"}),"I reviewed the exceptions and understand that ",c," row",c===1?"":"s"," will be skipped."]}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",disabled:!M||!C,onClick:()=>{t.onApply(u.map(S=>S.dataRow))},children:t.isApplying?"Applying groups…":`Apply ${u.length} matched row${u.length===1?"":"s"}`})]}):e.jsx(A,{type:"button",className:"mt-3 min-h-11",disabled:!M,onClick:()=>{t.onApply(u.map(S=>S.dataRow))},children:t.isApplying?"Creating groups…":`Create ${d.counts.groupsReady} group${d.counts.groupsReady===1?"":"s"} with ${u.length} membership${u.length===1?"":"s"}`})]}):null]})}const vg="—";function jg({access:t,availability:s,properties:n,queries:a,selectedQueryIds:r,isApplying:o=!1,isBusy:i=!1,canContinue:d=!0,onSelectedQueryIdsChange:c,onApplySelectedQueries:u,onClearQueryAssignments:m,onRemoveQuery:x,onCreateQueries:g,onCreateAndPairQuestions:h,isCreatingQueries:p=!1,createQueriesError:y=null,onManageProjectQueries:j,groups:w,audience:k,onAudienceChange:M,assignmentImpact:C=null,isPreviewingAssignmentImpact:f=!1,assignmentImpactError:v=null,onRetryAssignmentImpact:S,assignmentNotice:R=null,onReplaceAssignments:E,isReplacingAssignments:L=!1,onBack:B,onContinue:U}){const[T,N]=l.useState(""),[D,J]=l.useState(!1),[G,Z]=l.useState(!1),[de,se]=l.useState(""),[Q,$]=l.useState(""),[ie,O]=l.useState(null);if(Kr(s))return e.jsx("section",{"aria-label":"Queries",children:e.jsx(Ur,{message:s.message})});const _=Gr(t),X=k,ge=M,H=da(X,n,w),ae=H.length,ue=ae>0&&r.length>0&&!o&&!i&&!f&&C!==null&&v===null,Oe=m??x,Fe=T.trim().toLocaleLowerCase(),Pe=Fe?a.filter(z=>rr(z).toLocaleLowerCase().includes(Fe)):a,tt=Pe.filter(z=>(z.propertyIds?.length??0)===0),it=G?tt:Pe,ke=D?it:it.slice(0,fg),Xe=ke.filter(z=>!Ar(z)),_e=[...new Set(de.split(`
|
|
5
|
-
`).map(z=>z.trim()).filter(Boolean))],Ve=[...Q.matchAll(/\{([a-z][\w-]*)\}/gi)].map(z=>z[1]),He=n.filter(z=>H.includes(z.id)),Te=Ve.length===0||Q.trim()===""?[]:He.map(z=>({propertyId:z.id,text:Ve.reduce((Ne,Ie)=>Ne.replaceAll(`{${Ie}}`,z.label),Q.trim())})),V=[...new Set(Te.map(z=>z.text))];function F(){const z=new Set([...r,...Xe.map(Ne=>Ne.id)]);c(a.filter(Ne=>z.has(Ne.id)).map(Ne=>Ne.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."})]})}),_?e.jsx(_r,{}):null,_?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:X.kind==="all"?"all":X.kind==="specific"?"specific":`group:${X.groupIds[0]??""}`,onChange:z=>{const Ne=z.currentTarget.value;Ne==="all"?ge({kind:"all"}):Ne==="specific"?ge({kind:"specific",propertyIds:[]}):Ne.startsWith("group:")&&ge({kind:"groups",groupIds:[Ne.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]}),w.length>0?e.jsx("optgroup",{label:"Groups",children:w.map(z=>{const Ne=da({kind:"groups",groupIds:[z.id]},n,w).length;return e.jsx("option",{value:`group:${z.id}`,disabled:Ne===0,children:ar(z,n)},z.id)})}):null,e.jsx("option",{value:"specific",children:"Specific Properties…"})]})]})}),X.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:X.groupIds.map(z=>{const Ne=w.find(Ie=>Ie.id===z);return Ne?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:[ar(Ne,n),e.jsx("button",{type:"button","aria-label":`Remove ${Ne.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 Ie=X.groupIds.filter(ee=>ee!==Ne.id);ge(Ie.length>0?{kind:"groups",groupIds:Ie}:{kind:"all"})},children:"×"})]},Ne.id):null})}),w.some(z=>!X.groupIds.includes(z.id)&&da({kind:"groups",groupIds:[z.id]},n,w).length>0)?e.jsxs("label",{className:"block max-w-sm",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Add another group"}),e.jsxs("select",{"aria-label":"Add another group",value:"",onChange:z=>{z.currentTarget.value&&ge({kind:"groups",groupIds:[...X.groupIds,z.currentTarget.value]})},className:"mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-400",children:[e.jsx("option",{value:"",children:"Choose a group"}),w.filter(z=>!X.groupIds.includes(z.id)).map(z=>{const Ne=da({kind:"groups",groupIds:[z.id]},n,w).length;return e.jsx("option",{value:z.id,disabled:Ne===0,children:ar(z,n)},z.id)})]})]}):null,ae===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,X.kind==="specific"?e.jsx("div",{className:"mt-4",children:e.jsx(Pr,{legend:"Specific Properties",properties:n,selectedPropertyIds:X.propertyIds,showBulkActions:!1,onSelectedPropertyIdsChange:z=>{ge({kind:"specific",propertyIds:z})}})}):null,e.jsx("p",{className:"mt-3 max-w-2xl text-sm text-secondary",children:"Groups are shortcuts resolved when you assign. Changing membership later does not rewrite existing assignments, and a Property added later does not receive earlier group queries."})]}),_||!g?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:de,onChange:z=>se(z.currentTarget.value),placeholder:`best apartments in dallas
|
|
6
|
-
luxury apartments atlanta
|
|
7
|
-
pet friendly apartments austin`}),y?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:y}):null,e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:_e.length===0||p||i,onClick:()=>{Promise.resolve(g(_e)).then(()=>se(""),()=>{})},children:p?"Adding…":`Add ${_e.length||""} ${_e.length===1?"query":"queries"}`.replace(" "," ")}),j?e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i,onClick:j,children:"Manage project queries"}):null]}),e.jsxs("div",{className:"mt-4 border-t border-default pt-4",children:[e.jsx("h4",{className:"m-0 text-sm font-medium text-heading",children:"Write one query for every Property"}),e.jsxs("p",{className:"mt-1 mb-2 text-sm text-secondary",children:["Put ",e.jsx("code",{className:"rounded bg-bg-elevated px-1",children:"{property}"})," where the Property name belongs. You get one query per selected Property."]}),e.jsx("input",{"aria-label":"Query pattern",className:"min-h-11 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",value:Q,onChange:z=>$(z.target.value),placeholder:"apartments near {property}"}),Q.trim()===""?null:Ve.length===0?e.jsxs("p",{className:"mt-2 text-sm text-caution",children:["Add ","{property}"," to the pattern, or use the box above for a single query."]}):He.length===0?e.jsx("p",{className:"mt-2 text-sm text-caution",children:"Select at least one Property to write queries for."}):e.jsxs("div",{className:"mt-2 rounded-md border border-base bg-bg-elevated p-3",children:[e.jsxs("p",{className:"m-0 text-sm text-secondary",children:[V.length," ",V.length===1?"query":"queries",", one per selected Property:"]}),e.jsx("ul",{className:"mt-1 mb-0 list-none space-y-0.5 p-0",children:V.slice(0,3).map(z=>e.jsx("li",{className:"text-sm text-strong",children:z},z))}),V.length>3?e.jsxs("p",{className:"mt-1 mb-0 text-sm text-secondary",children:["and ",V.length-3," more"]}):null]}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"mt-2 min-h-11",disabled:Te.length===0||p||i||!h,onClick:()=>{h&&Promise.resolve(h(Te)).then(()=>$(""),()=>{})},children:p?"Adding…":`Add ${Te.length||""} ${Te.length===1?"query":"queries"}`.replace(" "," ")}),Te.length>0?e.jsxs("p",{className:"mt-2 mb-0 text-sm text-secondary",children:["Each query is measured on the one Property it names, so this adds"," ",Te.length," assignment",Te.length===1?"":"s","."]}):null]})]})]}),_?null:e.jsx("div",{className:"space-y-3 border-y border-default py-4",children:a.length===0?null:e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:Xe.length===0,onClick:F,children:"Select all shown queries"}),e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:r.length===0,onClick:()=>c([]),children:"Clear query selection"}),e.jsx(A,{type:"button",size:"sm",className:"min-h-11",disabled:!ue,onClick:()=>{u({queryIds:r,propertyIds:H,...X.kind==="groups"?{groupIds:X.groupIds}:{}})},children:o?"Assigning queries…":`Assign ${r.length||""} ${r.length===1?"query":"queries"} to ${yg(X,w,ae)}`.replace(" "," ")}),e.jsxs("div",{className:"min-h-[2.75rem]",children:[f?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Calculating assignment impact…"}):null,C?e.jsxs("p",{className:"text-sm text-secondary",children:[r.length," ",r.length===1?"query":"queries"," → ",C.assignmentCount," Property assignment",C.assignmentCount===1?"":"s"," · ",C.addedAssignments," new, ",C.alreadyPresentAssignments," already assigned"," · ",C.fullRunProviderCalls," provider request",C.fullRunProviderCalls===1?"":"s"," per full run"," · ",C.addedProviderCalls," new",X.kind==="groups"?` · ${C.resolvedPropertyCount} unique ${C.resolvedPropertyCount===1?"Property":"Properties"}${C.overlapCount>0?`, ${C.overlapCount} in overlapping groups`:""}`:"",". Existing assignments stay in place."]}):v?e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("p",{role:"alert",className:"text-sm text-negative",children:v}),S?e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:S,children:"Retry impact"}):null,B?e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:B,children:"Back to Groups"}):null]}):e.jsxs("p",{className:"text-sm text-secondary",children:[r.length," ",r.length===1?"query":"queries"," × ",ae," Properties = ",r.length*ae," assignments"]})]}),R?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:R}):null]})}),a.length>0?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Search queries"}),e.jsx("input",{type:"search",value:T,onChange:z=>{N(z.currentTarget.value),J(!1)},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",placeholder:"Query text"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("p",{className:"m-0 text-sm text-secondary",children:["Showing ",ke.length," of ",it.length," queries,"," ",Pe.length-tt.length," of ",Pe.length," applied"]}),_||tt.length===0?null:e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>{Z(z=>!z),J(!1)},children:G?"Show all queries":`Show the ${tt.length} not applied`})]})]}):null,ke.length>0?e.jsx("div",{className:"overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[_?null:e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Select query"})}),e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Properties"}),_?null:e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Clear query assignments"})})]})}),e.jsx("tbody",{children:ke.map(z=>{const Ne=Ar(z),Ie=rr(z),ee=r.includes(z.id),We=(z.propertyIds?.length??0)>0;return e.jsxs("tr",{children:[_?null:Ne?e.jsx("td",{"aria-hidden":"true"}):e.jsx("td",{className:"p-0",children:e.jsx("label",{className:"flex min-h-11 min-w-11 cursor-pointer items-center justify-center",children:e.jsx("input",{"aria-label":`Select query ${Ie}`,checked:ee,type:"checkbox",onChange:ht=>c(bl(r,z.id,ht.currentTarget.checked)),className:"size-6 accent-accent"})})}),e.jsx("td",{children:e.jsx("p",{className:"font-medium text-heading",children:Ie})}),e.jsx("td",{className:"text-secondary",children:vl(z.propertyIds??[],n)}),_?null:e.jsx("td",{className:"text-right",children:We?e.jsxs("div",{className:"flex flex-wrap justify-end gap-1",children:[E?e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i||L,onClick:()=>O({queryId:z.id,propertyIds:[...z.propertyIds??[]]}),"aria-label":`Replace query assignments for ${Ie}`,children:"Replace assignments"}):null,e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i,onClick:()=>{Oe(z.id)},"aria-label":`Clear query assignments for ${Ie}`,children:"Clear assignments"})]}):null})]},z.id)})})]})}):a.length>0?e.jsx("p",{className:"text-sm text-secondary",children:"No queries match this search."}):null,_||!ie?null:(()=>{const z=a.find(ee=>ee.id===ie.queryId),Ne=z?rr(z):"this query",Ie=ie.propertyIds.filter(ee=>n.some(We=>We.id===ee));return e.jsxs("section",{"aria-labelledby":"advanced-measurement-replace-assignments-title",className:"border-y border-default py-4",children:[e.jsx("h4",{id:"advanced-measurement-replace-assignments-title",className:"text-sm font-medium text-heading",children:"Replace assigned Properties"}),e.jsxs("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:["This replaces every Property assigned to “",Ne,"”."]}),e.jsx("div",{className:"mt-3",children:e.jsx(Pr,{legend:"Properties for this query",properties:n,selectedPropertyIds:Ie,onSelectedPropertyIdsChange:ee=>O(We=>We&&{...We,propertyIds:[...ee]})})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3",children:[e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:L||i,onClick:()=>O(null),children:"Keep current assignments"}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:Ie.length===0||L||i||!E,onClick:()=>{E&&Promise.resolve(E({queryId:ie.queryId,propertyIds:Ie}))},children:L?"Replacing assignments…":`Replace with ${Ie.length} ${Ie.length===1?"Property":"Properties"}`})]})]})})(),ke.length<it.length?e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:()=>J(!0),children:"Show all queries"}):null,_?null:e.jsxs(e.Fragment,{children:[d?null:e.jsx("p",{role:"status",className:"text-sm text-caution",children:"Apply at least one query to a Property before continuing."}),e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${B?"justify-between":"justify-end"}`,children:[B?e.jsx(A,{type:"button",variant:"outline",className:"min-h-11",disabled:i,onClick:B,children:"Back"}):null,e.jsx(A,{type:"button",variant:ue?"outline":"default",className:"min-h-11",disabled:!d||i,onClick:U,children:"Continue"})]})]})]})}function Ng({access:t,availability:s,properties:n,groups:a,groupDraft:r,isSaving:o=!1,onGroupDraftChange:i,onSaveGroup:d,onEditGroup:c,onRemoveGroup:u,onClearGroupDraft:m,membershipImport:x,onBack:g,onContinue:h}){if(Kr(s))return e.jsx("section",{"aria-label":"Groups",children:e.jsx(Ur,{message:s.message})});const p=Gr(t),y=r.name.trim().length>0&&r.propertyIds.length>0&&!o,j=n.filter(C=>r.propertyIds.includes(C.id)).length,w=r.name.trim().length>0||r.propertyIds.length>0||r.competitorDomains.trim().length>0,k=!p&&(c!==void 0||u!==void 0);function M(){if(m){m();return}i({name:"",propertyIds:[],competitorDomains:""})}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-groups-title",className:"space-y-5",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{id:"advanced-measurement-groups-title",children:"Groups"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Use groups to assign queries by market and compare competitors."})]})}),p?e.jsx(_r,{}):null,p||!x?null:e.jsx(bg,{value:x}),p?null:e.jsxs("div",{className:"space-y-4 border-y border-default py-4",children:[e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Group name"}),e.jsx("input",{"aria-label":"Group name",className:"mt-1 min-h-11 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",value:r.name,onChange:C=>i({...r,name:C.currentTarget.value}),placeholder:"Waterfront venues"})]}),e.jsxs("details",{children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:[j," of ",n.length," Properties selected"]}),e.jsx("div",{className:"pt-3",children:e.jsx(Pr,{legend:"Properties in this group",properties:n,selectedPropertyIds:r.propertyIds,onSelectedPropertyIdsChange:C=>i({...r,propertyIds:C})})})]}),e.jsxs("label",{className:"block max-w-xl",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Competitor domains"}),e.jsx("input",{"aria-label":"Competitor domains",className:"mt-1 min-h-11 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",value:r.competitorDomains,onChange:C=>i({...r,competitorDomains:C.currentTarget.value}),placeholder:"one.example, two.example"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!y,onClick:()=>{d(r)},children:o?"Saving group…":"Save group"}),e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:!w,onClick:M,children:"Clear form"}),e.jsx("p",{className:"text-sm text-secondary",children:"Competitor domains are used only in this group's competitor report. Membership changes affect future assignments only."})]}),w?e.jsx("p",{role:"status",className:"text-sm text-caution",children:"Save this group or clear the form before continuing."}):null]}),e.jsx("div",{className:"overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Properties"}),e.jsx("th",{children:"Competitors"}),k?e.jsx("th",{children:"Actions"}):null]})}),e.jsx("tbody",{children:a.map(C=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:C.name}),e.jsx("td",{className:"text-secondary",children:vl(C.propertyIds,n)}),e.jsx("td",{className:"text-secondary",children:C.competitors.length>0?C.competitors.join(", "):"None"}),k?e.jsx("td",{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[c?e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11","aria-label":`Edit ${C.name}`,onClick:()=>c(C),children:"Edit"}):null,u?e.jsx(A,{type:"button",size:"sm",variant:"ghost",className:"min-h-11","aria-label":`Remove ${C.name}`,onClick:()=>{u(C.id)},children:"Remove"}):null]})}):null]},C.id))})]})}),a.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No groups have been added."}):null,p?null:e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${g?"justify-between":"justify-end"}`,children:[g?e.jsx(A,{type:"button",variant:"outline",className:"min-h-11",onClick:g,children:"Back"}):null,e.jsx(A,{type:"button",className:"min-h-11",disabled:w,onClick:h,children:a.length===0&&!w?"Continue without groups":"Continue"})]})]})}function wg({access:t,availability:s,counts:n,flaggedExceptions:a,sitemapReview:r,onBack:o,onReviewChanges:i,isReviewing:d=!1,canReviewChanges:c=!0,reviewedChanges:u,reviewChangesError:m,canPublish:x,isPublishing:g=!1,onPublish:h}){const[p,y]=l.useState(nr),[j,w]=l.useState(nr),[k,M]=l.useState(nr);if(Kr(s))return e.jsx("section",{"aria-label":"Review and publish",children:e.jsx(Ur,{message:s.message})});const C=Gr(t),f=r?.items??[],v=r?.coverageItems??[],S=f.slice(0,p),R=v.slice(0,j),E=a.slice(0,k),L=i!==void 0,B=u!=null;return e.jsxs("section",{"aria-labelledby":"advanced-measurement-review-title",className:"space-y-5",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("h3",{id:"advanced-measurement-review-title",children:"Review & publish"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Confirm the setup details before publishing."})]})}),C?e.jsx(_r,{}):null,r?e.jsx("section",{"aria-labelledby":"advanced-measurement-sitemap-review-title",className:"border-y border-caution-800/40 bg-caution-950/20 py-4",children:e.jsxs("div",{className:"max-w-2xl space-y-3",children:[e.jsxs("div",{children:[e.jsx("h4",{id:"advanced-measurement-sitemap-review-title",className:"text-sm font-medium text-heading",children:"Sitemap changes need review"}),r.exceptionCount>0?e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:[r.exceptionCount," sitemap ",r.exceptionCount===1?"entry needs":"entries need"," review."]}):null,r.coverageReviewCount>0?e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:[r.coverageReviewCount," ",r.coverageReviewCount===1?"Property has":"Properties have"," URL coverage changes."]}):null]}),r.exceptionCount>0?e.jsxs("details",{className:"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:["URLs not added to Properties (",r.exceptionCount,")"]}),f.length>0?e.jsx("ul",{className:"mt-3 space-y-3 text-sm",children:S.map(U=>e.jsxs("li",{children:[e.jsx("p",{className:"font-medium text-primary",children:U.url}),e.jsx("p",{className:"mt-1 text-secondary",children:U.reason})]},`${U.url}-${U.reason}`))}):e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Review the affected sitemap URLs before confirming."}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",S.length," of ",f.length]}),S.length<f.length?e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>y(U=>U+As),children:"Show next 50 URLs"}):null]})]}):null,C?e.jsx("p",{className:"text-sm text-secondary",children:"An editor must finish this review before publishing."}):e.jsxs(e.Fragment,{children:[r.coverageReviewCount>0?e.jsxs("fieldset",{className:"space-y-3",children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:"For changed Property URLs"}),e.jsxs("p",{className:"text-sm text-secondary",children:["This choice applies to all ",r.coverageReviewCount," changed ",r.coverageReviewCount===1?"Property":"Properties","."]}),e.jsxs("details",{className:"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:["Review Property URL changes (",r.coverageReviewCount,")"]}),R.length>0?e.jsxs("div",{className:"mt-3 space-y-4",children:[R.map(U=>e.jsxs("section",{"aria-label":`${U.property} URL changes`,children:[e.jsx("h5",{className:"text-sm font-medium text-primary",children:U.property}),e.jsxs("div",{className:"mt-2 grid gap-3 text-sm md:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-secondary",children:"Saved URLs"}),e.jsx("ul",{className:"mt-1 space-y-1",children:U.savedUrls.map(T=>e.jsx("li",{className:"break-all text-secondary",children:T},T))})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-secondary",children:"Current sitemap URLs"}),U.currentSitemapUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1",children:U.currentSitemapUrls.map(T=>e.jsx("li",{className:"break-all text-secondary",children:T},T))}):e.jsx("p",{className:"mt-1 text-secondary",children:"No matching URL was found."})]})]})]},U.property)),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",R.length," of ",v.length]}),R.length<v.length?e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>w(U=>U+As),children:"Show next 50 URL changes"}):null]})]}):e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Review the affected Properties before confirming."})]}),e.jsxs("label",{className:"flex min-h-11 items-center gap-2 text-sm text-primary",children:[e.jsx("input",{type:"radio",name:"advanced-measurement-coverage-resolution",checked:r.coverageResolution==="keep-existing",onChange:()=>r.onCoverageResolutionChange("keep-existing")}),"Keep existing Property URLs"]}),e.jsxs("label",{className:"flex min-h-11 items-center gap-2 text-sm text-primary",children:[e.jsx("input",{type:"radio",name:"advanced-measurement-coverage-resolution",checked:r.coverageResolution==="replace-with-imported",onChange:()=>r.onCoverageResolutionChange("replace-with-imported")}),"Use current sitemap URLs"]})]}):null,e.jsx(A,{type:"button",className:"min-h-11",onClick:()=>{r.onResolve()},children:"Confirm sitemap changes"})]})]})}):null,e.jsx("div",{className:"overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[720px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Properties"}),e.jsx("th",{children:"Queries"}),e.jsx("th",{children:"Groups"}),e.jsx("th",{children:"Assignments"}),e.jsx("th",{children:"Provider requests / run"})]})}),e.jsx("tbody",{children:e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-heading",children:n.properties}),e.jsx("td",{className:"tabular-nums text-heading",children:n.queries}),e.jsx("td",{className:"tabular-nums text-heading",children:n.groups}),e.jsx("td",{className:"tabular-nums text-heading",children:n.assignments??"—"}),e.jsx("td",{className:"tabular-nums text-heading",children:n.providerCalls??vg})]})})]})}),n.providerCalls===void 0?e.jsx("p",{className:"supporting-copy",children:"Review changes to see how many provider requests one run will make."}):null,n.assignments!==void 0&&n.assignments>n.queries?e.jsxs("p",{className:"supporting-copy",children:[n.queries," ",n.queries===1?"query":"queries"," aimed at markets and Properties"," ","produce ",n.assignments," assignment",n.assignments===1?"":"s",":"," ","a query aimed at a market is measured on every Property in it."]}):null,u?e.jsxs("section",{"aria-labelledby":"advanced-measurement-reviewed-changes-title",className:"border-y border-default py-4","aria-live":"polite",children:[e.jsx("h4",{id:"advanced-measurement-reviewed-changes-title",className:"text-sm font-medium text-heading",children:u.title}),u.items.length>0?e.jsx("ul",{className:"mt-3 list-disc space-y-2 pl-5 text-sm text-secondary",children:u.items.map((U,T)=>e.jsx("li",{children:U},`${U}-${T}`))}):null]}):null,e.jsxs("section",{"aria-labelledby":"advanced-measurement-flagged-exceptions-title",className:"space-y-3",children:[e.jsx("h4",{id:"advanced-measurement-flagged-exceptions-title",className:"text-sm font-medium text-heading",children:"Flagged exceptions"}),a.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No flagged exceptions."}):e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"divide-y divide-default border-y border-default",children:E.map(U=>e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3 py-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-heading",children:U.title}),U.detail?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:U.detail}):null]}),e.jsx(le,{tone:U.tone??"caution",children:"Needs attention"})]},U.id))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",E.length," of ",a.length]}),E.length<a.length?e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>M(U=>U+As),children:"Show next 50 exceptions"}):null]})]})]}),C?null:e.jsxs(e.Fragment,{children:[L&&m?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:m}):null,e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${o?"justify-between":"justify-end"}`,children:[o?e.jsx(A,{type:"button",variant:"outline",className:"min-h-11",onClick:o,children:"Back"}):null,i!==void 0&&!B?e.jsx(A,{type:"button",className:"min-h-11",disabled:d||!c,onClick:()=>{i()},children:d?"Reviewing changes…":"Review changes"}):e.jsx(A,{type:"button",className:"min-h-11",disabled:!x||g,onClick:()=>{h()},children:g?"Publishing setup…":"Publish setup"})]})]})]})}const Sg={proposed:{label:"New",tone:"caution"},confirmed:{label:"Included",tone:"positive"},excluded:{label:"Excluded",tone:"neutral"}};function Cg(t){return t.trim().toLocaleLowerCase()}function kg(t,s){return s?`${t.name} ${(t.urls??[t.url]).join(" ")}`.toLocaleLowerCase().includes(s):!0}function Ag({property:t}){const s=t.urls??[t.url];return s.length<=1?e.jsx("span",{children:s[0]??"No URL"}):e.jsxs("details",{children:[e.jsxs("summary",{className:"cursor-pointer text-xs font-medium text-primary",children:[s.length," URLs"]}),e.jsx("ul",{className:"mt-2 space-y-1",children:s.map(n=>e.jsx("li",{className:"break-all font-mono text-xs text-secondary",children:n},n))})]})}function Pg({canEdit:t,draft:s,onDraftChange:n,onReviewSitemap:a,reviewState:r}){const o=!t||r==="reviewing",i=o||!s.sitemapUrl.trim()||!s.examplePropertyUrl.trim()&&!s.propertyPathPattern.trim();function d(c,u){n({...s,[c]:u})}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-import-heading","aria-busy":r==="reviewing",children:[e.jsxs("div",{children:[e.jsx("h2",{id:"advanced-measurement-import-heading",className:"text-lg font-semibold text-heading",children:"Import Properties"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Review sitemap entries before choosing the Properties to measure."})]}),t?null:e.jsxs("div",{className:"mt-4 flex items-center gap-2 text-sm text-secondary",children:[e.jsx(le,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]}),e.jsxs("form",{className:"mt-5 space-y-4",onSubmit:c=>{c.preventDefault(),!i&&a(s)},children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-sitemap-url",className:"text-sm font-medium text-heading",children:"Sitemap URL"}),e.jsx("input",{id:"advanced-measurement-sitemap-url",type:"url",value:s.sitemapUrl,disabled:o,onChange:c=>d("sitemapUrl",c.target.value),placeholder:"https://example.com/sitemap.xml",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",{children:[e.jsx("label",{htmlFor:"advanced-measurement-example-property-url",className:"text-sm font-medium text-heading",children:"Example Property page"}),e.jsx("input",{id:"advanced-measurement-example-property-url",type:"url",required:!s.propertyPathPattern.trim(),value:s.examplePropertyUrl,disabled:o,onChange:c=>d("examplePropertyUrl",c.target.value),placeholder:"https://example.com/locations/example",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.jsx("p",{className:"mt-1 text-xs text-secondary",children:"This shows Canonry the Property URL pattern. Or enter the pattern under More import options."})]}),e.jsxs("details",{className:"rounded-md border border-default bg-surface-subtle p-3",children:[e.jsx("summary",{className:"cursor-pointer text-sm font-medium text-heading",children:"More import options"}),e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-preferred-host",className:"text-sm font-medium text-heading",children:"Use URLs from this domain"}),e.jsx("input",{id:"advanced-measurement-preferred-host",value:s.preferredHost,disabled:o,onChange:c=>d("preferredHost",c.target.value),placeholder:"example.com",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",{children:[e.jsx("label",{htmlFor:"advanced-measurement-property-path-pattern",className:"text-sm font-medium text-heading",children:"Property URL pattern"}),e.jsx("input",{id:"advanced-measurement-property-path-pattern",value:s.propertyPathPattern,disabled:o,onChange:c=>d("propertyPathPattern",c.target.value),placeholder:"/locations/*",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:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-additional-host",className:"text-sm font-medium text-heading",children:"Additional URL domain"}),e.jsx("input",{id:"advanced-measurement-additional-host",value:s.additionalHost,disabled:o,onChange:c=>d("additionalHost",c.target.value),placeholder:"properties.example.com",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",{children:[e.jsx("label",{htmlFor:"advanced-measurement-additional-path-pattern",className:"text-sm font-medium text-heading",children:"Additional URL pattern"}),e.jsx("input",{id:"advanced-measurement-additional-path-pattern",value:s.additionalPathPattern,disabled:o,onChange:c=>d("additionalPathPattern",c.target.value),placeholder:"/*",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.jsx("p",{className:"text-sm text-secondary md:col-span-2",children:"Use both fields when each Property also has a matching page on another domain."})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"advanced-measurement-excluded-paths",className:"text-sm font-medium text-heading",children:"Ignore these URL paths"}),e.jsx("textarea",{id:"advanced-measurement-excluded-paths",value:s.excludedPaths,disabled:o,onChange:c=>d("excludedPaths",c.target.value),placeholder:"/locations/archive",rows:3,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.jsx("p",{className:"mt-1 text-xs text-secondary",children:"One path per line. Use * at the beginning or end to match similar pages."})]})]})]}),e.jsx(A,{type:"submit",disabled:i,children:r==="reviewing"?"Reviewing sitemap…":"Review sitemap"})]})]})}function Rg({canEdit:t,properties:s,propertiesState:n,propertiesSearch:a,onPropertiesSearchChange:r,selectedPropertyIds:o,onSelectedPropertyIdsChange:i,onContinue:d,isContinuing:c=!1,onRetryProperties:u,onReturnToImport:m,maxVisibleProperties:x,onShowAllProperties:g}){const h=Cg(a),p=s.filter(E=>kg(E,h)),y=Math.max(1,x??p.length),j=p.slice(0,y),w=new Set(o),k=s.filter(E=>w.has(E.id)).map(E=>E.id),M=j.length<p.length;function C(E){const L=new Set(E);i(s.filter(B=>L.has(B.id)).map(B=>B.id))}function f(E,L){if(!t||c)return;const B=new Set(k);L?B.add(E):B.delete(E),C(B)}function v(){!t||c||C([...k,...j.map(E=>E.id)])}function S(){!t||c||i([])}function R(){!t||c||k.length===0||d(k)}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-properties-heading","aria-busy":n==="loading"||c,children:[e.jsxs("div",{children:[e.jsx("h2",{id:"advanced-measurement-properties-heading",className:"text-lg font-semibold text-heading",children:"Properties"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Choose the Properties to include, then continue."})]}),t?null:e.jsx("p",{className:"mt-4 text-sm text-secondary",children:"Viewing only. Property changes are unavailable."}),n==="loading"?e.jsxs("div",{className:"mt-5 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading Properties…"}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"If this does not finish, refresh the list."}),e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:u,children:"Refresh Properties"})]}):null,n==="error"?e.jsxs("div",{className:"mt-5 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{role:"alert",className:"text-sm text-negative",children:"Could not load Properties. Retry to request the current list."}),e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:u,children:"Retry"})]}):null,n==="ready"&&s.length===0?e.jsxs("div",{className:"mt-5 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{className:"text-sm text-secondary",children:"No Properties were found."}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Check the sitemap and review it again."}),e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:!t,onClick:m,children:"Review sitemap"})]}):null,n==="ready"&&s.length>0?e.jsxs("div",{className:"mt-5",children:[e.jsxs("div",{className:"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:a,disabled:c,onChange:E=>r(E.target.value),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"})]}),t?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:c,onClick:v,children:"Select all shown"}),e.jsx(A,{type:"button",variant:"ghost",size:"sm",disabled:c||k.length===0,onClick:S,children:"Clear selection"})]}):null]}),p.length===0?e.jsxs("div",{className:"mt-4 rounded-md border border-default bg-surface-subtle p-4",children:[e.jsx("p",{className:"text-sm text-secondary",children:"No Properties match this search."}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Clear the search or review the sitemap again."}),e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:!t,onClick:m,children:"Review sitemap"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-between gap-2 text-sm text-secondary",children:[e.jsxs("p",{children:["Showing ",j.length," of ",p.length," Properties"]}),e.jsxs("p",{children:[k.length," of ",s.length," selected"]})]}),e.jsx("div",{className:"mt-2 overflow-x-auto rounded-md border border-default",children:e.jsxs("table",{className:"w-full min-w-150 text-left text-sm","aria-label":"Properties to review",children:[e.jsx("thead",{className:"bg-surface-subtle text-xs font-medium uppercase tracking-wide text-secondary",children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",className:"px-3 py-2",children:"Property"}),e.jsx("th",{scope:"col",className:"px-3 py-2",children:"URL"}),e.jsx("th",{scope:"col",className:"px-3 py-2",children:"State"}),t?e.jsx("th",{scope:"col",className:"px-3 py-2 text-right",children:"Include"}):null]})}),e.jsx("tbody",{children:j.map(E=>{const L=Sg[E.state];return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"px-3 py-3 font-medium text-heading",children:E.name}),e.jsx("td",{className:"max-w-96 px-3 py-3 font-mono text-xs text-secondary",children:e.jsx(Ag,{property:E})}),e.jsx("td",{className:"px-3 py-3",children:e.jsx(le,{tone:L.tone,children:L.label})}),t?e.jsx("td",{className:"p-0 text-right",children:e.jsx("label",{className:"ml-auto flex min-h-11 min-w-11 cursor-pointer items-center justify-center",children:e.jsx("input",{type:"checkbox","aria-label":`Select ${E.name}`,checked:k.includes(E.id),disabled:c,onChange:B=>f(E.id,B.target.checked),className:"size-6 accent-accent"})})}):null]},E.id)})})]})}),M&&g?e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:c,onClick:g,children:"Show all Properties"}):null]}),t?e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-3",children:[e.jsx(A,{type:"button",variant:"ghost",disabled:c,onClick:m,children:"Back"}),e.jsx(A,{type:"button",disabled:c||k.length===0,onClick:R,children:c?"Saving Properties…":"Continue"})]}):null]}):null]})}function Ig(t){return t.activeStep==="import"?e.jsx(Pg,{canEdit:t.canEdit,draft:t.importDraft,onDraftChange:t.onImportDraftChange,onReviewSitemap:t.onReviewSitemap,reviewState:t.reviewState}):e.jsx(Rg,{...t})}const $g=[{id:"import",label:"Import"},{id:"properties",label:"Properties"},{id:"groups",label:"Groups"},{id:"queries",label:"Queries"},{id:"review",label:"Review and publish"}];function Tg({currentStep:t,hasDraft:s,canEdit:n,onDiscard:a,onStepChange:r,children:o}){const i=l.useRef(null),d=l.useRef(null),c=l.useRef(null),u=l.useRef(null),m=l.useRef(!1),[x,g]=l.useState(!1);return l.useEffect(()=>{s||g(!1)},[s]),l.useEffect(()=>{const h=m.current;m.current=x,x?c.current?.focus():h&&u.current?.focus()},[x]),l.useEffect(()=>{const h=i.current;if(i.current=t,h===null||h===t)return;const p=d.current?.querySelector('h1, h2, h3, [role="heading"]');p&&(p.tabIndex=-1,p.focus())},[t]),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"mb-3 flex flex-col items-start gap-3 sm:flex-row sm:flex-wrap sm:justify-between",children:[e.jsxs("div",{className:"min-w-0 w-full sm:flex-1",children:[e.jsx("h2",{children:"Advanced measurement setup"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-secondary",children:"Choose the Properties and queries you want to measure."})]}),s?e.jsxs("div",{className:"flex w-full flex-wrap items-center justify-between gap-3 sm:w-auto sm:justify-end",children:[e.jsx(le,{tone:"caution",children:"Unpublished changes"}),n&&a?x?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",role:"group","aria-label":"Confirm discard",children:[e.jsx("span",{className:"text-sm text-secondary",children:"Discard all unpublished changes?"}),e.jsx(A,{ref:c,type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>g(!1),children:"Keep editing"}),e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:a,children:"Discard unpublished changes"})]}):e.jsx(A,{ref:u,type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>g(!0),children:"Discard changes"}):null]}):null]}),e.jsx("div",{role:"group","aria-label":"Advanced measurement setup progress",className:"overflow-x-auto border-b border-default",children:e.jsx("ol",{className:"flex min-w-max gap-6",children:$g.map(h=>e.jsx("li",{children:r?e.jsx("button",{type:"button","aria-current":t===h.id?"step":void 0,onClick:()=>r(h.id),className:`block min-h-11 border-b-2 bg-transparent px-1 py-3 text-left text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400 ${t===h.id?"border-strong text-heading":"border-transparent text-secondary hover:text-heading"}`,children:h.label}):e.jsx("span",{"aria-current":t===h.id?"step":void 0,className:`block min-h-11 border-b-2 px-1 py-3 text-sm font-medium ${t===h.id?"border-strong text-heading":"border-transparent text-secondary"}`,children:h.label})},h.id))})}),e.jsx("div",{ref:d,children:o})]})}function Mg(t){const s=t.canEdit?"editor":"viewer";return t.currentStep==="import"||t.currentStep==="properties"?e.jsx(Ig,{...t.importProperties,activeStep:t.currentStep,canEdit:t.canEdit}):t.currentStep==="queries"?e.jsx(jg,{...t.queries,access:s,onManageProjectQueries:t.onManageProjectQueries}):t.currentStep==="groups"?e.jsx(Ng,{...t.groups,access:s}):"review"in t?e.jsx(wg,{...t.review,access:s}):null}function ma(t){return e.jsx(Tg,{currentStep:t.currentStep,hasDraft:t.hasDraft,canEdit:t.canEdit,onDiscard:t.onDiscard,onStepChange:t.onStepChange,children:Mg(t)})}function jl(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`web-${Date.now()}-${Math.random().toString(36).slice(2)}`}function Et(t){return{"If-Match":t,"Idempotency-Key":jl()}}function on(t){return t instanceof hn&&(t.statusCode===404||t.statusCode===409||t.statusCode===412)}function ns(t,s){return t instanceof hn?s:(t instanceof Error?t.message.trim():"")||s}function Lg(t){const s="Could not calculate assignment impact.";if(!(t instanceof hn)||t.code!=="VALIDATION_ERROR")return s;const n=t.message.trim();return t.details?.displayToOperator===!0&&n?n:s}const qg={loadSetup:t=>lt(()=>_d({client:W,path:{name:t}})),loadDraft:t=>lt(()=>Kd({client:W,path:{name:t}})),createDraft:(t,s)=>lt(()=>Gd({client:W,path:{name:t},headers:{"Idempotency-Key":jl()},body:{expectedActiveRevision:s}})),importSitemap:(t,s,n)=>lt(()=>Fd({client:W,path:{name:t},headers:Et(s),body:n})),applySitemapSelection:(t,s,n,a)=>lt(()=>Od({client:W,path:{name:t},headers:Et(s),body:{selections:n,selectedTargetKeys:a}})),previewAssignments:(t,s)=>lt(()=>Dd({client:W,path:{name:t},body:s})),applyAssignments:(t,s,n)=>lt(()=>Ed({client:W,path:{name:t},headers:Et(s),body:n})),replaceAssignments:(t,s,n)=>lt(()=>qd({client:W,path:{name:t},headers:Et(s),body:n})),applyPairedAssignments:(t,s,n)=>lt(()=>Ld({client:W,path:{name:t},headers:Et(s),body:{pairs:n}})),removeAssignment:(t,s,n,a)=>lt(()=>Md({client:W,path:{name:t},headers:Et(s),body:{targetKeys:n,queryId:a}})),excludeTarget:(t,s,n)=>lt(()=>Td({client:W,path:{name:t},headers:Et(s),body:{targetKey:n,cleanup:"assignments-and-group-memberships"}})),upsertTarget:(t,s,n)=>lt(()=>$d({client:W,path:{name:t},headers:Et(s),body:{target:n}})),upsertGroup:(t,s,n)=>lt(()=>Id({client:W,path:{name:t},headers:Et(s),body:{group:n}})),removeGroup:(t,s,n)=>lt(()=>Rd({client:W,path:{name:t},headers:Et(s),body:{groupKey:n}})),upsertCompetitor:(t,s,n)=>lt(()=>Pd({client:W,path:{name:t},headers:Et(s),body:n})),removeCompetitor:(t,s,n,a)=>lt(()=>Ad({client:W,path:{name:t},headers:Et(s),body:{groupKey:n,competitorKey:a}})),previewGroupMembership:(t,s)=>lt(()=>kd({client:W,path:{name:t},body:s})),applyGroupMembership:(t,s,n)=>lt(()=>Cd({client:W,path:{name:t},headers:Et(s),body:n})),compilePreview:t=>lt(()=>Sd({client:W,path:{name:t}})),diffPreview:t=>lt(()=>wd({client:W,path:{name:t}})),publish:(t,s,n)=>lt(()=>Nd({client:W,path:{name:t},headers:Et(s),body:n})),discard:(t,s)=>lt(()=>jd({client:W,path:{name:t},headers:Et(s)}))},to={sitemapUrl:"",examplePropertyUrl:"",preferredHost:"",propertyPathPattern:"",additionalHost:"",additionalPathPattern:"",excludedPaths:""},Ln={name:"",propertyIds:[],competitorDomains:""},so=50;function On(t){const s=t.trim();if(!s)return null;try{return new URL(s.includes("://")?s:`https://${s}`).hostname.toLocaleLowerCase()}catch{return null}}function Eg(t){const s=t.trim();if(!s)throw new Error("Add a sitemap URL.");let n;try{n=new URL(s.includes("://")?s:`https://${s}`)}catch{throw new Error("Sitemap URL must be a valid web address.")}return(n.pathname===""||n.pathname==="/")&&(n.pathname="/sitemap.xml"),n.toString()}function no(t){const s=t.propertyPathPattern.trim();if(s){const r=(s.startsWith("/")?s:`/${s}`).split("/").slice(1);if(r.filter(i=>i==="*"||i==="{slug}").length!==1||r.some(i=>i.includes("*")&&i!=="*"))throw new Error("Property URL pattern must contain exactly one * or {slug} segment.");return`/${r.map(i=>i==="*"?"{slug}":i).join("/")}`}const n=t.examplePropertyUrl.trim();if(!n)throw new Error("Add one example Property page so Canonry can identify the matching URLs.");try{const a=new URL(n).pathname.split("/").filter(Boolean);if(a.length===0)throw new Error;return a[a.length-1]="{slug}",`/${a.join("/")}`}catch{throw new Error("Example Property page must be a valid web address.")}}function Dg(t){const s=[],n=new Set;for(const a of t.split(/[\n,]+/)){const r=a.trim().replace(/\/+$/,"");if(!r)continue;const i=r.split("/").filter(Boolean).at(-1)??r,d=i.startsWith("*"),c=i.endsWith("*"),u=i.slice(d?1:0,c?-1:void 0).trim();if(!u)throw new Error("Ignored URL patterns must include text besides *.");const m=d&&c?"contains":d?"suffix":c?"prefix":"exact",x=`${m}:${u}`;n.has(x)||(n.add(x),s.push({kind:m,value:u}))}return s}function Og(t){const s=Eg(t.sitemapUrl),n=t.examplePropertyUrl.trim()?On(t.examplePropertyUrl):null,a=On(t.preferredHost)??n??On(s);if(!a)throw new Error("Add a valid sitemap or Property page URL.");const r=On(t.additionalHost),o=t.additionalHost.trim().length>0,i=t.additionalPathPattern.trim().length>0;if(o!==i||o&&!r)throw new Error("Add both an additional domain and its Property URL pattern.");const d=Dg(t.excludedPaths);return{sitemapUrl:s,rule:{primary:{host:a,pathTemplate:no(t)},...r?{aliases:[{host:r,pathTemplate:no({...t,examplePropertyUrl:"",propertyPathPattern:t.additionalPathPattern})}]}:{},...d.length>0?{excludedSlugPatterns:d}:{}}}}function Fg(t){return!t||t.authoring.targets.length===0?"import":t.authoring.targets.some(s=>s.status==="proposed")?"properties":t.authoring.assignments.length===0?"groups":t.baseActiveRevision===null?"review":"properties"}function Gg(t,s){return!t||t.authoring.targets.length===0?"import":!t.authoring.targets.some(n=>n.status!=="excluded")||t.authoring.targets.some(n=>n.status==="proposed")?"properties":t.authoring.assignments.length===0&&s==="review"?"groups":s}function ao(t){return[...new Set([...t.discoveredUrl?[t.discoveredUrl]:[],...t.urlMatchers])]}function Kg(t){return t==="included"?"confirmed":t==="excluded"?"excluded":"proposed"}function ir(t){return t?.authoring.targets.filter(s=>s.status!=="excluded").map(s=>s.stableKey)??[]}function Rr(t,s){const n=t.trim().toLocaleLowerCase().replace(/[^a-z0-9._~-]+/g,"-").replace(/^-+|-+$/g,"");return`${s}-${n||"item"}`.slice(0,128)}function ro(t){return On(t)}function Nl(t,s){if(s[0]!=="targets")return;const n=s[1];if(typeof n=="number")return t?.targets[n];if(typeof n=="string")return t?.targets.find(a=>a.stableKey===n)}function wl(t,s){if(s[0]!=="groups")return;const n=s[1];if(typeof n=="number")return t?.groups[n];if(typeof n=="string")return t?.groups.find(a=>a.stableKey===n)}function Sl(t,s){return s[0]==="assignments"&&typeof s[1]=="number"?t?.assignments[s[1]]:void 0}function Cl(t,s){return t?.targets.find(n=>n.stableKey===s)?.label??"a Property"}function _g(t,s){const n=Nl(t.authoring,s.path);if(!n)return;const a=s.path[2],r=s.path[3];if(a==="urlMatchers"&&typeof r=="number"){const o=n.urlMatchers[r];return o?`${n.label} — ${o}`:n.label}if(a==="aliases"&&typeof r=="number"){const o=n.aliases[r];return o?`${n.label} — ${o}`:n.label}return n.label}function Ug(t,s){const n=wl(t.authoring,s.path);if(!n)return;const a=s.path[2],r=s.path[3];if(a==="competitors"&&typeof r=="number"){const o=n.competitors.at(r)?.domain;return o?`${n.label} — ${o}`:n.label}if(a==="targetKeys"&&typeof r=="number"){const o=Cl(t.authoring,n.targetKeys[r]);return`${n.label} — ${o}`}return n.label}function Bg(t,s){const n=Sl(t.authoring,s.path);if(!n)return;const a=t.queries.find(r=>r.id===n.queryId)?.query??"an unavailable query";return`${Cl(t.authoring,n.targetKey)} — ${a}`}function Vg(t,s){return s.path[0]==="identities"?"Project domain":_g(t,s)??Ug(t,s)??Bg(t,s)}function io(t,s,n){const a=Sl(t.authoring,s.path);if(!a)return;const r={...t.authoring?.defaultContext,...a.contextOverride},o=s.path.at(-1);if(n==="models"&&typeof o=="string")return r.models?.[o];if(n==="locations"&&typeof o=="number")return r.locations?.[o]}function zg(t,s){const n=Vg(s,t);switch(t.ruleId){case"invalid-project-identity":return{title:"Fix the project domain",detail:"The project domain is not valid. Update it in project settings, then review again.",tone:"negative",affected:n};case"target-limit-exceeded":return{title:"Reduce Properties",detail:"This setup exceeds the Properties publishing limit. Remove some Properties, then review again.",tone:"negative"};case"duplicate-target-key":return{title:"Resolve duplicate Properties",detail:"Two Properties use the same setup identifier. Rename or recreate one, then review again.",tone:"negative",affected:n};case"no-included-targets":return{title:"Include a Property",detail:"Include at least one Property before publishing.",tone:"negative"};case"target-url-matcher-invalid":return{title:"Fix a Property URL",detail:"Use a valid web address, site-wide address, or URL pattern for this Property.",tone:"negative",affected:n};case"target-url-matcher-unowned":return{title:"Use a project domain",detail:"This Property URL must use the project domain or one of its subdomains.",tone:"negative",affected:n};case"target-url-matcher-ambiguous":return{title:"Separate Property URL coverage",detail:"This URL is assigned to more than one Property at the same specificity. Update one of the URLs.",tone:"negative",affected:n};case"target-alias-ambiguous":return{title:"Use distinct Property names",detail:"This name or alias matches another Property. Make each Property name and alias distinct.",tone:"negative",affected:n};case"execution-context-no-provider":return{title:"Choose a provider",detail:"Choose at least one provider before publishing.",tone:"negative",affected:n};case"invalid-provider-model":return{title:"Fix provider settings",detail:"Choose the provider that runs this model, or remove the model setting.",tone:"negative",affected:[n,io(s,t,"models")].filter(Boolean).join(" — ")||void 0};case"invalid-location":return{title:"Fix a location",detail:"Choose a location configured for this project, or remove it from the query.",tone:"negative",affected:[n,io(s,t,"locations")].filter(Boolean).join(" — ")||void 0};case"target-without-aliases":return{title:"Add Property aliases",detail:"Add a name or alias to measure mentions.",tone:"caution",affected:n};case"duplicate-group-key":return{title:"Resolve duplicate groups",detail:"Two groups use the same setup identifier. Rename one group, then review again.",tone:"negative",affected:n};case"group-unknown-target":return{title:"Fix group Properties",detail:"This group contains a Property that is no longer in setup. Remove it or add the Property back.",tone:"negative",affected:n};case"group-excluded-target":return{title:"Include or remove a grouped Property",detail:"This group contains an excluded Property. Include it or remove it from the group.",tone:"negative",affected:n};case"competitor-invalid-domain":return{title:"Fix a competitor domain",detail:"Enter a valid competitor domain.",tone:"negative",affected:n};case"competitor-matches-project":return{title:"Remove a project domain",detail:"A competitor cannot use the project domain.",tone:"negative",affected:n};case"competitor-duplicate":return{title:"Remove a duplicate competitor",detail:"List each competitor domain only once in a group.",tone:"negative",affected:n};case"duplicate-assignment":return{title:"Remove a duplicate query",detail:"Assign each query to a Property only once.",tone:"negative",affected:n};case"assignment-unknown-target":return{title:"Fix a query assignment",detail:"This query is assigned to a Property that is no longer in setup. Remove the assignment or add the Property back.",tone:"negative",affected:n};case"assignment-excluded-target":return{title:"Include or unassign a Property",detail:"This query is assigned to an excluded Property. Include it or remove the assignment.",tone:"negative",affected:n};case"assignment-unknown-query":return{title:"Remove an unavailable query",detail:"This assignment refers to a tracked query that is no longer available. Remove it or add the query back to the project.",tone:"negative",affected:n};case"assignment-unclassified":return{title:"Classify a query",detail:"Choose Branded or Non-brand for this query before publishing.",tone:"negative",affected:n};case"query-limit-exceeded":return{title:"Reduce queries",detail:"This setup exceeds the distinct-query publishing limit. Remove some query assignments, then review again.",tone:"negative"};case"target-without-assignments":return{title:"Assign queries",detail:"Assign at least one query to measure a Property.",tone:"caution",affected:n};case"invalid-compiled-plan":return{title:"Fix setup details",detail:"A setup value could not be validated. Review the affected item, then review again.",tone:"negative",affected:n};case"compiled-plan-too-large":return{title:"Reduce setup size",detail:"This setup is too large to publish. Remove Properties, queries, or groups, then review again.",tone:"negative"};case"active-revision-schema-v1":return{title:"Historical results will be kept",detail:"Existing results remain visible after you publish this setup.",tone:"neutral"}}return{title:t.severity==="fail"?"An unexpected setup issue blocks publishing":"An unexpected setup issue needs review",detail:t.severity==="fail"?"Review the affected item, make a correction, and review again. If it remains blocked, contact support.":"Review the affected item before publishing. If it remains, contact support.",tone:t.severity==="fail"?"negative":"caution",affected:n}}function ha(t,s,n=`${s}s`){return`${t} ${t===1?s:n}`}function kl(t){const s=[...new Set(t)];return s.length===0?"":s.length===1?` Affected: ${s[0]}.`:s.length<=3?` Affected: ${s.join(", ")}.`:` Affected: ${s.slice(0,3).join(", ")}, and ${s.length-3} more.`}function Qg(t,s,n,a){return`${(()=>{switch(t){case"execution-context-no-provider":return`${s} ${ha(n,"query assignment")} need${n===1?"s":""} a provider.`;case"target-without-aliases":return`${s} ${ha(n,"Property","Properties")} need${n===1?"s":""} aliases.`;case"target-without-assignments":return`${s} ${ha(n,"Property","Properties")} need${n===1?"s":""} queries.`;default:return n>1?`${s} ${ha(n,"item")} need review.`:s}})()}${kl(a)}`}function Hg(t,s){const n=new Map;for(const a of t){const r=zg(a,s),o=[a.ruleId,a.severity,r.title,r.detail].join("\0"),i=n.get(o)??{ruleId:a.ruleId,severity:a.severity,meaning:r,paths:new Set,affected:new Set};i.paths.add(JSON.stringify(a.path)),r.affected&&i.affected.add(r.affected),n.set(o,i)}return[...n.values()].map((a,r)=>({id:`${a.ruleId}-${a.severity}-${r}`,title:a.meaning.title,detail:Qg(a.ruleId,a.meaning.detail,a.paths.size,a.affected),tone:a.meaning.tone}))}function or(t){if(!t)return;const s=t.discoveredUrl??t.urlMatchers[0];return s?`${t.label} — ${s}`:t.label}function lr(t,s,n){const a=Nl(n,t.path),r=wl(n,t.path),o=t.path[2]==="rebind"&&typeof t.path[3]=="string"?t.path[3]:void 0,i=o?n?.targets.find(m=>m.stableKey===o):void 0,d=a?.label??r?.label,c=kl(d?[d]:[]),u={id:`${t.code}-${s}`,tone:"caution"};switch(t.code){case"merge-targets-noop":return{...u,title:"Choose another Property to merge",detail:`Select at least one other Property before merging.${c}`};case"excluded-target-has-assignments":return{...u,title:"Review excluded Property queries",detail:`An excluded Property still has assigned queries. Include it or remove those queries before publishing.${c}`};case"group-unknown-target":return{...u,title:"Fix group Properties",detail:`This group includes a Property that is not in setup. Remove it or add the Property first.${c}`};case"measurement.discovery.proposed_new_target":{const m=or(a)??"the proposed Property";return{...u,title:"Review a new Property",detail:`Review ${m}. It did not match an existing Property.`}}case"measurement.discovery.proposed_rebind":{const m=or(a)??"the proposed Property",x=i?.label??"an existing Property";return{...u,title:"Review a moved Property",detail:`Review ${m}. It may be the same Property as ${x}.`}}case"measurement.discovery.rebind_ambiguous":{const m=or(a)??"the proposed Property",x=i?.label??"an existing Property";return{...u,title:"Choose an existing Property",detail:`Review ${m}. It may match ${x}; choose the correct Property.`}}default:return{...u,title:"Unexpected setup warning",detail:"Review the latest setup change before publishing. If this warning remains, contact support."}}}function Wg(t,s=!1){const n=[],a=t.targets.added.length+t.targets.removed.length+t.targets.changed.length,r=t.groups.added.length+t.groups.removed.length+t.groups.changed.length,o=t.assignments.added+t.assignments.removed+t.assignments.reclassified;return a>0&&n.push(`${a} Property ${a===1?"change":"changes"}`),o>0&&n.push(`${o} query assignment ${o===1?"change":"changes"}`),r>0&&n.push(`${r} group ${r===1?"change":"changes"}`),s&&n.unshift("Existing results remain visible after you publish this setup."),{title:s?"Historical results will be kept":t.activeRevision===null?"New setup ready":"Changes ready",items:n.length>0?n:["No changes from the published setup."]}}function ys(t){return[...new Set(t)]}function Us(t){return ys(t).sort()}function Yg(t,s,n){return t.kind==="groups"?{groupKeys:Us(t.groupIds),queryIds:Us(n)}:{targetKeys:Us(t.kind==="all"?s:t.propertyIds),queryIds:Us(n)}}function Jg(t){return{assignmentCount:t.assignments.requested,addedAssignments:t.assignments.added,alreadyPresentAssignments:t.assignments.alreadyPresent,resolvedPropertyCount:t.resolvedTargetKeys.length,overlapCount:t.overlapCount,addedProviderCalls:t.execution.addedProviderCalls,fullRunProviderCalls:t.execution.fullRunProviderCalls}}function oo(t){return t.kind==="exact"?t.url??"":t.kind==="prefix"?`https://${t.host??""}${t.pathPrefix==="/"?"":t.pathPrefix??""}/*`:t.host??""}function Xg(t){const s=t.plan;if(s.schemaVersion===2)return{defaultContext:{providers:[],locations:[]},targets:s.targets.map(a=>({stableKey:a.stableKey,label:a.label,status:"included",aliases:[...a.aliases],urlMatchers:a.urlMatchers.map(oo).filter(Boolean),source:a.discoveryIdentity?"sitemap":"manual",...a.discoveryIdentity?{discoveryIdentity:a.discoveryIdentity}:{}})),assignments:s.assignments.map(a=>({targetKey:a.targetKey,queryId:a.queryId,queryClass:a.queryClass,classificationSource:"operator"})),groups:s.groups.map(a=>({stableKey:a.stableKey,label:a.label,targetKeys:[...a.targetKeys],competitors:a.competitors.map(r=>({...r,aliases:[...r.aliases]}))}))};const n=s.targetQuerySelections.flatMap(a=>a.queryIds.map(r=>({targetKey:a.targetKey,queryId:r,queryClass:"unclassified",classificationSource:"rule"})));return{defaultContext:{providers:[],locations:[]},targets:s.targets.map(a=>({stableKey:a.stableKey,label:a.label,status:"included",aliases:[...a.aliases],urlMatchers:a.urls.map(oo).filter(Boolean),source:"manual"})),assignments:n,groups:s.groups.map(a=>({stableKey:a.stableKey,label:a.label,targetKeys:[...a.targetKeys],competitors:(a.competitors??[]).map(r=>({stableKey:Rr(r,"competitor"),label:r,domain:r,aliases:[]}))}))}}function Zg({projectName:t,queries:s,isQueryLoading:n,isQueryError:a,onRetryQueries:r,publishedPlan:o,canEdit:i=!0,onCreateQueries:d,onManageProjectQueries:c,onPublished:u,service:m=qg}){const[x,g]=l.useState(null),[h,p]=l.useState(null),[y,j]=l.useState("import"),[w,k]=l.useState(!0),[M,C]=l.useState(null),[f,v]=l.useState(null),[S,R]=l.useState([]),[E,L]=l.useState({...to}),[B,U]=l.useState("idle"),[T,N]=l.useState(""),[D,J]=l.useState(so),[G,Z]=l.useState([]),[de,se]=l.useState([]),[Q,$]=l.useState({kind:"all"}),[ie,O]=l.useState(null),[_,X]=l.useState(null),[ge,H]=l.useState(!1),[ae,ue]=l.useState(null),[Oe,Fe]=l.useState(0),[Pe,tt]=l.useState(null),[it,ke]=l.useState({...Ln}),[Xe,_e]=l.useState(null),[Ve,He]=l.useState(""),[Te,V]=l.useState(null),[F,z]=l.useState(!1),[Ne,Ie]=l.useState(!1),[ee,We]=l.useState(null),[ht,Ze]=l.useState(null),[ye,Ge]=l.useState(null),[It,xt]=l.useState(null),[qe,Ye]=l.useState(null),pt=l.useRef(0),St=l.useRef(0),Ke=h?.draft??null,Le=h?.etag??null,et=l.useMemo(()=>!i&&o?{baseActiveRevision:o.revision,authoring:Xg(o)}:null,[i,o]),Ue=Ke??et;async function Be(q){const ne=++pt.current;k(!0),C(null);try{let[fe,re]=await Promise.all([m.loadSetup(t),m.loadDraft(t)]);if(!re.draft&&q&&i&&(await m.createDraft(t,fe.activeRevision),[fe,re]=await Promise.all([m.loadSetup(t),m.loadDraft(t)])),ne!==pt.current)return;g(fe),p(re),j(Fg(re.draft));const oe=ir(re.draft);Z(oe)}catch(fe){if(ne!==pt.current)return;C(ns(fe,"Could not load advanced measurement setup."))}finally{ne===pt.current&&k(!1)}}l.useEffect(()=>(Be(!0),()=>{pt.current+=1}),[t,i,m]),l.useEffect(()=>{!w&&!Ke&&et&&j("properties")},[Ke,w,et]);async function $t(){const q=await m.loadDraft(t);return p(q),q}async function vt(q){Ye(null);try{const[ne,fe]=await Promise.all([m.loadSetup(t),m.loadDraft(t)]);g(ne),p(fe);const re=ir(fe.draft);Z(re),j(oe=>Gg(fe.draft,oe)),v(q)}catch(ne){v(ns(ne,q))}}async function Ft(q,ne,fe,re={}){const{preserveBusyAction:oe=!1}=re;if(!i||!Le||ye&&!oe)return null;oe||Ge(q),v(null),Ye(null);try{const $e=await ne(Le),Wt=await $t();return R(($e.warnings??[]).map((yt,ps)=>lr(yt,ps,Wt.draft?.authoring))),Wt}catch($e){return on($e)?await vt("This setup changed in another session. The latest draft is loaded; review your changes again."):v(ns($e,fe)),null}finally{oe||Ge(null)}}const gt=l.useMemo(()=>(Ue?.authoring.targets??[]).map(q=>{const ne=ao(q);return{id:q.stableKey,name:q.label,url:ne[0]??"No URL",urls:ne,state:Kg(q.status)}}),[Ue]),Y=l.useMemo(()=>Ue?.authoring.targets.filter(q=>q.status==="included")??[],[Ue]),Re=l.useMemo(()=>Y.map(q=>({id:q.stableKey,label:q.label,urlCount:ao(q).length})),[Y]),be=Ue?.authoring.assignments.length??0,je=l.useMemo(()=>{if(!Ue)return[];const q=new Set(s.map(re=>re.id)),ne=s.map(re=>({id:re.id,text:re.query,source:"saved-project-queries",propertyIds:ys(Ue.authoring.assignments.filter(oe=>oe.queryId===re.id).map(oe=>oe.targetKey))})),fe=ys(Ue.authoring.assignments.map(re=>re.queryId).filter(re=>!q.has(re))).map(re=>({id:re,source:"unavailable-tracked-query",state:"missing",propertyIds:ys(Ue.authoring.assignments.filter(oe=>oe.queryId===re).map(oe=>oe.targetKey))}));return[...ne,...fe]},[s,Ue]),Gt=l.useMemo(()=>(Ue?.authoring.groups??[]).map(q=>({id:q.stableKey,name:q.label,propertyIds:q.targetKeys,competitors:q.competitors.map(ne=>ne.domain)})),[Ue]),ze=l.useMemo(()=>{if(de.length===0)return null;const q=Yg(Q,Re.map(fe=>fe.id),de);return(q.groupKeys?.length??q.targetKeys?.length??0)>0?q:null},[Q,Re,de]),ft=ze?JSON.stringify(ze):"";l.useEffect(()=>{const q=ze,ne=++St.current;if(!i||!Ke||!Le||!q){O(null),X(null),ue(null),H(!1);return}O(null),X(null),ue(null),H(!0);const fe=window.setTimeout(()=>{m.previewAssignments(t,q).then(re=>{if(ne===St.current){if(re.draftEtag!==Le){O(null),X(null),ue("The setup changed while calculating assignment impact. Refresh the draft and try again.");return}O(re),X(ft)}}).catch(re=>{ne===St.current&&(O(null),X(null),ue(Lg(re)))}).finally(()=>{ne===St.current&&H(!1)})},250);return()=>{window.clearTimeout(fe),St.current+=1}},[ze,ft,Oe,i,Ke,Le,t,m]);const Tt=l.useMemo(()=>[...be===0?[{id:"no-query-assignments",title:"Assign at least one query",detail:"Apply a tracked query to at least one Property before publishing.",tone:"negative"}]:[],...Ue?.authoring.assignments.some(q=>q.queryClass==="unclassified")&&!(et&&o?.plan.schemaVersion===1)?[{id:"unclassified-query-assignments",title:"Remove an unavailable query",detail:"One or more saved assignments no longer have a tracked query. Clear them before publishing.",tone:"negative"}]:[],...S],[be,et,o,S,Ue]),ls=n?{status:"unavailable",message:"Tracked queries are loading."}:a?{status:"unavailable",message:"Tracked queries could not be loaded. Retry before assigning Properties."}:{status:"available"};async function Mt(q){let ne;try{ne=Og(q)}catch(re){v(ns(re,"Check the sitemap details and try again."));return}L(q),U("reviewing");const fe=await Ft("import",re=>m.importSitemap(t,re,ne),"Could not review this sitemap.");if(fe?.draft){const re=fe.draft.authoring.targets.filter($e=>$e.status==="proposed").map($e=>$e.stableKey),oe=fe.draft.authoring.targets.filter($e=>$e.status==="included").map($e=>$e.stableKey);Z([...oe,...re]),N(""),J(so),j("properties"),U("idle")}else U("error")}async function Kt(q){if(!d||q.length===0||ye)return[];Ge("create-queries"),xt(null);try{return await d(q)}catch(ne){throw xt(mt(ne)),ne}finally{Ge(null)}}async function ot(q){if(!Ke||!Le||ye)return;const ne=new Set(q),re=Ke.authoring.targets.filter($e=>$e.status==="proposed"&&$e.discoveryIdentity).map($e=>({discoveryIdentity:$e.discoveryIdentity,action:ne.has($e.stableKey)?"create":"ignore"})),oe=re.length>0||Ke.authoring.targets.some($e=>$e.status!=="proposed"&&$e.status==="included"!==ne.has($e.stableKey));Ge("properties"),v(null),Ye(null);try{if(!oe){Z([...ne]),$({kind:"all"}),j("groups");return}await m.applySitemapSelection(t,Le,re,[...ne]);const $e=await $t(),Wt=ir($e.draft);Z(Wt),$({kind:"all"}),j("groups")}catch($e){on($e)?await vt("This setup changed in another session. The latest Properties are loaded."):v(ns($e,"Could not save the selected Properties."))}finally{Ge(null)}}async function cs(q){const ne=q.groupIds&&q.groupIds.length>0?{groupKeys:Us(q.groupIds),queryIds:Us(q.queryIds)}:{targetKeys:Us(q.propertyIds),queryIds:Us(q.queryIds)};if(!ie||_!==JSON.stringify(ne)||!Le||ie.draftEtag!==Le){v("Review the latest assignment impact before assigning queries.");return}await Ft("assignments",re=>m.applyAssignments(t,re,ne),"Could not apply these queries.")&&(se([]),tt(`${ie.assignments.added} new assignment${ie.assignments.added===1?"":"s"} added. Existing assignments were kept.`))}async function Ct(q){if(q.propertyIds.length===0)return;await Ft("replace-assignments",fe=>m.replaceAssignments(t,fe,{targetKeys:ys(q.propertyIds),queryIds:[q.queryId]}),"Could not replace this query assignment.")&&(se(fe=>fe.filter(re=>re!==q.queryId)),tt("Query assignments replaced."))}async function Ts(q,ne=!1){if(q.length===0)return;if(!await Ft("paired-assignments",re=>m.applyPairedAssignments(t,re,[...q]),"Could not assign these queries.",{preserveBusyAction:ne}))throw new Error("Could not assign these queries.")}async function zt(q){if(!(!i||!d||q.length===0||ye)){Ge("create-and-pair-questions"),xt(null);try{let ne;try{ne=await d(ys(q.map(oe=>oe.text)))}catch(oe){throw xt(mt(oe)),oe}const fe=new Map(ne.map(oe=>[oe.query,oe.id])),re=q.map(oe=>({targetKey:oe.propertyId,queryId:fe.get(oe.text)})).filter(oe=>oe.queryId!==void 0);if(re.length!==q.length){const oe=new Error("The created queries could not be matched to their Properties.");throw xt("The queries were added, but could not be paired with every Property. Try again to pair them."),oe}try{await Ts(re,!0)}catch(oe){throw xt("The queries were added, but could not be assigned to their Properties. Try again to pair them."),oe}}finally{Ge(null)}}}async function Zt(q){if(!Ke)return;const ne=ys(Ke.authoring.assignments.filter(re=>re.queryId===q).map(re=>re.targetKey));if(ne.length===0)return;await Ft(`remove-${q}`,re=>m.removeAssignment(t,re,ne,q),"Could not clear this query assignment.")&&se(re=>re.filter(oe=>oe!==q))}async function Qt(q){if(!Ke||!Le||ye)return;const ne=q.name.trim();if(!ne)return;const fe=Xe??Rr(ne,"group"),re=Ke.authoring.groups.find(yt=>yt.stableKey===fe);if(re&&Xe===null){v(`A group named "${re.label}" already exists. Edit it or choose a different name.`);return}const oe=q.competitorDomains.split(/[\s,]+/).map(yt=>yt.trim()).filter(Boolean),$e=oe.find(yt=>ro(yt)===null);if($e){v(`"${$e}" is not a valid competitor domain.`);return}const Wt=ys(oe.map(yt=>ro(yt)));Ge("group"),v(null),Ye(null);try{const yt=await m.upsertGroup(t,Le,{stableKey:fe,label:ne,targetKeys:ys(q.propertyIds),competitors:Wt.map(P=>re?.competitors.find(me=>me.domain===P)??{stableKey:Rr(P,"competitor"),label:P,domain:P,aliases:[]})}),ps=await $t();R(yt.warnings.map((P,me)=>lr(P,me,ps.draft?.authoring))),ke({...Ln}),_e(null)}catch(yt){on(yt)?await vt("This setup changed in another session. The latest groups are loaded."):v(ns(yt,"Could not save this group."))}finally{Ge(null)}}function dt(q){const ne=Ke?.authoring.groups.find(fe=>fe.stableKey===q);ne&&(_e(q),ke({name:ne.label,propertyIds:[...ne.targetKeys],competitorDomains:ne.competitors.map(fe=>fe.domain).join(", ")}))}async function ws(q){await Ft("remove-group",fe=>m.removeGroup(t,fe,q),"Could not remove this group.")&&($(fe=>fe.kind==="groups"&&fe.groupIds.includes(q)?{kind:"all"}:fe),Xe===q&&(_e(null),ke({...Ln})))}function Ht(q){He(q),V(null),We(null),Ze(null)}async function ct(){if(!(!i||!Ve.trim()||F||Ne)){z(!0),We(null),Ze(null);try{V(await m.previewGroupMembership(t,{csv:Ve}))}catch(q){V(null),We(ns(q,"Could not review this CSV."))}finally{z(!1)}}}async function ms(q){if(!(!i||!Le||!Te||q.length===0||ye)){if(Te.draftEtag!==Le){We("The setup changed while this CSV was open. Review the latest CSV before applying it.");return}Ie(!0),Ge("group-import"),We(null),Ze(null),Ye(null);try{const ne=await m.applyGroupMembership(t,Le,{csv:Ve,sourceChecksum:Te.sourceChecksum,previewChecksum:Te.previewChecksum,acceptedRows:ys(q.map(String)).map(Number)}),fe=await $t();R(ne.warnings.map((re,oe)=>lr(re,oe,fe.draft?.authoring))),He(""),V(null),Ze(`${ne.addedMemberships} membership${ne.addedMemberships===1?"":"s"} added${ne.unchangedMemberships>0?`; ${ne.unchangedMemberships} already present`:""}.`)}catch(ne){on(ne)?(await vt("This setup changed in another session. The latest draft is loaded; review the CSV again."),We("The setup changed while this CSV was open. Review the latest CSV before applying it.")):We(ns(ne,"Could not apply this CSV."))}finally{Ge(null),Ie(!1)}}}async function jt(){if(!(!Ke||!Le||ye||be===0)){Ge("review"),v(null),Ye(null);try{const[q,ne]=await Promise.all([m.compilePreview(t),m.diffPreview(t)]),fe=[...q.checks,...ne.checks],re=fe.some(oe=>oe.ruleId==="active-revision-schema-v1");if(R(Hg(fe.filter(oe=>oe.ruleId!=="active-revision-schema-v1"),{authoring:Ue?.authoring,queries:s})),!q.ok||!ne.ok)return;if(ne.diff.activeRevision!==Ke.baseActiveRevision){await vt("The published setup changed while you were reviewing. The latest draft is loaded; review it again.");return}if(q.compiledChecksum!==ne.compiledChecksum){v("The setup changed while it was being reviewed. Review the latest changes again.");return}Ye({etag:Le,baseActiveRevision:Ke.baseActiveRevision,compiledChecksum:q.compiledChecksum,changes:Wg(ne.diff,re),providerCalls:q.plan.executionNodes.reduce((oe,$e)=>oe+$e.expectedSnapshots,0)})}catch(q){v(ns(q,"Could not review this setup."))}finally{Ge(null)}}}async function es(){if(!(!Ke||!Le||!qe||ye)){if(Le!==qe.etag||Ke.baseActiveRevision!==qe.baseActiveRevision){Ye(null),v("The setup changed after review. Review the latest changes before publishing.");return}Ge("publish"),v(null);try{await m.publish(t,Le,{expectedActiveRevision:qe.baseActiveRevision,expectedCompiledChecksum:qe.compiledChecksum}),p({draft:null,etag:null}),Ye(null),u?.()}catch(q){on(q)?await vt("The setup changed before it could be published. Review the latest draft and publish again."):v(ns(q,"Could not publish this setup."))}finally{Ge(null)}}}async function hs(){if(!(!Le||ye)){Ge("discard"),v(null);try{await m.discard(t,Le),p({draft:null,etag:null}),Ye(null),u?.()}catch(q){on(q)?await vt("This setup changed in another session. The latest draft is loaded."):v(ns(q,"Could not discard these changes."))}finally{Ge(null)}}}async function xs(){if(!(!Ke||!Le||!x||ye)){Ge("restart"),v(null),Ye(null);try{await m.discard(t,Le),await m.createDraft(t,x.activeRevision),L({...to}),N(""),Z([]),se([]),$({kind:"all"}),O(null),ue(null),tt(null),ke({...Ln}),_e(null),He(""),V(null),We(null),Ze(null),await Be(!1)}catch(q){on(q)?await vt("The setup changed again. Reloaded the latest draft and published setup."):v(ns(q,"Could not restart this setup."))}finally{Ge(null)}}}if(w)return e.jsxs("section",{"aria-labelledby":"advanced-measurement-loading-title",className:"space-y-4",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"advanced-measurement-loading-title",children:"Advanced measurement setup"})}),e.jsx("div",{className:"h-28 animate-pulse rounded-md bg-surface-subtle","aria-label":"Loading advanced measurement setup"})]});if(M)return e.jsxs("section",{"aria-labelledby":"advanced-measurement-error-title",className:"space-y-4",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"advanced-measurement-error-title",children:"Advanced measurement setup"})}),e.jsxs("div",{role:"alert",className:"border-y border-negative-800/40 bg-negative-950/20 py-4 text-sm text-negative",children:[e.jsx("p",{children:M}),e.jsx(A,{className:"mt-3 min-h-11",type:"button",size:"sm",variant:"outline",onClick:()=>{Be(!0)},children:"Try again"})]})]});if(!Ue||i&&!Le)return e.jsxs("section",{"aria-labelledby":"advanced-measurement-empty-title",className:"space-y-4",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"advanced-measurement-empty-title",children:"Advanced measurement setup"})}),e.jsx("p",{className:"text-sm text-secondary",children:i?"Start setup from the project Overview.":"No advanced setup is available to review."})]});if(i&&Ke&&x&&Ke.baseActiveRevision!==x.activeRevision)return e.jsxs("section",{"aria-labelledby":"advanced-measurement-stale-draft-title",className:"space-y-4",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"advanced-measurement-stale-draft-title",children:"Advanced measurement setup"})}),e.jsxs("div",{role:"alert",className:"border-y border-caution-800/40 bg-caution-950/20 py-4",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"This draft is based on an older published setup."}),e.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Restart from the latest setup before making more changes."}),e.jsx(A,{className:"mt-3 min-h-11",type:"button",size:"sm",variant:"outline",disabled:ye==="restart",onClick:()=>{xs()},children:ye==="restart"?"Restarting…":"Discard draft and restart"})]}),f?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:f}):null]});const Lt=a&&r?e.jsx("div",{className:"flex justify-end",children:e.jsx(A,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:r,children:"Retry queries"})}):null;return e.jsxs("div",{className:"space-y-4",children:[x?.mode==="active-v1"?e.jsx("p",{role:"status",className:"border-y border-caution-800/40 bg-caution-950/20 py-3 text-sm text-secondary",children:"Review and publish this setup to enable class-filtered reporting."}):null,f?e.jsx("p",{role:"alert",className:"border-y border-negative-800/40 bg-negative-950/20 py-3 text-sm text-negative",children:f}):null,Lt,y==="import"||y==="properties"?e.jsx(ma,{currentStep:y,hasDraft:Ke!==null,canEdit:i,onStepChange:i?void 0:j,onDiscard:()=>{hs()},importProperties:{importDraft:E,onImportDraftChange:q=>{L(q),U("idle"),v(null)},onReviewSitemap:q=>{Mt(q)},reviewState:B,properties:gt,propertiesState:"ready",propertiesSearch:T,onPropertiesSearchChange:N,maxVisibleProperties:D,onShowAllProperties:()=>J(gt.length),selectedPropertyIds:G,onSelectedPropertyIdsChange:q=>Z([...q]),onContinue:q=>{ot(q)},isContinuing:ye==="properties",onRetryProperties:()=>{$t()},onReturnToImport:()=>j("import")}}):y==="queries"?e.jsx(ma,{currentStep:"queries",hasDraft:Ke!==null,canEdit:i,onStepChange:i?void 0:j,onDiscard:()=>{hs()},onManageProjectQueries:c,queries:{onCreateQueries:d?q=>Kt(q):void 0,isCreatingQueries:ye==="create-queries"||ye==="create-and-pair-questions",isBusy:ye!==null,createQueriesError:It,availability:ls,properties:Re,queries:je,selectedQueryIds:de,isApplying:ye==="assignments"||ye==="paired-assignments",onSelectedQueryIdsChange:q=>se([...q]),onApplySelectedQueries:q=>cs(q),groups:Gt,audience:Q,onAudienceChange:q=>{$(q),tt(null)},assignmentImpact:ie&&_===ft?Jg(ie):null,isPreviewingAssignmentImpact:ge,assignmentImpactError:ae,onRetryAssignmentImpact:()=>Fe(q=>q+1),assignmentNotice:Pe,onReplaceAssignments:Ct,isReplacingAssignments:ye==="replace-assignments",onCreateAndPairQuestions:i&&d?zt:void 0,onClearQueryAssignments:Zt,onRemoveQuery:Zt,canContinue:be>0,onBack:()=>j("groups"),onContinue:()=>j("review")}}):y==="groups"?e.jsx(ma,{currentStep:"groups",hasDraft:Ke!==null,canEdit:i,onStepChange:i?void 0:j,onDiscard:()=>{hs()},groups:{properties:Re,groups:Gt,groupDraft:it,isSaving:ye==="group",onGroupDraftChange:ke,onSaveGroup:Qt,onEditGroup:q=>dt(q.id),onRemoveGroup:ws,onClearGroupDraft:()=>{_e(null),ke({...Ln})},membershipImport:{csv:Ve,preview:Te,isReviewing:F,isApplying:Ne,error:ee,notice:ht,onCsvChange:Ht,onReview:ct,onApply:ms},onBack:()=>{j("properties")},onContinue:()=>j("queries")}}):e.jsx(ma,{currentStep:"review",hasDraft:Ke!==null,canEdit:i,onStepChange:i?void 0:j,onDiscard:()=>{hs()},review:{counts:{properties:Y.length,queries:new Set(Ue.authoring.assignments.map(q=>q.queryId)).size,groups:Ue.authoring.groups.length,assignments:Ue.authoring.assignments.length,providerCalls:qe?.providerCalls},flaggedExceptions:Tt,reviewedChanges:qe?.changes,isReviewing:ye==="review",canReviewChanges:be>0&&!ye,onReviewChanges:jt,onBack:()=>j("queries"),canPublish:qe!==null&&!ye,isPublishing:ye==="publish",onPublish:es}})]})}const ef=[{key:"label",label:"Property",numeric:!1},{key:"mentionCoverage",label:"Mention",numeric:!0},{key:"citationCoverage",label:"Citation",numeric:!0}];function lo(t){return t.label!=="Complete"}const ln="__all_properties__",tf=50,Al=50,sf=20,nf=50,af=250,rf=5,of=[{value:"all",label:"All queries"},{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],lf={"this-property":"Matches this Property","another-property":"Matches another Property","owned-unassigned":"Site URL not included in a Property",external:"External URL","multiple-properties":"Matches multiple Properties","invalid-url":"Invalid URL"},Pl={plan_v1:"Setup update required.",no_completed_run:"Not measured yet.",no_population:"No matching queries.",evidence_incomplete:"Evidence incomplete.",not_applicable:"Not applicable.",incomplete:"The latest measurement is incomplete.","evidence-incomplete":"Some source evidence is incomplete.","no-population":"No measurements are available for this selection.",unavailable:"This measurement is unavailable."},cf={numerator:null,denominator:null,reason:"plan_v1"};function Kn(t){return t.numerator===null?!1:Number.isFinite(t.numerator)&&Number.isFinite(t.denominator)&&t.numerator>=0&&t.denominator>0&&t.numerator<=t.denominator}function df(t){return Kn(t)?`${t.numerator} of ${t.denominator} (${Math.round(t.numerator/t.denominator*100)}%)`:"N/A"}function Rl(t){if(Kn(t))return"";const s=t.reason??"unavailable";return Pl[s]??s}function co(t){const s=[];return t.market&&s.push(t.market),t.urls.length>0&&s.push(`${t.urls.length} ${t.urls.length===1?"URL":"URLs"}`),s.join(" · ")}function uf(t,s){return!Number.isFinite(t)||!Number.isFinite(s)||t<0||s<=0||t>s?null:`${t} of ${s}`}function mf(t){const s=t.trim();return s&&!s.toLocaleLowerCase().includes("unavailable")?s:null}function hf(t){return t?.closest?.('button, a, input, select, textarea, [role="button"]')!=null}function Fn({metric:t,compact:s=!1}){const n=s?Kn(t)?"text-sm font-medium text-primary":"text-sm font-medium text-secondary":Kn(t)?"text-lg font-semibold text-heading":"text-lg font-semibold text-secondary";return e.jsx("span",{className:"inline-flex flex-wrap items-baseline gap-x-1.5 gap-y-1 tabular-nums",...Kn(t)?{}:{title:Rl(t)},children:e.jsx("span",{className:n,children:df(t)})})}function Br({shown:t,total:s,onShowAll:n,itemLabel:a}){return t>=s?null:e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",t," of ",s]}),e.jsxs(A,{size:"sm",variant:"outline",onClick:n,children:["Show all ",s," ",a]})]})}function uo({title:t,values:s,emptyLabel:n,valueClassName:a="text-secondary"}){const[r,o]=l.useState(Al),i=s.slice(0,r);return e.jsxs("section",{"aria-label":t,children:[e.jsx("h4",{className:"text-sm font-medium text-heading",children:t}),s.length===0?e.jsx("p",{className:"mt-2 text-sm text-secondary",children:n}):e.jsxs(e.Fragment,{children:[e.jsx("ul",{className:"mt-2 space-y-1.5 text-sm",children:i.map((d,c)=>e.jsx("li",{className:a,children:d},`${d}:${c}`))}),e.jsx(Br,{shown:i.length,total:s.length,itemLabel:t.toLocaleLowerCase(),onShowAll:()=>o(Number.MAX_SAFE_INTEGER)})]})]})}function xf({evidence:t,state:s="ready",onRetry:n}){const[a,r]=l.useState(Al),o=t.slice(0,a);return e.jsxs("section",{"aria-label":"Evidence",children:[e.jsx("h4",{className:"text-sm font-medium text-heading",children:"Evidence"}),s==="loading"?e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"Loading evidence…"}):s==="error"?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsx("span",{children:"Evidence could not be loaded."}),n?e.jsx(A,{type:"button",size:"sm",variant:"outline",onClick:n,children:"Retry evidence"}):null]}):t.length===0?e.jsx("p",{className:"mt-2 text-sm text-secondary",children:"No source evidence is available."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-2 overflow-x-auto rounded-md border border-default",children:e.jsxs("table",{className:"evidence-table min-w-[640px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Query"}),e.jsx("th",{children:"URL"})]})}),e.jsx("tbody",{children:o.map(i=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("span",{className:"flex flex-wrap items-center gap-1",children:[e.jsx(le,{tone:i.tone,children:lf[i.kind]}),i.historical?e.jsx(le,{tone:"caution",children:"Historical"}):null]})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:i.query}),i.provider||i.location?e.jsx("span",{className:"mt-1 block text-xs text-muted",children:[i.provider,i.location].filter(Boolean).join(" · ")}):null]}),e.jsx("td",{className:"break-all text-secondary",children:i.url})]},i.id))})]})}),e.jsx(Br,{shown:o.length,total:t.length,itemLabel:"evidence items",onShowAll:()=>r(Number.MAX_SAFE_INTEGER)})]})]})}function pf({property:t,onRetryEvidence:s}){return e.jsxs("div",{className:"space-y-5 py-2",children:[e.jsx(uo,{title:"Assigned queries",values:t.assignedQueries,emptyLabel:"No queries are assigned."}),e.jsx(uo,{title:"URLs",values:t.urls,emptyLabel:"No URLs are assigned.",valueClassName:"break-all text-secondary"}),e.jsx(xf,{evidence:t.evidence,state:t.evidenceState,onRetry:s})]})}function gf({values:t}){return e.jsxs("section",{"aria-labelledby":"advanced-measurement-share-of-voice",className:"border-y border-default py-4",children:[e.jsx("h2",{id:"advanced-measurement-share-of-voice",className:"text-sm font-medium text-heading",children:"Brand share of voice"}),e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[420px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Name"}),e.jsx("th",{children:"Share of voice"})]})}),e.jsx("tbody",{children:t.map(s=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:s.name}),e.jsx("td",{className:"text-secondary",children:e.jsx(Fn,{metric:s.coverage,compact:!0})})]},s.name))})]})})]})}function mo({ariaLabelledBy:t,value:s,options:n,onChange:a,disabled:r=!1}){function o(i){if(r)return;const d=n.findIndex(m=>m.value===s);let c=null;if(i.key==="ArrowRight"||i.key==="ArrowDown"?c=(d+1)%n.length:i.key==="ArrowLeft"||i.key==="ArrowUp"?c=(d-1+n.length)%n.length:i.key==="Home"?c=0:i.key==="End"&&(c=n.length-1),c===null)return;i.preventDefault();const u=n[c];a(u.value),i.currentTarget.querySelectorAll('[role="radio"]')[c].focus()}return e.jsx("div",{role:"radiogroup","aria-labelledby":t,"aria-disabled":r,className:"segmented flex-wrap",onKeyDown:o,children:n.map(i=>{const d=i.value===s;return e.jsx("button",{type:"button",role:"radio","aria-checked":d,tabIndex:d?0:-1,disabled:r,onClick:()=>a(i.value),className:`segmented-option disabled:cursor-not-allowed disabled:opacity-50 ${d?"segmented-option-active":""}`,children:i.label},i.value)})})}function ff({outcomes:t}){const s=[{key:"both",count:t.bothSignals,label:"mentioned and cited",tone:"text-primary"},{key:"mentioned-only",count:t.mentionedOnly,label:"mentioned only",tone:"text-primary"},{key:"cited-only",count:t.citedOnly,label:"cited only",tone:"text-primary"},{key:"neither",count:t.neither,label:"neither signal",tone:"text-negative"},...t.notMeasured>0?[{key:"not-measured",count:t.notMeasured,label:"not measured",tone:"text-faint"}]:[]];return e.jsx("div",{"aria-label":"Property outcomes",className:"flex flex-wrap gap-x-8 gap-y-3 py-3",children:s.map(n=>e.jsxs("div",{className:"whitespace-nowrap",children:[e.jsx("p",{className:`font-mono text-xl font-semibold leading-none tabular-nums ${n.tone}`,children:n.count}),e.jsxs("p",{className:"mt-1 text-[13px] text-secondary",children:[n.label,n.key==="not-measured"?e.jsx(Me,{text:"One or both signals missing. Not the same as neither."}):null]})]},n.key))})}function yf({report:t,canEdit:s,onRunMeasurement:n,onRepublishSetup:a,isRunningMeasurement:r=!1,isRepublishingSetup:o=!1,isViewLoading:i=!1,isLoadingMore:d=!1,isLoadMoreError:c=!1,viewSearch:u,onViewChange:m,onLoadMore:x,onPropertyExpand:g,onRetryEvidence:h,renderPropertyLink:p}){const y=t.currentView!=null,j=t.classReporting==="available"&&(y||t.classScopes!=null),[w,k]=l.useState(t.currentView?.queryClass??"all"),[M,C]=l.useState(t.currentView?.scope.key??ln),[f,v]=l.useState(u??""),[S,R]=l.useState(tf),[E,L]=l.useState(sf),[B,U]=l.useState(t.currentView?.sort??"label-asc"),[T,N]=l.useState(null),D=l.useRef(u??""),J=j&&!y&&w!=="all"?w==="non-brand"?t.classScopes.nonBrand:t.classScopes.branded:t.overall,G=y?{aggregate:t.currentView.aggregate,groups:[]}:J,Z=l.useCallback(V=>{if(!y||!m)return;const F=V.scope??(M===ln?"all":"group"),z=V.search??f;D.current=z,m({scope:F,...F==="group"?{groupKey:V.groupKey??M}:{},queryClass:V.queryClass??w,...z?{search:z}:{},...V.sort?{sort:V.sort}:{}})},[m,f,w,M,y]);l.useEffect(()=>{!t.currentView||i||(k(t.currentView.queryClass),C(t.currentView.scope.key??ln),t.currentView.sort&&U(t.currentView.sort))},[i,t.currentView]),l.useEffect(()=>{u!==void 0&&(D.current=u,v(V=>V.trim()===u.trim()?V:u))},[u]),l.useEffect(()=>{if(!y||!m||f===D.current)return;const V=window.setTimeout(()=>Z({search:f}),af);return()=>window.clearTimeout(V)},[m,Z,f,y]);const de=t.availableGroups??G.groups;l.useEffect(()=>{M===ln||de.some(V=>V.id===M)||C(ln)},[de,M]);const se=y?void 0:G.groups.find(V=>V.id===M),Q=se?.aggregate??G.aggregate,$=V=>j?V:cf,ie=B,O=f.trim().toLocaleLowerCase(),_=l.useMemo(()=>!y&&O?Q.properties.filter(V=>V.name.toLocaleLowerCase().includes(O)):Q.properties,[Q.properties,O,y]),X=y?_:_.slice(0,S),ge=(y?t.currentView?.scope.kind==="group":se!=null)&&w==="non-brand"&&j&&(y||se.confirmedCompetitorCount>0)&&(Q.shareOfVoice?.length??0)>0,H=j?Q.unavailablePropertyCount??0:0,ae=t.flaggedResults.reduce((V,F)=>V+(F.count??1),0),ue=t.flaggedResultsTotal??ae,Oe=[$(Q.metrics.propertiesMentioned),$(Q.metrics.mentionCoverage),$(Q.metrics.citationCoverage)].map(Rl).find(Boolean),Fe=j?t.nextActionText??Oe??(H>0?`${H} ${H===1?"property is":"properties are"} unavailable.`:ue>0?`${ue} flagged ${ue===1?"result needs":"results need"} review.`:null):Pl.plan_v1,it=!(t.latestMeasurement.status.tone==="negative")&&t.latestMeasurement.completedSlots<t.latestMeasurement.totalSlots?uf(t.latestMeasurement.completedSlots,t.latestMeasurement.totalSlots):null,ke=mf(t.latestMeasurement.date),Xe=[{value:ln,label:"All properties"},...de.map(V=>({value:V.id,label:V.label}))],_e=de.length>rf;function Ve(V){C(V),Z(V===ln?{scope:"all"}:{scope:"group",groupKey:V})}function He(V){k(V),Z({queryClass:V})}function Te(V){const F=T!==V;N(F?V:null),F&&g?.(V)}return e.jsxs("section",{"aria-label":"Advanced measurement overview","aria-busy":i,className:"space-y-5",children:[e.jsx("header",{className:"border-b border-default pb-4",children:e.jsx("div",{role:"status","aria-label":"Measurement status and next action",className:"flex flex-wrap items-center gap-x-3 gap-y-2",children:i?e.jsx("span",{className:"text-sm text-secondary",children:"Updating results…"}):e.jsxs(e.Fragment,{children:[e.jsx(le,{tone:t.latestMeasurement.status.tone,children:t.latestMeasurement.status.label}),t.latestMeasurement.includesBridgedHistory?e.jsx(le,{tone:"caution",children:"Includes historical data"}):null,it?e.jsx("span",{className:"text-sm text-secondary tabular-nums",children:it}):null,ke?e.jsx("span",{className:"text-sm text-secondary",children:ke}):null,Fe?e.jsx("span",{className:"text-sm text-secondary",children:Fe}):null,s&&j&&n?e.jsx(A,{className:"ml-auto",size:"sm",onClick:()=>{n()},disabled:r,children:r?"Starting measurement…":"Run measurement"}):s&&!j?e.jsx(A,{className:"ml-auto",size:"sm",onClick:()=>{a?.()},disabled:!a||o,children:o?"Opening setup…":"Republish setup"}):null]})})}),e.jsxs("div",{className:"flex flex-wrap items-end gap-4 border-b border-default pb-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{id:"advanced-measurement-group-label",htmlFor:_e?"advanced-measurement-group":void 0,className:"block text-sm font-medium text-heading",children:"Group"}),_e?e.jsx("select",{id:"advanced-measurement-group",value:M,onChange:V=>Ve(V.target.value),className:"h-9 rounded-md border border-default bg-surface px-3 text-sm text-primary focus:outline-none focus:ring-2 focus:ring-mono-400",children:Xe.map(V=>e.jsx("option",{value:V.value,children:V.label},V.value))}):e.jsx(mo,{ariaLabelledBy:"advanced-measurement-group-label",value:M,options:Xe,onChange:Ve})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{id:"advanced-measurement-class-label",className:"block text-sm font-medium text-heading",children:"Query type"}),e.jsx(mo,{ariaLabelledBy:"advanced-measurement-class-label",value:w,options:of,onChange:He,disabled:!j})]}),e.jsxs("div",{className:"ml-auto min-w-52 max-w-xs flex-1 space-y-1",children:[e.jsx("label",{htmlFor:"advanced-measurement-search",className:"block text-sm font-medium text-heading",children:"Search properties"}),e.jsx("input",{id:"advanced-measurement-search",type:"search",value:f,onChange:V=>v(V.target.value),placeholder:"Search properties",className:"h-9 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"})]})]}),!i&&ge?e.jsx(gf,{values:Q.shareOfVoice??[]}):null,i?e.jsx("div",{className:"h-44 animate-pulse rounded-md bg-surface-subtle","aria-label":"Updating Property results"}):e.jsxs("section",{"aria-labelledby":"advanced-measurement-properties-title",children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("h2",{id:"advanced-measurement-properties-title",className:"text-base font-semibold text-heading",children:["Properties",e.jsx(Me,{text:"Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other."})]}),e.jsxs("span",{className:"text-sm text-secondary",children:[t.currentView?.propertyTotal??_.length," ",(t.currentView?.propertyTotal??_.length)===1?"property":"properties"]})]}),t.currentView?.outcomes?e.jsx(ff,{outcomes:t.currentView.outcomes}):null,e.jsx("div",{className:"overflow-x-auto rounded-md border border-default",children:e.jsxs("table",{className:"evidence-table min-w-[720px]",children:[e.jsx("caption",{className:"sr-only",children:"Property measurement results"}),e.jsx("thead",{children:e.jsxs("tr",{children:[ef.map(V=>{const F=ie.startsWith(`${V.key}-`),z=F&&ie.endsWith("-desc")?"descending":F?"ascending":"none";return e.jsx("th",{"aria-sort":z,className:(V.numeric,void 0),children:m?e.jsxs("button",{type:"button",className:"inline-flex items-center gap-1 text-inherit hover:text-heading",onClick:()=>{const Ne=`${V.key}-${F&&ie.endsWith("-asc")?"desc":"asc"}`;U(Ne),Z({sort:Ne})},"aria-label":`Sort by ${V.label.toLowerCase()}`,children:[V.label,e.jsx(Ws,{className:`h-3 w-3 transition-transform ${F?"opacity-100":"opacity-0"} ${z==="ascending"?"rotate-180":""}`,"aria-hidden":"true"})]}):V.label},V.key)}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Details"})})]})}),e.jsxs("tbody",{children:[X.map(V=>{const F=T===V.id;return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"cursor-pointer transition-colors hover:bg-surface-subtle",onClick:z=>{hf(z.target)||Te(V.id)},children:[e.jsxs("td",{className:"font-medium text-heading",children:[p?p({id:V.id,name:V.name}):V.name,lo(V.status)||V.historical?e.jsxs("span",{className:"ml-2 inline-flex flex-wrap items-center gap-1 align-middle",children:[lo(V.status)?e.jsx(le,{tone:V.status.tone,children:V.status.label}):null,V.historical?e.jsx(le,{tone:"caution",children:"Historical"}):null]}):null,co(V)?e.jsx("div",{className:"mt-0.5 text-xs font-normal text-faint",children:co(V)}):null]}),e.jsx("td",{className:"text-secondary",children:e.jsx(Fn,{metric:V.mentionCoverage,compact:!0})}),e.jsx("td",{className:"text-secondary",children:e.jsx(Fn,{metric:V.citationCoverage,compact:!0})}),e.jsx("td",{className:"text-right",children:e.jsx(A,{size:"icon",variant:"ghost","aria-expanded":F,"aria-label":F?`Hide details for ${V.name}`:`Show details for ${V.name}`,onClick:()=>Te(V.id),children:e.jsx(Ws,{className:`h-4 w-4 transition-transform duration-200 motion-reduce:transition-none ${F?"rotate-180":""}`,"aria-hidden":"true"})})})]},V.id),F?(V.providers??[]).map(z=>e.jsxs("tr",{className:"measurement-subrow",children:[e.jsx("td",{className:"measurement-subrow-name",children:z.provider}),e.jsx("td",{className:"text-secondary",children:e.jsx(Fn,{metric:z.mentionCoverage,compact:!0})}),e.jsx("td",{className:"text-secondary",children:e.jsx(Fn,{metric:z.citationCoverage,compact:!0})}),e.jsx("td",{})]},`${V.id}:${z.provider}`)):null,F?e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"bg-surface-subtle px-4",children:e.jsx(pf,{property:V,onRetryEvidence:h})})},`${V.id}:details`):null]},V.id)}),X.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"py-8 text-center text-sm text-secondary",children:"No properties match this search."})}):null]})]})}),y&&t.currentView.nextCursor&&x?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",X.length," of ",t.currentView.propertyTotal]}),c?e.jsx("span",{role:"alert",children:"Could not load more properties."}):null,e.jsx(A,{size:"sm",variant:"outline",disabled:d,onClick:()=>x(t.currentView.nextCursor),children:d?"Loading…":c?"Retry loading more properties":"Show 50 more"})]}):y?X.length<t.currentView.propertyTotal?e.jsxs("p",{className:"mt-2 text-sm text-secondary",children:["Showing ",X.length," of ",t.currentView.propertyTotal]}):null:e.jsx(Br,{shown:X.length,total:_.length,itemLabel:"properties",onShowAll:()=>R(Number.MAX_SAFE_INTEGER)})]}),!i&&!O&&ue>0?e.jsx("section",{"aria-label":"Flagged results",className:"border-t border-default pt-4",children:e.jsxs("details",{children:[e.jsxs("summary",{className:"cursor-pointer text-sm font-medium text-heading",children:["Flagged results (",ue,")"]}),e.jsx("ul",{className:"mt-3 space-y-3",children:t.flaggedResults.slice(0,E).map(V=>e.jsxs("li",{className:"flex flex-wrap items-start gap-2 text-sm",children:[e.jsx(le,{tone:V.tone,children:"Flagged"}),e.jsx("span",{className:"font-medium text-heading",children:V.property}),e.jsx("span",{className:"text-secondary",children:V.summary})]},V.id))}),E<t.flaggedResults.length?e.jsxs("div",{className:"mt-3 flex items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing details for ",t.flaggedResults.slice(0,E).reduce((V,F)=>V+(F.count??1),0)," of ",ue," flagged results"]}),e.jsx(A,{size:"sm",variant:"outline",onClick:()=>L(V=>Math.min(t.flaggedResults.length,V+nf)),children:"Show 50 more"})]}):ae<ue?e.jsxs("div",{className:"mt-3 flex items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing details for ",ae," of ",ue," flagged results"]}),y&&t.currentView.nextCursor&&x?e.jsx(A,{size:"sm",variant:"outline",disabled:d,onClick:()=>x(t.currentView.nextCursor),children:d?"Loading…":c?"Retry loading more Properties":"Load more Properties"}):null]}):null]})}):null]})}function Il(t){return t==="continue"?"Continue setup":t==="edit"?"Edit setup":t==="republish"?"Republish setup":"Set up advanced measurement"}function bf(t){return t.activePlanSchemaVersion===null?{surface:"simple-overview",setupAction:t.hasDraft?"continue":"set-up"}:t.activePlanSchemaVersion<2?{surface:"advanced-overview-v1",setupAction:"republish"}:{surface:"advanced-overview",setupAction:t.hasDraft?"continue":"edit"}}function vf({mode:t,canEdit:s,simpleOverview:n,report:a,reportState:r="ready",onOpenSetup:o,onRunMeasurement:i,onRetryReport:d,onViewChange:c,onLoadMore:u,onPropertyExpand:m,onRetryEvidence:x,renderPropertyLink:g,isRunningMeasurement:h,isOpeningSetup:p,isViewLoading:y,isLoadingMore:j,isLoadMoreError:w,viewSearch:k}){return t.surface==="simple-overview"?n:e.jsxs("div",{className:"space-y-4",children:[t.setupAction==="republish"&&!a&&s&&o?e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(A,{type:"button",size:"sm",disabled:p,onClick:o,children:p?"Opening setup…":Il(t.setupAction)}),e.jsx("p",{className:"supporting-copy m-0",children:"Unpublished changes are waiting to go live."})]}):null,r==="loading"?e.jsx("div",{className:"h-32 animate-pulse rounded-md bg-surface-subtle","aria-label":"Loading advanced measurement report"}):r==="error"&&!a?e.jsxs("div",{role:"alert",className:"border-y border-negative-800/40 bg-negative-950/20 py-4 text-sm text-negative",children:[e.jsx("p",{children:"Could not load the advanced measurement report."}),d?e.jsx(A,{className:"mt-3",type:"button",size:"sm",variant:"outline",onClick:d,children:"Retry report"}):null]}):a?e.jsx(yf,{report:a,canEdit:s,onRunMeasurement:i,onRepublishSetup:o,onViewChange:c,onLoadMore:u,onPropertyExpand:m,onRetryEvidence:x,renderPropertyLink:g,isRunningMeasurement:h,isRepublishingSetup:p,isViewLoading:y,isLoadingMore:j,isLoadMoreError:w,viewSearch:k}):e.jsx("div",{role:"status",className:"border-y border-caution-800/40 bg-caution-950/20 py-4 text-sm text-secondary",children:"No advanced measurement report is available yet."})]})}const jn={numerator:null,denominator:null,reason:"plan_v1"};function jf(t){return t.kind==="exact"?t.url:t.kind==="prefix"?`https://${t.host}${t.pathPrefix}`:`https://${t.host}`}function ho(t){return t.numerator===null?{numerator:null,denominator:null,reason:t.reason}:{numerator:t.numerator,denominator:t.denominator}}function Nf(t){return t==="assigned"?"this-property":t==="sibling"?"another-property":t==="ownedUnmapped"?"owned-unassigned":t==="external"?"external":t==="ambiguous"?"multiple-properties":"invalid-url"}function wf(t){return t==="assigned"?"positive":t==="external"?"neutral":t==="invalid"?"negative":"caution"}function Sf(t){if(!t)return"Date unavailable";const s=new Date(t);return Number.isFinite(s.getTime())?s.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:"UTC"}):"Date unavailable"}function Cf(t){return t.usageEdgeType!=="target"||!t.usageEdgeId.startsWith("target:")?null:t.usageEdgeId.slice(7).split(":",1)[0]??null}function kf(t){const s=new Map;for(const n of t){const a=Cf(n);if(!a)continue;const r=s.get(a)??[];r.push(n),s.set(a,r)}return s}function Af(t,s){if(t.plan.schemaVersion!==1)throw new Error("Version-one report adapter received a different setup version.");const n=t.plan,a=new Map(n.targets.map(p=>[p.stableKey,p])),r=new Map(n.querySnapshots.map(p=>[p.queryId,p.queryText])),o=new Map;for(const p of n.targetQuerySelections){const y=o.get(p.targetKey)??[];y.push(...p.queryIds.map(j=>r.get(j)).filter(j=>!!j)),o.set(p.targetKey,[...new Set(y)])}const i=kf(s.evidence),d=n.executionNodes.reduce((p,y)=>p+y.expectedSnapshots,0),c=s.run?.status==="completed"&&d>0,u=c?d:0,m=c?d:0,x=s.targets.map(p=>{const y=a.get(p.id),j=i.get(p.id)??[],w=j.map(C=>({id:`${C.observationId}:${C.usageEdgeId}:${C.sourceUrl}`,kind:Nf(C.classification),query:C.queryText,url:C.sourceUrl,tone:wf(C.classification),historical:C.historical||C.bridged})),k=j.some(C=>C.historical||C.bridged),M=s.run?p.completeness.complete?y?.mentionNotApplicable?{label:"No aliases",tone:"caution"}:{label:"Complete",tone:"positive"}:{label:`Incomplete · ${p.completeness.executed} of ${p.completeness.expected}`,tone:"caution"}:{label:"Not measured",tone:"neutral"};return{id:p.id,name:p.label,mentionCoverage:ho(p.mentionCoverage),citationCoverage:ho(p.citationCoverage),status:M,assignedQueries:o.get(p.id)??[],urls:y?.urls.map(jf)??[],evidence:w,historical:k}}),g=new Map(x.map(p=>[p.id,p])),h=new Map(n.groups.map(p=>[p.stableKey,p]));return{classReporting:"plan-v1",latestMeasurement:{status:s.run?.status==="completed"?{label:"Complete",tone:"positive"}:s.run?.status==="partial"?{label:"Partial result",tone:"caution"}:{label:"Not measured",tone:"neutral"},completedSlots:u,totalSlots:m,date:Sf(s.run?.finishedAt??s.run?.createdAt??null),includesBridgedHistory:s.diagnostics.bridgedObservationIds.length>0||s.diagnostics.historicalObservationIds.length>0},overall:{aggregate:{metrics:{propertiesMentioned:jn,mentionCoverage:jn,citationCoverage:jn},properties:x},groups:s.groups.map(p=>({id:p.id,label:p.label,confirmedCompetitorCount:h.get(p.id)?.competitors?.length??0,aggregate:{metrics:{propertiesMentioned:jn,mentionCoverage:jn,citationCoverage:jn},properties:p.targetIds.map(y=>g.get(y)).filter(y=>!!y)}}))},flaggedResults:[]}}const Pf={critical:"negative",high:"negative",medium:"caution",low:"neutral"};function bt(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 Rf(t){if(!t)return"—";const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}function If(t){const s=[t.city,t.region,t.country].filter(Boolean).join(", ");return s?`${t.label} (${s})`:t.label}function $f({projectName:t}){const[s,n]=l.useState(!1),[a,r]=l.useState(null),[o,i]=l.useState(Ud),d=we({...Bd({client:W,path:{name:t},query:{period:o}}),placeholderData:Ir});async function c(){n(!0),r(null);try{await zd(t,"client",o)}catch(m){const x=m instanceof hn||m instanceof Error?m.message:"Download failed";r(x)}finally{n(!1)}}if(d.isLoading)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading report…"});if(d.error){const m=d.error instanceof Error?d.error.message:"Failed to load report";return e.jsx("div",{className:"py-8 text-center",children:e.jsx("p",{className:"text-sm text-negative-400",children:m})})}const u=d.data;return u?e.jsxs("div",{children:[e.jsxs("div",{className:"page-header",children:[e.jsxs("div",{className:"page-header-left",children:[e.jsx("p",{className:"eyebrow",children:"AI Visibility Report"}),e.jsx("h1",{className:"page-title",children:u.meta.project.displayName}),e.jsxs("p",{className:"page-subtitle",children:[u.meta.project.canonicalDomain," · ",u.meta.project.country," / ",u.meta.project.language.toUpperCase(),u.meta.location?` · Location: ${If(u.meta.location)}`:" · No location set"," · ","Last ",u.meta.periodDays," days"," · ","Generated ",Rf(u.meta.generatedAt)]}),a&&e.jsx("p",{className:"mt-2 text-xs text-negative-400",children:a})]}),e.jsxs("div",{className:"page-header-right flex flex-col items-end gap-2",children:[e.jsx(Mf,{period:o,onChange:i}),e.jsxs(A,{variant:"secondary",size:"sm",onClick:Ee(c),disabled:s,children:[e.jsx(Oo,{className:"size-4"}),s?"Preparing…":"Download report HTML"]})]})]}),e.jsx(Gf,{report:u}),e.jsx(Tf,{report:u}),e.jsx(zf,{report:u,audience:"client"}),e.jsx(Ef,{report:u}),e.jsx(Uf,{report:u,audience:"client",projectName:t}),e.jsx(Bf,{report:u})]}):null}function Tf({report:t}){const s=[t.mentionLandscape.nonBrand?.shareOfVoice,t.mentionLandscape.branded?.shareOfVoice?.queryClass==="branded"?t.mentionLandscape.branded.shareOfVoice:void 0];return e.jsx("div",{className:"space-y-2 text-sm text-secondary","aria-label":"Share of voice",children:s.map(n=>n?e.jsxs("div",{children:[e.jsx("p",{children:Qd(n.percent,n.queryClass,n)}),n.reason?e.jsx("p",{children:wo(n.reason)}):null]},n.queryClass):null)})}function Mf({period:t,onChange:s}){return e.jsx("div",{className:"segmented",role:"group","aria-label":"Report time period",children:Vd.map(n=>{const a=n===t;return e.jsxs("button",{type:"button",onClick:()=>s(n),"aria-pressed":a,className:`segmented-option ${a?"segmented-option-active":""}`,children:[n,"d"]},n)})})}const xo="AI Visibility — Server-Side",po="AI engine attention",Lf=t=>`What AI engines actually do in your server logs over the last ${t} days — the other half of citations.`,qf="Live telemetry from your server logs.";function Ef({report:t}){const s=t.serverActivity;if(!s)return null;if(!s.hasData)return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(Qn,{eyebrow:po,title:xo,subtitle:qf}),e.jsx("p",{className:"text-sm text-muted",children:"Your server-side traffic source is connected. Numbers will appear after the next sync."})]});const n={current:s.verifiedCrawlerHits.current+s.unverifiedCrawlerHits.current,prior:s.verifiedCrawlerHits.prior+s.unverifiedCrawlerHits.prior,deltaPct:Rm(s.verifiedCrawlerHits.current+s.unverifiedCrawlerHits.current,s.verifiedCrawlerHits.prior+s.unverifiedCrawlerHits.prior)},a=t.meta.periodDays,r=`vs prior ${a} days`,o=Oa(n,"requests",r),i=`${bt(s.verifiedCrawlerHits.current)} verified · ${bt(s.unverifiedCrawlerHits.current)} unverified${o?` · ${o}`:""}`,d=Oa(s.aiUserFetchHits,"requests",r),c=Oa(s.referralArrivals,"sessions",r),u=s.referralRedirects>0?`${bt(s.referralRedirects)} blocked by redirects`:"",m=[c,s.referralArrivalsClassSummary,u].filter(Boolean).join(" · "),x=s.byOperator.filter(g=>g.verifiedHits>0||g.unverifiedHits>0||g.userFetchHits>0||g.referralArrivals>0).slice(0,5);return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(Qn,{eyebrow:po,title:xo,subtitle:Lf(a)}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(ur,{label:"AI bot requests observed",value:bt(n.current),subtitle:i}),e.jsx(ur,{label:"AI user-fetch requests",value:bt(s.aiUserFetchHits.current),subtitle:d||"ChatGPT-User, Perplexity-User, MistralAI-User"}),e.jsx(ur,{label:"AI referral sessions",value:bt(s.referralArrivals.current),subtitle:m})]}),x.length>0&&e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow mb-2",children:"By AI tool"}),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:"AI tool"}),e.jsxs("th",{children:["Bot requests (",a,"d)"]}),e.jsxs("th",{children:["User fetches (",a,"d)"]}),e.jsx("th",{children:"Referral sessions"})]})}),e.jsx("tbody",{children:x.map(g=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:g.operator}),e.jsx("td",{children:bt(g.verifiedHits+g.unverifiedHits)}),e.jsx("td",{children:bt(g.userFetchHits)}),e.jsx("td",{children:bt(g.referralArrivals)})]},g.operator))})]})}),e.jsx("p",{className:"mt-2 text-[11px] text-muted",children:"Bot requests are bulk crawl (GPTBot, PerplexityBot, …). User fetches are on-demand reads triggered by real users inside an AI surface (ChatGPT-User, Perplexity-User, …). Verified means the request came from an IP the operator publishes as its own; unverified means the user-agent matched but the IP is not in a published range. User-fetch totals count both, since many genuine user fetches come from outside any published range."})]})]})}function Df(t,s){return t.audience==="both"||t.audience===s}const Of={gemini:"Gemini",openai:"ChatGPT",claude:"Claude",perplexity:"Perplexity",local:"Local model","cdp:chatgpt":"ChatGPT (browser)"};function Aa(t){return Of[t]??t.charAt(0).toUpperCase()+t.slice(1)}function Ff(t){if(!t)return null;const s=t.window??1,n=s>=2?`vs prior ${s} checks (avg ${t.prior}%)`:`since last check (was ${t.prior}%)`;return t.direction==="up"?{text:`Up ${t.deltaAbs.toFixed(1)} points ${n}`,tone:"positive",arrow:"↑"}:t.direction==="down"?{text:`Down ${Math.abs(t.deltaAbs).toFixed(1)} points ${n}`,tone:"negative",arrow:"↓"}:{text:`Holding steady ${s>=2?`vs prior ${s} checks (avg ${t.prior}%)`:`since last check (was ${t.prior}%)`}`,tone:"neutral",arrow:"→"}}function Gf({report:t}){const s=t.executiveSummary,n=t.citationScorecard,a=s.totalQueryCount,r=a>0?`${s.mentionRate}%`:"—",o=a>0?`When customers asked AI ${a} ${a===1?"query":"queries"} about your industry, AI mentioned you in ${s.mentionedQueryCount} of ${a===1?"them":"those answers"}.`:"No AI check has been run yet. Run a check to see how AI tools answer customer queries about your business.",i=Ff(t.whatsChanged.mentionRate),d=n.providers.length>0?n.providers.map(Aa).join(", "):`${bt(s.queryCount)} ${s.queryCount===1?"query":"queries"} tested`;return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"rounded-2xl border border-default bg-bg-elevated/40 p-6 sm:p-8",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-muted",children:"Overview"}),e.jsx("p",{className:"mt-3 text-6xl font-bold tracking-tight text-primary sm:text-7xl",children:r}),e.jsx("p",{className:"mt-3 max-w-2xl text-base text-neutral sm:text-lg",children:o}),i&&e.jsxs("p",{className:`mt-3 text-sm font-medium ${i.tone==="positive"?"text-positive-400":i.tone==="negative"?"text-negative-400":"text-secondary"}`,children:[e.jsx("span",{className:"mr-1",children:i.arrow}),i.text]})]}),e.jsxs("div",{className:"mt-5 grid gap-4 sm:grid-cols-3",children:[e.jsx(cr,{label:"AI mentions your name",value:`${s.mentionRate}%`,subtitle:a>0?`Says your name in ${s.mentionedQueryCount} of ${a} ${a===1?"answer":"answers"}`:"No data yet"}),e.jsx(cr,{label:"AI links to your website",value:`${s.citationRate}%`,subtitle:a>0?`Cites your site as a source in ${s.citedQueryCount} of ${a} ${a===1?"answer":"answers"}`:"No data yet"}),e.jsx(cr,{label:"AI tools tested",value:bt(s.providerCount),subtitle:d})]}),e.jsxs("div",{className:"mt-4 rounded-xl border border-default bg-bg/40 px-4 py-3 text-xs text-secondary",children:[e.jsx("span",{className:"font-semibold text-strong",children:"Mentions and links are different."})," ","A ",e.jsx("span",{className:"font-medium text-strong",children:"mention"})," is when AI says your name out loud in its answer. A ",e.jsx("span",{className:"font-medium text-strong",children:"link"})," is when AI lists your website as a source it used. AI can do either, both, or neither — that's why we track both."]}),n.queries.length>0&&e.jsxs("div",{className:"mt-5 rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Customer queries we tested"}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["These are the ",n.queries.length," ",n.queries.length===1?"query we asked":"queries we asked"," every AI tool. The numbers above measure how often you came up."]}),e.jsx("ol",{className:"mt-4 grid gap-2 sm:grid-cols-2",children:n.queries.map((c,u)=>e.jsxs("li",{className:"flex items-start gap-3 rounded-lg border border-default bg-bg/40 px-3 py-2 text-sm text-strong",children:[e.jsx("span",{className:"shrink-0 text-xs font-semibold tabular-nums text-muted",children:String(u+1).padStart(2,"0")}),e.jsxs("span",{children:['"',c,'"']})]},u))})]}),n.providerRates.length>0&&e.jsxs("div",{className:"mt-5 rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"How often each AI tool mentions you"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"Higher is better. Each bar shows the share of customer queries where the AI named you in the answer."}),e.jsx("div",{className:"mt-4 space-y-3",children:n.providerRates.map(c=>e.jsxs("div",{className:"grid grid-cols-[120px_1fr_120px] items-center gap-3",children:[e.jsx("span",{className:"text-sm text-neutral",children:Aa(c.provider)}),e.jsx("div",{className:"h-3 overflow-hidden rounded-full bg-mono-800/80",children:e.jsx("div",{className:"h-full rounded-full bg-positive-500/70",style:{width:`${Math.max(c.mentionRate,1.5)}%`}})}),e.jsxs("span",{className:"text-right text-sm font-semibold text-heading",children:[c.mentionRate,"% ",e.jsxs("span",{className:"font-normal text-muted",children:["(",c.mentionedCount,"/",c.totalCount,")"]})]})]},c.provider))})]}),t.clientSummary.confidenceNotes.length>0&&e.jsx("div",{className:"mt-4 grid gap-2",children:t.clientSummary.confidenceNotes.map((c,u)=>e.jsx("div",{className:"rounded-lg border border-default bg-surface px-3 py-2 text-xs text-secondary",children:c},u))})]})}function cr({label:t,value:s,subtitle:n}){return e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-muted",children:t}),e.jsx("p",{className:"mt-3 text-4xl font-bold tracking-tight text-primary sm:text-5xl",children:s}),e.jsx("p",{className:"mt-2 text-xs text-muted",children:n})]})}function Kf(t){switch(t){case"immediate":return"Do now";case"short-term":return"This month";case"medium-term":return"Next quarter"}}function _f(t){switch(t){case"high":return"Strong evidence";case"medium":return"Some evidence";case"low":return"Worth trying"}}function Uf({report:t,audience:s,projectName:n}){const a=s==="client"?t.clientSummary.actionItems:t.agencyDiagnostics.priorities.length>0?t.agencyDiagnostics.priorities:t.actionPlan.filter(x=>Df(x,s)),r=Lm(t,a),o=s==="client",i=Hd(),[d,c]=l.useState(new Set),u=d.size>0?r.filter(x=>!x.targetRef||!d.has(x.targetRef)):r,m=x=>{if(!x.targetRef)return;const g=x.targetRef;c(h=>new Set(h).add(g)),i.mutate({projectName:n,body:{targetRef:g}},{onSuccess:()=>{Se({tone:"positive",title:`Dismissed "${x.title}"`,detail:"Will not appear in future reports until un-dismissed."})},onError:h=>{Se({tone:"negative",title:`Couldn't dismiss "${x.title}"`,detail:String(h)}),c(p=>{const y=new Set(p);return y.delete(g),y})}})};return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(Qn,{eyebrow:o?"Action plan":"Agency actions",title:o?"What to do next":"Agency Action Plan",subtitle:o?"Approve these in order. They are sorted by what will move the needle fastest.":"The highest-leverage work, sorted by urgency and evidence strength."}),u.length===0?e.jsx(Qr,{message:"No recommendations yet — run an AI check to populate this."}):e.jsx("div",{className:"grid gap-3 lg:grid-cols-2",children:u.map((x,g)=>{const h=x.evidence.length>0?x.evidence:x.why,p=x.why.length>0||x.evidence.length>0;return e.jsxs("article",{className:"rounded-xl border border-default bg-surface p-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex size-8 shrink-0 items-center justify-center rounded-full bg-mono-800/80 text-sm font-semibold text-heading",title:"Priority — 1 will move the needle fastest",children:g+1}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"mb-2 flex flex-wrap gap-2",children:[e.jsx(le,{tone:Yd(x),children:o?Kf(x.horizon):Wd(x.horizon)}),!o&&e.jsx(le,{tone:"neutral",children:Jd(x.category)}),e.jsx(le,{tone:"neutral",children:o?_f(x.confidence):`${Xd(x.confidence)} confidence`})]}),e.jsx("p",{className:"text-sm font-medium text-heading",children:x.title})]})]}),e.jsx("p",{className:"mt-3 text-sm text-secondary",children:x.action}),e.jsx(Qf,{items:h,limit:3,className:"mt-3"}),p&&e.jsxs("details",{className:"mt-3 text-xs text-secondary",children:[e.jsx("summary",{className:"cursor-pointer text-muted hover:text-neutral",children:o?"See the data behind this":"Evidence details"}),x.why.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"eyebrow-soft mb-1",children:o?"Why this matters":"Why"}),e.jsx("ul",{className:"list-disc space-y-1 pl-4",children:x.why.map((y,j)=>e.jsx("li",{children:y},j))})]}),x.evidence.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"eyebrow-soft mb-1",children:o?"What we saw":"Evidence"}),e.jsx("ul",{className:"list-disc space-y-1 pl-4",children:x.evidence.map((y,j)=>e.jsx("li",{children:y},j))})]})]}),e.jsxs("p",{className:"mt-3 border-t border-default pt-3 text-xs text-neutral",children:[e.jsx("span",{className:"font-medium",children:o?"What success looks like:":"Win condition:"})," ",x.successMetric]}),x.targetRef&&!te()&&e.jsx("div",{className:"mt-3 flex justify-end",children:e.jsx("button",{type:"button",onClick:()=>m(x),className:"rounded-md border border-default bg-bg-elevated/50 px-2.5 py-1 text-[11px] font-medium text-neutral hover:border-mono-600 hover:bg-mono-800/70 hover:text-heading",title:"Stop showing this recommendation. The page-detection logic relies on GSC/GA syncs that lag by days — if you've already addressed it, dismissing keeps the report current.",children:"Mark addressed"})})]},`${x.priority}-${x.title}`)})})]})}function go({label:t,value:s,displayValue:n,max:a,barClass:r}){const o=a>0?Math.max(s/a*100,1.5):0;return e.jsxs("div",{className:"grid grid-cols-[1fr_auto] items-center gap-3 text-sm",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-neutral",title:t,children:t}),e.jsx("div",{className:"mt-1 h-2 overflow-hidden rounded-full bg-mono-800/80",children:e.jsx("div",{className:`h-full rounded-full ${r}`,style:{width:`${o}%`}})})]}),e.jsx("span",{className:"whitespace-nowrap text-sm font-semibold text-heading",children:n})]})}function Bf({report:t}){const s=t.aiSourceOrigin.topDomains.slice(0,5),n=t.gsc,a=t.indexingHealth,r=qm(t).slice(0,5),o=s.length>0?Math.max(...s.map(c=>c.count)):0,i=n?Math.max(...n.topQueries.slice(0,5).map(c=>c.impressions),1):0,d=s.length>0||n!==null||a!==null||r.length>0;return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(Qn,{eyebrow:"What we based this on",title:"The signals behind this plan",subtitle:"The data behind the recommendations above. Switch to Agency for the full breakdowns."}),d?e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[s.length>0&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Where AI gets its answers"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"The websites AI tools cited most often when answering customer queries about your industry."}),e.jsx("div",{className:"mt-4 space-y-3",children:s.map(c=>e.jsx(go,{label:c.domain+(c.isCompetitor?" (competitor)":""),value:c.count,displayValue:`${bt(c.count)}×`,max:o,barClass:"bg-mono-400/70"},c.domain))})]}),a&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Pages Google can find on your site"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"Google indexing your site increases the chances of it appearing in AI search (especially Gemini)."}),e.jsxs("p",{className:`mt-4 text-5xl font-bold tracking-tight ${a.indexedPct>=90?"text-positive-400":a.indexedPct>=70?"text-caution-400":"text-negative-400"}`,children:[a.indexedPct,"%"]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[bt(a.indexed)," of ",bt(a.total)," pages indexed"]}),e.jsx("div",{className:"mt-3 h-3 overflow-hidden rounded-full bg-mono-800/80",children:e.jsx("div",{className:`h-full rounded-full ${a.indexedPct>=90?"bg-positive-500/70":a.indexedPct>=70?"bg-caution-500/70":"bg-negative-500/70"}`,style:{width:`${Math.max(a.indexedPct,1.5)}%`}})}),e.jsxs("p",{className:"mt-3 text-xs text-secondary",children:[e.jsx("span",{className:"font-medium text-strong",children:bt(a.notIndexed)})," ",a.notIndexed===1?"page is":"pages are"," not indexed yet."]})]}),n&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"What people search Google for"}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["You appeared in ",e.jsx("span",{className:"font-semibold text-strong",children:bt(n.totalImpressions)})," Google searches and got ",e.jsx("span",{className:"font-semibold text-strong",children:bt(n.totalClicks)})," ",n.totalClicks===1?"click":"clicks"," this period."]}),n.topQueries.length>0&&e.jsx("div",{className:"mt-4 space-y-3",children:n.topQueries.slice(0,5).map(c=>e.jsx(go,{label:c.query,value:c.impressions,displayValue:`${bt(c.impressions)} ${c.impressions===1?"search":"searches"}`,max:i,barClass:"bg-info-500/70"},c.query))})]}),r.length>0&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Topics where you could improve"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"Customer queries where better content on your site would help AI cite you."}),e.jsx("ul",{className:"mt-4 space-y-2 text-sm text-neutral",children:r.map((c,u)=>e.jsxs("li",{className:"rounded-lg border border-default bg-bg/40 px-3 py-2",children:[e.jsx("p",{className:"font-medium text-heading",children:c.query}),e.jsxs("p",{className:"mt-0.5 flex items-center gap-2 text-xs text-secondary",children:[Zd(c.action),c.winnabilityClass==="ceded"&&e.jsx(le,{tone:"caution",children:"Ceded surface"})]})]},u))})]})]}):e.jsx(Qr,{message:"No supporting evidence yet — this fills in after the first AI check."})]})}function Vr(t){return t==="up"?"positive":t==="down"?"negative":"neutral"}function zr(t){return t==="up"?"↑":t==="down"?"↓":"→"}function dr({label:t,delta:s,unit:n}){if(!s)return e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("p",{className:"text-2xl font-semibold tracking-tight text-muted",children:"—"}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:"No prior data"})]});const a=n==="%"?"%":"",r=Vr(s.direction),o=r==="positive"?"text-positive-400":r==="negative"?"text-negative-400":"text-heading",i=n==="%"?`${s.deltaAbs>0?"+":""}${s.deltaAbs.toFixed(1)}% vs ${s.prior}%`:Im(s);return e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsxs("p",{className:`text-2xl font-semibold tracking-tight ${o}`,children:[s.current,a," ",e.jsx("span",{className:"text-sm font-medium",children:zr(s.direction)})]}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:i})]})}function fo({label:t,delta:s,countLabel:n,comparisonWindowDays:a}){if(!s)return e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("p",{className:"text-2xl font-semibold tracking-tight text-muted",children:"—"}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:"Not enough trend data"})]});const r=Vr(s.direction),o=r==="positive"?"text-positive-400":r==="negative"?"text-negative-400":"text-heading",i=$m(s,n,`vs prior ${a} days`);return e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsxs("p",{className:`text-2xl font-semibold tracking-tight ${o}`,children:[bt(s.current)," ",e.jsx("span",{className:"text-sm font-medium",children:zr(s.direction)})]}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:i})]})}function Vf({movements:t,audience:s}){const n=t.filter(r=>r.direction!=="flat");if(n.length===0)return null;const a=s==="client";return e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow mb-2",children:a?"How each AI tool changed":"AI engine movements"}),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:a?"AI tool":"Engine"}),e.jsx("th",{children:a?"Was":"Prior"}),e.jsx("th",{children:a?"Now":"Current"}),e.jsx("th",{children:"Change"})]})}),e.jsx("tbody",{children:n.map(r=>{const o=r.deltaAbs>0?"+":"",i=Vr(r.direction),d=i==="positive"?"text-positive-400":i==="negative"?"text-negative-400":"text-neutral";return e.jsxs("tr",{children:[e.jsx("td",{children:a?Aa(r.provider):r.provider}),e.jsxs("td",{children:[r.prior,"%"]}),e.jsxs("td",{children:[r.current,"%"]}),e.jsxs("td",{className:d,children:[o,r.deltaAbs.toFixed(1),"% ",zr(r.direction)]})]},r.provider)})})]})})]})}function yo({insights:t,heading:s,emptyMessage:n,audience:a}){if(t.length===0)return e.jsxs("div",{className:"mt-4 rounded-xl border border-default bg-surface p-4",children:[e.jsx("p",{className:"eyebrow mb-1",children:s}),e.jsx("p",{className:"text-xs text-muted",children:n})]});const r=a==="client";return e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow mb-2",children:s}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[!r&&e.jsx("th",{children:"Severity"}),e.jsx("th",{children:r?"What changed":"Title"}),e.jsx("th",{children:r?"Customer query":"Query"}),e.jsx("th",{children:r?"AI tool":"Provider"})]})}),e.jsx("tbody",{children:t.map(o=>e.jsxs("tr",{children:[!r&&e.jsxs("td",{children:[e.jsx(le,{tone:Pf[o.severity],children:eu(o.severity)}),o.instanceCount>1&&e.jsxs("span",{className:"ml-2 text-[11px] text-muted",children:["×",o.instanceCount]})]}),e.jsxs("td",{className:"evidence-query-cell",children:[o.title,r&&o.instanceCount>1&&e.jsxs("span",{className:"ml-2 text-[11px] text-muted",children:["×",o.instanceCount]})]}),e.jsx("td",{className:"text-xs text-secondary",children:o.query}),e.jsx("td",{className:"text-xs text-secondary",children:r?Aa(o.provider):o.provider})]},o.id))})]})})]})}function zf({report:t,audience:s}){const n=t.whatsChanged,a=s==="client",r=!n.enoughHistory&&!n.gscClicksDelta&&!n.aiReferralsDelta&&n.wins.length===0&&n.regressions.length===0,o=e.jsx(Qn,{eyebrow:a?"Since last check":"Section 2",title:a?"What's different since last check":"What's Changed",subtitle:a?void 0:n.headline});return r?e.jsxs("section",{className:"page-section-divider",children:[o,e.jsx(Qr,{message:a?"No comparison yet — trends will appear after a few more checks.":"Trends will appear after a few more checks."})]}):e.jsxs("section",{className:"page-section-divider",children:[o,e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(dr,{label:a?"AI mentions your name":"Citation rate",delta:a?n.mentionRate:n.citationRate,unit:"%"}),e.jsx(dr,{label:a?"AI links to your website":"Mention rate",delta:a?n.citationRate:n.mentionRate,unit:"%"}),e.jsx(dr,{label:a?"Queries AI mentioned you in":"Cited queries",delta:a?n.mentionedQueryCount:n.citedQueryCount,unit:"count"}),e.jsx(fo,{label:a?"Visitors from Google":"GSC clicks",delta:n.gscClicksDelta,countLabel:a?"visits":"clicks",comparisonWindowDays:n.comparisonWindowDays}),e.jsx(fo,{label:a?"Visitors from AI tools":"AI referral sessions",delta:n.aiReferralsDelta,countLabel:a?"visits":"sessions",comparisonWindowDays:n.comparisonWindowDays})]}),e.jsx(Vf,{movements:n.providerMovements,audience:s}),e.jsx(yo,{insights:n.wins,heading:a?"What got better":"Wins",emptyMessage:a?"No new wins this period.":"No new gains in the latest check.",audience:s}),e.jsx(yo,{insights:n.regressions,heading:a?"What got worse":"Regressions",emptyMessage:a?"Nothing got worse this period.":"No new regressions in the latest check.",audience:s})]})}function ur({label:t,value:s,tone:n,subtitle:a}){const r=n==="positive"?"text-positive-400":n==="caution"?"text-caution-400":n==="negative"?"text-negative-400":"text-heading";return e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("p",{className:`text-2xl font-semibold tracking-tight ${r}`,children:s}),a&&e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:a})]})}function Qn({eyebrow:t,title:s,subtitle:n}){return e.jsxs("div",{className:"mb-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("h2",{className:"page-title",children:s}),n&&e.jsx("p",{className:"page-subtitle mt-1",children:n})]})}function Qf({items:t,limit:s=3,className:n}){if(t.length===0)return null;const a=t.slice(0,s),r=t.length-a.length;return e.jsxs("div",{className:`flex flex-wrap gap-1.5 ${n??""}`,children:[a.map((o,i)=>e.jsx("span",{className:"rounded-md border border-default bg-bg-elevated/40 px-2 py-0.5 text-[11px] text-neutral",children:o},i)),r>0&&e.jsxs("span",{className:"rounded-md border border-default bg-bg-elevated/40 px-2 py-0.5 text-[11px] text-secondary",children:["+",r," more"]})]})}function Qr({message:t}){return e.jsx("p",{className:"text-sm text-muted py-4 text-center",children:t})}function Hf({project:t,onUpdateProject:s,onRefresh:n}){const[a,r]=l.useState(!1),[o,i]=l.useState(!1),[d,c]=l.useState(null),[u,m]=l.useState(t.displayName),[x,g]=l.useState(t.canonicalDomain),[h,p]=l.useState(t.country),[y,j]=l.useState(t.language),[w,k]=l.useState(t.ownedDomains??[]),[M,C]=l.useState(""),[f,v]=l.useState(t.aliases??[]),[S,R]=l.useState(""),[E,L]=l.useState(null),[B,U]=l.useState(!1),[T,N]=l.useState(!1),[D,J]=l.useState(""),[G,Z]=l.useState(""),[de,se]=l.useState(""),[Q,$]=l.useState(""),[ie,O]=l.useState(""),[_,X]=l.useState(null),[ge,H]=l.useState(null);l.useEffect(()=>{a||(m(t.displayName),g(t.canonicalDomain),p(t.country),j(t.language),k(t.ownedDomains??[]),v(t.aliases??[]))},[t,a]);function ae(){r(!1),c(null),m(t.displayName),g(t.canonicalDomain),p(t.country),j(t.language),k(t.ownedDomains??[]),v(t.aliases??[]),C(""),R("")}function ue(){const F=M.trim();F&&(w.includes(F)||k([...w,F]),C(""))}function Oe(F){k(w.filter(z=>z!==F))}function Fe(){const F=S.trim();if(!F)return;const z=F.toLowerCase();f.some(Ne=>Ne.toLowerCase()===z)||v([...f,F]),R("")}function Pe(F){v(f.filter(z=>z!==F))}async function tt(){if(!(!u.trim()||!x.trim()||!h.trim()||!y.trim())){i(!0),c(null);try{await s(t.name,{displayName:u.trim(),canonicalDomain:x.trim(),ownedDomains:w,aliases:f,country:h.trim(),language:y.trim()}),r(!1),Se({title:"Project settings saved",detail:`${u.trim()} was updated.`,tone:"positive",dedupeKey:`project:update:${t.name}`,dedupeMode:"replace"})}catch(F){c(F instanceof Error?F.message:"Failed to save")}finally{i(!1)}}}async function it(){const F=D.trim(),z=G.trim(),Ne=de.trim(),Ie=Q.trim();if(!(!F||!z||!Ne||!Ie)){U(!0),L(null);try{const ee={label:F,city:z,region:Ne,country:Ie};ie.trim()&&(ee.timezone=ie.trim()),await nu(t.name,ee),n(),J(""),Z(""),se(""),$(""),O(""),N(!1),Se({title:"Location added",detail:`${F} is now available for ${t.name}.`,tone:"positive",dedupeKey:`project:location:add:${t.name}:${F}`,dedupeMode:"drop"})}catch(ee){L(ee instanceof Error?ee.message:"Failed to add location")}finally{U(!1)}}}async function ke(F){U(!0),L(null);try{await su(t.name,F),n(),Se({title:"Location removed",detail:`${F} was removed from ${t.name}.`,tone:"positive",dedupeKey:`project:location:remove:${t.name}:${F}`,dedupeMode:"drop"})}catch(z){L(z instanceof Error?z.message:"Failed to remove location")}finally{U(!1)}}async function Xe(F){U(!0),L(null);try{await tu(t.name,F),n(),Se({title:"Default location updated",detail:`${F} is now the default for ${t.name}.`,tone:"positive",dedupeKey:`project:location:default:${t.name}`,dedupeMode:"replace"})}catch(z){L(z instanceof Error?z.message:"Failed to set default location")}finally{U(!1)}}async function _e(F){X(F),H(null);try{await au(t.name,F),Se({title:`${F.toUpperCase()} download started`,detail:`Historical citation and mention results for ${t.displayName}.`,tone:"positive",dedupeKey:`project:results-export:${t.name}`,dedupeMode:"replace"})}catch(z){H(z instanceof Error?z.message:"Could not download tracking results.")}finally{X(null)}}const Ve=u!==t.displayName||x!==t.canonicalDomain||h!==t.country||y!==t.language||JSON.stringify(w)!==JSON.stringify(t.ownedDomains??[])||JSON.stringify(f)!==JSON.stringify(t.aliases??[]),He="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",Te="mb-1 block text-sm font-medium text-secondary",V=D.trim()&&G.trim()&&de.trim()&&Q.trim();return e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Configuration"}),e.jsx("h2",{children:"Project settings"})]}),!te()&&!a&&e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>r(!0),children:"Edit settings"})]}),d&&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:[d,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>c(null),children:"×"})]}),!te()&&a?e.jsxs("div",{className:"rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:Te,children:"Display name"}),e.jsx("input",{className:He,type:"text",value:u,onChange:F=>m(F.target.value),placeholder:"My Project"})]}),e.jsxs("div",{children:[e.jsx("label",{className:Te,children:"Canonical domain"}),e.jsx("input",{className:He,type:"text",value:x,onChange:F=>g(F.target.value),placeholder:"example.com"})]}),e.jsxs("div",{children:[e.jsx("label",{className:Te,children:"Country"}),e.jsx("input",{className:He,type:"text",value:h,onChange:F=>p(F.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{children:[e.jsx("label",{className:Te,children:"Language"}),e.jsx("input",{className:He,type:"text",value:y,onChange:F=>j(F.target.value),placeholder:"en"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:Te,children:"Owned domains"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:w.map(F=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:[F,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>Oe(F),"aria-label":`Remove ${F}`,children:"×"})]},F))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${He} flex-1`,type:"text",placeholder:"docs.example.com",value:M,onChange:F=>C(F.target.value),onKeyDown:F=>F.key==="Enter"&&(F.preventDefault(),ue())}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:!M.trim(),onClick:ue,children:"Add"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:Te,children:"Aliases"}),e.jsx("p",{className:"mb-1.5 text-sm text-secondary",children:"Other brand names that may appear in answers."}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:f.map(F=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:[F,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>Pe(F),"aria-label":`Remove ${F}`,children:"×"})]},F))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${He} flex-1`,type:"text",placeholder:"Facebook",value:S,onChange:F=>R(F.target.value),onKeyDown:F=>F.key==="Enter"&&(F.preventDefault(),Fe())}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:!S.trim(),onClick:Fe,children:"Add"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-default",children:[e.jsx(A,{type:"button",disabled:o||!Ve||!u.trim()||!x.trim(),onClick:Ee(tt),children:o?"Saving...":"Save changes"}),e.jsx(A,{type:"button",variant:"outline",disabled:o,onClick:ae,children:"Cancel"})]})]}):e.jsx("div",{className:"rounded-lg border border-default bg-surface overflow-hidden",children:e.jsx("table",{className:"w-full text-sm",children:e.jsxs("tbody",{children:[e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium w-40",children:"Display name"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.displayName||"—"})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Canonical domain"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.canonicalDomain})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Owned domains"}),e.jsx("td",{className:"px-4 py-2.5",children:(t.ownedDomains??[]).length>0?e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.ownedDomains.map(F=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:F},F))}):e.jsx("span",{className:"text-muted",children:"—"})})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Aliases"}),e.jsx("td",{className:"px-4 py-2.5",children:(t.aliases??[]).length>0?e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.aliases.map(F=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:F},F))}):e.jsx("span",{className:"text-muted",children:"—"})})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Country"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.country})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Language"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.language})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium align-top pt-3",children:"Locations"}),e.jsxs("td",{className:"px-4 py-2.5",children:[E&&e.jsxs("div",{className:"mb-2 rounded border border-negative-800/40 bg-negative-950/20 px-2 py-1 text-xs text-negative",children:[E,e.jsx("button",{type:"button",className:"ml-1 text-negative-400 hover:text-negative-200",onClick:()=>L(null),children:"×"})]}),(t.locations??[]).length>0?e.jsxs("table",{className:"w-full text-xs mb-2",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-faint",children:[e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Label"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"City"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Region"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Country"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Timezone"}),e.jsx("th",{className:"pb-1"})]})}),e.jsx("tbody",{children:t.locations.map(F=>e.jsxs("tr",{className:"border-t border-mono-800/30",children:[e.jsx("td",{className:"py-1.5 pr-3",children:e.jsxs("span",{className:`inline-flex items-center gap-1 rounded-md border px-2 py-1 text-xs font-medium ${F.label===t.defaultLocation?"border-positive-700/60 bg-positive-950/30 text-positive":"border-mono-700/60 bg-mono-800/40 text-neutral"}`,children:[F.label,F.label===t.defaultLocation?" ★":""]})}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:F.city}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:F.region}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:F.country}),e.jsx("td",{className:"py-1.5 pr-3 text-muted",children:F.timezone??"—"}),e.jsx("td",{className:"py-1.5",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[!te()&&F.label!==t.defaultLocation&&e.jsx("button",{type:"button",disabled:B,onClick:()=>{Xe(F.label)},className:"text-sm text-secondary hover:text-positive-400 transition-colors disabled:opacity-40","aria-label":`Set ${F.label} as default location`,children:"Set default"}),!te()&&e.jsx("button",{type:"button",disabled:B,onClick:()=>{ke(F.label)},className:"text-sm text-secondary hover:text-negative-400 transition-colors disabled:opacity-40","aria-label":`Remove location ${F.label}`,children:"Remove"})]})})]},F.label))})]}):e.jsx("p",{className:"text-muted text-xs mb-2",children:"No locations configured"}),te()?null:T?e.jsxs("div",{className:"mt-2 rounded border border-base bg-bg-elevated/50 p-3 space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-secondary",children:"Add location"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-sm text-secondary",children:"Label *"}),e.jsx("input",{className:He,type:"text",value:D,onChange:F=>J(F.target.value),placeholder:"nyc"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-sm text-secondary",children:"City *"}),e.jsx("input",{className:He,type:"text",value:G,onChange:F=>Z(F.target.value),placeholder:"New York"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-sm text-secondary",children:"Region *"}),e.jsx("input",{className:He,type:"text",value:de,onChange:F=>se(F.target.value),placeholder:"NY"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"mb-1 block text-sm text-secondary",children:"Country *"}),e.jsx("input",{className:He,type:"text",value:Q,onChange:F=>$(F.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"mb-1 block text-sm text-secondary",children:"Timezone (optional)"}),e.jsx("input",{className:He,type:"text",value:ie,onChange:F=>O(F.target.value),placeholder:"America/New_York"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(A,{type:"button",size:"sm",disabled:B||!V,onClick:Ee(it),children:B?"Adding...":"Add location"}),e.jsx(A,{type:"button",size:"sm",variant:"outline",disabled:B,onClick:()=>{N(!1),L(null)},children:"Cancel"})]})]}):e.jsx(A,{type:"button",size:"sm",variant:"outline",onClick:()=>N(!0),children:"+ Add location"})]})]})]})})})]}),e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Data export"}),e.jsx("h2",{children:"Tracking results"}),e.jsx("p",{className:"mt-1 max-w-2xl text-sm text-muted",children:"Download historical citation and mention observations for this project. Each row is one query and provider result, including stored answer text and source URLs."})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("p",{className:"max-w-xl text-xs leading-5 text-muted",children:"Includes completed, partial, and failed answer-visibility runs with stored results. Test runs are excluded. Provider credentials and raw provider payloads are never included."}),e.jsxs("div",{className:"flex shrink-0 flex-wrap gap-2",children:[e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:_!==null,onClick:Ee(()=>_e("csv")),children:_==="csv"?"Preparing CSV...":"Download CSV"}),e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:_!==null,onClick:Ee(()=>_e("json")),children:_==="json"?"Preparing JSON...":"Download JSON"})]})]}),ge&&e.jsx("p",{className:"mt-3 rounded border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:ge})]})]})]})}function qn(t){return{...t??{}}}function Wf(t,s){const n=Object.entries(t).sort(([r],[o])=>r.localeCompare(o)),a=Object.entries(s).sort(([r],[o])=>r.localeCompare(o));return n.length===a.length&&n.every(([r,o],i)=>{const d=a[i];return d?.[0]===r&&d[1]===o})}function Yf({project:t,onSave:s}){const{isAdmin:n}=Hn(),a=we({queryKey:["settings"],queryFn:Po,staleTime:6e4,enabled:n&&!te()}),[r,o]=l.useState(t.providers.length===0),[i,d]=l.useState(t.providers),[c,u]=l.useState(()=>qn(t.providerModels)),[m,x]=l.useState({providers:t.providers,providerModels:qn(t.providerModels)}),[g,h]=l.useState(!1),[p,y]=l.useState(!1),[j,w]=l.useState(null),[k,M]=l.useState(null),C=l.useRef(null),f=a.data?.providerCatalog??[],v=l.useMemo(()=>new Set((a.data?.providers??[]).filter(N=>N.configured).map(N=>N.name)),[a.data]),S=l.useMemo(()=>{const N=new Map(f.map(D=>[D.name,D]));for(const D of Object.keys(c))N.has(D)||N.set(D,{name:D,displayName:D,mode:"api",modelConfigurable:!0,defaultModel:"",knownModels:[],modelValidationPattern:{source:".",flags:""},modelValidationHint:"Validate this custom model ID with the server."});return[...N.values()].sort((D,J)=>D.displayName.localeCompare(J.displayName))},[f,c]),R=!Wf(c,m.providerModels);l.useEffect(()=>{if(g||p)return;const N={providers:t.providers,providerModels:qn(t.providerModels)};x(N),o(N.providers.length===0),d(N.providers),u(N.providerModels)},[t]);function E(){y(!0),o(!1),i.length===0&&d([...v])}function L(N,D,J=!1){y(!0),u(G=>{const Z={...G};return D==="__inherit__"?delete Z[N]:D==="__custom__"?Z[N]=J?"":Z[N]??"":Z[N]=D,Z}),D==="__custom__"&&queueMicrotask(()=>C.current?.focus())}function B(N,D){y(!0),d(J=>D?[...new Set([...J,N])]:J.filter(G=>G!==N))}function U(){y(!1),o(m.providers.length===0),d(m.providers),u(qn(m.providerModels)),w(null),M(null)}async function T(){if(!(a.isError||a.isLoading||!r&&i.length===0)){h(!0),w(null),M(null);try{const N=Object.fromEntries(Object.entries(c).filter(([J,G])=>G.trim()!==""&&(r||i.includes(J)))),D={providers:r?[]:i,providerModels:N};await s(D),x({providers:[...D.providers],providerModels:qn(D.providerModels)}),y(!1),M("Engine settings saved. They apply on the next sweep.")}catch(N){w(_n(N))}finally{h(!1)}}}return te()||!n?null:a.isLoading?e.jsx("section",{className:"project-engine-settings","aria-busy":"true",children:e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading engine settings…"})}):a.isError?e.jsxs("section",{className:"project-engine-settings",children:[e.jsx("h2",{children:"Answer engines"}),e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"Could not load the engine catalogue. Saving is disabled until it is available."}),e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>{a.refetch()},children:"Retry"})]}):f.length===0?e.jsxs("section",{className:"project-engine-settings",children:[e.jsx("h2",{children:"Answer engines"}),e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"The engine catalogue is incomplete. Saving is disabled so existing project overrides cannot be cleared."}),e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>{a.refetch()},children:"Retry"})]}):v.size===0?e.jsxs("section",{className:"project-engine-settings",children:[e.jsx("h2",{children:"Answer engines"}),e.jsxs("p",{className:"text-sm text-secondary",children:["Configure an answer engine in ",e.jsx(js,{to:"/settings",className:"text-link",children:"global Settings"})," before choosing project engines."]})]}):e.jsxs("section",{className:"project-engine-settings","aria-busy":g,children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Execution"}),e.jsx("h2",{children:"Answer engines"})]}),e.jsx("p",{className:"supporting-copy",children:"Changes apply on the next sweep."})]}),e.jsxs("fieldset",{disabled:g,className:"project-engine-fieldset",children:[e.jsx("legend",{children:"Provider mode"}),e.jsxs("label",{children:[e.jsx("input",{type:"radio",checked:r,onChange:()=>{y(!0),o(!0)}})," All configured engines"]}),e.jsx("p",{className:"project-engine-help",children:"Includes engines configured later in global Settings."}),e.jsxs("label",{children:[e.jsx("input",{type:"radio",checked:!r,onChange:E})," Choose engines"]}),!r&&e.jsx("div",{className:"project-engine-list",children:S.map(N=>{const D=i.includes(N.name),J=v.has(N.name),G=D&&!J,Z=c[N.name],de=N.knownModels.some(Q=>Q.id===Z),se=Z===void 0?"__inherit__":de?Z:"__custom__";return e.jsxs("div",{className:"project-engine-row",children:[e.jsxs("label",{className:"project-engine-provider",children:[e.jsx("input",{type:"checkbox",checked:D,disabled:!J&&!D,onChange:Q=>B(N.name,Q.target.checked)})," ",e.jsx("span",{children:N.displayName}),G&&e.jsx("span",{className:"text-xs text-caution-400",children:"Not configured, skipped"})]}),D&&(N.modelConfigurable?e.jsxs("div",{className:"project-engine-model",children:[e.jsx("label",{htmlFor:`project-model-${N.name}`,children:"Model"}),e.jsxs("select",{id:`project-model-${N.name}`,value:se,onChange:Q=>L(N.name,Q.target.value,de),children:[e.jsxs("option",{value:"__inherit__",children:["Use instance setting: ",N.defaultModel||"default"]}),N.knownModels.map(Q=>e.jsx("option",{value:Q.id,children:Q.displayName},Q.id)),e.jsx("option",{value:"__custom__",children:"Custom model ID…"})]}),se==="__custom__"&&e.jsx("input",{ref:C,"aria-label":`${N.displayName} custom model ID`,value:Z??"",onChange:Q=>{y(!0),u($=>({...$,[N.name]:Q.target.value}))},"aria-describedby":`project-model-hint-${N.name}`}),e.jsxs("p",{id:`project-model-hint-${N.name}`,className:"project-engine-help",children:[Z?"Project override":"Inherited from instance settings",". ",N.modelValidationHint]})]}):e.jsx("p",{className:"project-engine-help",children:"Model is detected/fixed for this browser engine."}))]},N.name)})})]}),!r&&i.length===0&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"Choose at least one configured engine."}),j&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:j}),k&&e.jsx("p",{role:"status",className:"text-sm text-positive-400",children:k}),R&&e.jsx("p",{className:"project-engine-warning",children:"Applies on the next sweep. Existing history remains visible. If the recorded model changes, month-to-month comparison may exclude that engine."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(A,{type:"button",onClick:()=>{T()},disabled:g||!r&&i.length===0,children:g?"Saving engines…":"Save engines"}),e.jsx(A,{type:"button",variant:"outline",onClick:U,disabled:g,children:"Cancel"})]})]})}const Jf=[{value:"daily",label:"Every day"},{value:"weekly@mon",label:"Every Monday"},{value:"weekly@wed",label:"Every Wednesday"},{value:"weekly@fri",label:"Every Friday"},{value:"twice-daily",label:"Twice a day (6am & 6pm)"},{value:"custom",label:"Custom cron expression"}],bo=["UTC","America/New_York","America/Chicago","America/Denver","America/Los_Angeles","America/Toronto","America/Vancouver","Europe/London","Europe/Paris","Europe/Berlin","Asia/Tokyo","Asia/Shanghai","Asia/Singapore","Australia/Sydney"];function Xf({projectName:t}){const s=Vt(),n=!te()&&!s,a=Ns(),[r,o]=l.useState(!1),[i,d]=l.useState("daily"),[c,u]=l.useState(6),[m,x]=l.useState(""),[g,h]=l.useState("UTC"),[p,y]=l.useState(!1),[j,w]=l.useState(""),[k,M]=l.useState(!1),[C,f]=l.useState(!1),[v,S]=l.useState(null),[R,E]=l.useState(void 0),L=ru({client:W,path:{name:t}}),B=we({...Lo({client:W,path:{name:t}}),staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always",retry:!1}),U=B.isPending||B.isFetching,T=B.isError,N=B.data?.find(_=>_.kind==="answer-visibility")??null,D=r&&R!==void 0&&(N?.updatedAt??null)!==R,J=_=>{a.setQueryData(L,X=>{const ge=(X??[]).filter(H=>H.kind!=="answer-visibility");return _?[...ge,_]:ge})},G=_=>{if(_){const X=cu(_.preset??null,_.cronExpr);d(X.freq),u(X.hour),x(X.customCron);const ge=bo.includes(_.timezone);h(ge?_.timezone:"Other"),y(!ge),w(ge?"":_.timezone)}else d("daily"),u(6),x(""),h("UTC"),y(!1),w("");E(_?.updatedAt??null)},Z=()=>{n&&(G(N),S(null),o(!0))},de=()=>{G(N),S(null)},se=async()=>{(await B.refetch()).isError?S("The schedule changed, but Canonry could not load the latest version. Retry the schedule check."):S(r?null:"This schedule changed elsewhere. The latest version is now shown; review it and try again.")},Q=async(_,X)=>{if(_ instanceof hn&&_.code==="SCHEDULE_VERSION_CONFLICT"){await se();return}S(_ instanceof Error?_.message:X)},$=async()=>{if(n&&!(D||R===void 0)){M(!0),S(null);try{const _=await B.refetch();if(_.isError||_.data===void 0){S("Canonry could not verify the latest schedule. Try again before saving.");return}if(((_.data.find(ue=>ue.kind==="answer-visibility")??null)?.updatedAt??null)!==R)return;const H={timezone:p?j.trim()||"UTC":g,expectedUpdatedAt:R};i==="custom"?H.cron=m.trim():H.preset=lu(i,c);const ae=await ri(t,H);o(!1),E(void 0),J(ae),Se({title:"Schedule saved",detail:Ea(ae.preset??null,ae.cronExpr,ae.timezone),tone:"positive",dedupeKey:`schedule:${t}`,dedupeMode:"replace"})}catch(_){await Q(_,"Failed to save schedule")}finally{M(!1)}}},ie=async()=>{if(!n||!N)return;const _=N.updatedAt;M(!0),S(null);try{const X=await B.refetch();if(X.isError||X.data===void 0){S("Canonry could not verify the latest schedule. Try again before updating it.");return}const ge=X.data.find(ue=>ue.kind==="answer-visibility")??null;if(!ge||ge.updatedAt!==_){S("This schedule changed elsewhere. Review the latest version and try again.");return}const H={timezone:ge.timezone,enabled:!ge.enabled,expectedUpdatedAt:_};ge.preset?H.preset=ge.preset:H.cron=ge.cronExpr;const ae=await ri(t,H);J(ae),Se({title:ae.enabled?"Schedule resumed":"Schedule paused",detail:Ea(ae.preset??null,ae.cronExpr,ae.timezone),tone:"positive",dedupeKey:`schedule:toggle:${t}`,dedupeMode:"replace"})}catch(X){await Q(X,"Failed to update schedule")}finally{M(!1)}},O=async()=>{if(!n||!N)return;const _=N.updatedAt;f(!0),S(null);try{await ou(t,_),J(null),o(!1),E(void 0),Se({title:"Schedule removed",detail:`${t} will no longer run automatically.`,tone:"positive",dedupeKey:`schedule:remove:${t}`,dedupeMode:"drop"})}catch(X){await Q(X,"Failed to remove schedule")}finally{f(!1)}};return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Automation"}),e.jsx("h2",{children:"Scheduled runs"})]}),n&&!U&&!T&&!r&&e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:Z,children:N?"Edit schedule":"+ Set schedule"})]}),U&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),v&&!r&&e.jsx("p",{className:"mt-2 text-sm text-negative",role:"alert",children:v}),!U&&T&&e.jsxs(xe,{className:"surface-card compact-card",children:[e.jsx("p",{className:"supporting-copy",children:"Canonry could not verify this schedule."}),e.jsx(A,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:()=>{B.refetch()},children:"Retry"})]}),!U&&!T&&!r&&N===null&&e.jsx(xe,{className:"surface-card compact-card",children:e.jsx("p",{className:"supporting-copy",children:s?Hs:"No schedule configured. Set one to automatically trigger visibility sweeps."})}),!U&&!T&&!r&&N!==null&&e.jsx(xe,{className:"surface-card compact-card",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[s&&e.jsx("p",{className:"text-sm text-secondary",children:Hs}),e.jsx("p",{className:"text-sm font-medium text-strong",children:Ea(N.preset??null,N.cronExpr,N.timezone)}),e.jsxs("p",{className:"text-xs text-muted",children:["Cron: ",e.jsx("span",{className:"font-mono",children:N.cronExpr})]}),N.enabled&&N.nextRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Next run: ",new Date(N.nextRunAt).toLocaleString()]}),N.lastRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Last run: ",new Date(N.lastRunAt).toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(le,{tone:N.enabled?"positive":"neutral",children:N.enabled?"Active":"Paused"}),n&&e.jsx(A,{type:"button",variant:"outline",size:"sm",disabled:k,onClick:Ee(ie),children:N.enabled?"Pause":"Resume"}),n&&e.jsx(A,{type:"button",variant:"ghost",size:"sm",disabled:C,onClick:Ee(O),children:C?"Removing...":"Remove"})]})]})}),n&&r&&e.jsxs("div",{className:"rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-3",children:[D&&e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 rounded-md border border-caution bg-caution-soft px-3 py-2 text-sm text-caution",role:"alert",children:[e.jsx("p",{children:"This schedule changed elsewhere. Load the latest version before saving."}),e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:de,children:"Load latest schedule"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Frequency"}),e.jsx("select",{className:"w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none",value:i,onChange:_=>d(_.target.value),children:Jf.map(_=>e.jsx("option",{value:_.value,children:_.label},_.value))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Time"}),e.jsx("select",{className:"w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none disabled:opacity-40",value:c,disabled:i==="twice-daily"||i==="custom",onChange:_=>u(parseInt(_.target.value)),children:Array.from({length:24},(_,X)=>e.jsx("option",{value:X,children:iu(X)},X))})]})]}),i==="custom"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Cron expression"}),e.jsx("input",{className:"w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 font-mono focus:border-mono-500 focus:outline-none",type:"text",placeholder:"0 9 * * 1-5",value:m,onChange:_=>x(_.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Timezone"}),e.jsxs("select",{className:"w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none",value:p?"Other":g,onChange:_=>{_.target.value==="Other"?(y(!0),h("Other")):(y(!1),h(_.target.value))},children:[bo.map(_=>e.jsx("option",{value:_,children:_},_)),e.jsxs("option",{value:"Other",children:["Other (enter manually)","…"]})]}),p&&e.jsx("input",{className:"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",type:"text",placeholder:"e.g. America/New_York",value:j,onChange:_=>w(_.target.value)})]}),v&&e.jsx("p",{className:"text-negative-400 text-sm",role:"alert",children:v}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>{o(!1),E(void 0),S(null)},children:"Cancel"}),e.jsx(A,{type:"button",size:"sm",disabled:k||B.isFetching||T||D||i==="custom"&&!m.trim(),onClick:Ee($),children:k?"Saving...":"Save schedule"})]})]})]})}const Zf=[{value:"citation.lost",label:"Citation lost"},{value:"citation.gained",label:"Citation gained"},{value:"run.completed",label:"Run completed"},{value:"run.failed",label:"Run failed"}];function ey({projectName:t}){const[s,n]=l.useState("loading"),[a,r]=l.useState(!1),[o,i]=l.useState(""),[d,c]=l.useState(["citation.lost","citation.gained"]),[u,m]=l.useState(!1),[x,g]=l.useState(null),[h,p]=l.useState({}),[y,j]=l.useState(new Set);l.useEffect(()=>{du(t).then(n).catch(()=>n([]))},[t]);const w=f=>{c(v=>v.includes(f)?v.filter(S=>S!==f):[...v,f])},k=async()=>{if(!(!o.trim()||d.length===0)){m(!0),g(null);try{const f=await uu(t,{channel:"webhook",url:o.trim(),events:d});n(v=>v==="loading"?[f]:[...v,f]),i(""),c(["citation.lost","citation.gained"]),r(!1),Se({title:"Webhook added",detail:`Notifications will be sent to ${f.url}.`,tone:"positive",dedupeKey:`notification:add:${t}`,dedupeMode:"drop"})}catch(f){g(f instanceof Error?f.message:"Failed to add webhook")}finally{m(!1)}}},M=async f=>{if(!y.has(f)){j(v=>new Set(v).add(f));try{await hu(t,f),n(v=>v==="loading"?v:v.filter(S=>S.id!==f)),Se({title:"Webhook removed",detail:`${t} no longer sends notifications to this endpoint.`,tone:"positive",dedupeKey:`notification:remove:${t}:${f}`,dedupeMode:"drop"})}catch(v){g(v instanceof Error?v.message:"Failed to remove webhook")}finally{j(v=>{const S=new Set(v);return S.delete(f),S})}}},C=async f=>{p(v=>({...v,[f]:{state:"testing"}}));try{const v=await mu(t,f);p(S=>({...S,[f]:{state:v.ok?"ok":"fail",status:v.status}})),v.ok&&Se({title:"Test notification sent",detail:`Webhook returned status ${v.status}.`,tone:"positive",dedupeKey:`notification:test:${t}:${f}`,dedupeMode:"replace"})}catch{p(v=>({...v,[f]:{state:"fail"}}))}};return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Automation"}),e.jsx("h2",{children:"Notifications"})]}),!te()&&s!=="loading"&&e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!a),g(null)},children:a?"Cancel":"+ Add webhook"})]}),!te()&&a&&e.jsxs("div",{className:"mb-3 rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Webhook URL"}),e.jsx("input",{className:"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",type:"url",placeholder:"https://hooks.example.com/canonry",value:o,onChange:f=>i(f.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Trigger on"}),e.jsx("div",{className:"flex flex-wrap gap-3",children:Zf.map(f=>e.jsxs("label",{className:"flex items-center gap-1.5 cursor-pointer select-none",children:[e.jsx("input",{type:"checkbox",className:"rounded border-mono-600 bg-mono-800",checked:d.includes(f.value),onChange:()=>w(f.value)}),e.jsx("span",{className:"text-sm text-neutral",children:f.label})]},f.value))})]}),x&&e.jsx("p",{className:"text-negative-400 text-sm",children:x}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:()=>{r(!1),g(null)},children:"Cancel"}),e.jsx(A,{type:"button",size:"sm",disabled:u||!o.trim()||d.length===0,onClick:Ee(k),children:u?"Adding...":"Add webhook"})]})]}),s==="loading"&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),s!=="loading"&&s.length===0&&!a&&e.jsx(xe,{className:"surface-card compact-card",children:e.jsx("p",{className:"supporting-copy",children:"No webhooks configured. Add one to get alerted when citations change or runs complete."})}),s!=="loading"&&s.length>0&&e.jsxs("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:"Endpoint"}),e.jsx("th",{children:"Events"}),e.jsx("th",{children:"Status"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:s.map(f=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:e.jsx("span",{className:"font-mono text-xs text-neutral break-all",title:f.urlHost,children:f.urlDisplay??f.url})}),e.jsx("td",{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:f.events.map(v=>e.jsx("span",{className:"inline-flex items-center rounded-full border border-strong bg-surface-inset px-2 py-0.5 text-[10px] font-medium text-secondary uppercase tracking-wide",children:v.replace("."," ")},v))})}),e.jsx("td",{children:e.jsx(le,{tone:f.enabled?"positive":"neutral",children:f.enabled?"Active":"Paused"})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[h[f.id]&&(()=>{const v=h[f.id],S=v.state==="testing"?"Sending…":v.state==="ok"?`Delivered${v.status?` (${v.status})`:""}`:`Failed${v.status?` (${v.status})`:""}`;return e.jsx(le,{tone:v.state==="ok"?"positive":v.state==="fail"?"negative":"neutral",children:S})})(),!te()&&e.jsx(A,{variant:"ghost",size:"sm",type:"button",disabled:h[f.id]?.state==="testing",onClick:()=>{C(f.id)},children:"Test"}),!te()&&e.jsx(A,{variant:"ghost",size:"sm",type:"button",disabled:y.has(f.id),onClick:()=>{M(f.id)},children:y.has(f.id)?"Removing…":"Remove"})]})})]},f.id))})]}),x&&e.jsx("p",{className:"text-negative-400 text-sm mt-2",children:x})]})]})}function ty({open:t,projectLabel:s,onOpenChange:n,onConfirm:a,onClosed:r,disabled:o}){return te()||Vt()?null:e.jsx(gu,{open:t,onOpenChange:n,children:e.jsxs(fu,{onCloseAutoFocus:i=>{r&&(i.preventDefault(),r())},children:[e.jsxs(yu,{children:[e.jsx(bu,{children:"Run AI sweep for the whole project?"}),e.jsxs(vu,{children:["Runs all tracked queries for ",s,". Report filters do not limit the sweep. Provider charges apply."]})]}),e.jsxs("div",{className:"mt-6 flex flex-wrap gap-3",children:[e.jsx(A,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(De,{disabled:o,onClick:a,children:"Run project-wide sweep"})]})]})})}const vo=2e3,jo=3e5;function sy(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`competitor-draft-${Date.now()}-${Math.random().toString(36).slice(2)}`}function ny(t,s){t.setQueriesData({predicate:n=>n.queryKey[0]==="project-dashboard-full"&&n.queryKey[1]===s.id},n=>!n||typeof n!="object"||!("project"in n)?n:{...n,project:s})}function ay({projectName:t,refreshNonce:s}){const n=Ns(),[a,r]=l.useState(null),[o,i]=l.useState([]),[d,c]=l.useState(null),[u,m]=l.useState([]),[x,g]=l.useState([]),[h,p]=l.useState(null),[y,j]=l.useState(""),[w,k]=l.useState(""),[M,C]=l.useState(""),[f,v]=l.useState(!0),[S,R]=l.useState(!1),[E,L]=l.useState(null),[B,U]=l.useState("performance");l.useEffect(()=>{T()},[t,s]);async function T(){v(!0),L(null);try{const $=await n.fetchQuery({...Eo({client:W,path:{name:t}}),staleTime:Dt});if(r($),$.connected){const[ie,O,_,X]=await Promise.all([n.fetchQuery({...Yu({client:W,path:{name:t}}),staleTime:Dt}).catch(()=>null),n.fetchQuery({...Ju({client:W,path:{name:t}}),staleTime:Dt}).catch(()=>[]),n.fetchQuery({...Xu({client:W,path:{name:t}}),staleTime:Dt}).catch(()=>[]),$.siteUrl?Promise.resolve([]):n.fetchQuery({...Zu({client:W,path:{name:t}}),staleTime:Dt}).then(ge=>ge.sites).catch(()=>[])]);c(ie),m(O),g(_),i(X)}else c(null),m([]),g([]),i([])}catch($){L($ instanceof Error?$.message:"Failed to load Bing data")}finally{v(!1)}}async function N(){if(w.trim()){L(null);try{const $=await em(t,w.trim());await Nt(n,"bing"),k(""),$.availableSites.length>0&&i($.availableSites),await T()}catch($){L($ instanceof Error?$.message:"Failed to connect")}}}async function D(){try{await tm(t),await Nt(n,"bing"),r(null),i([]),c(null),m([]),g([]),p(null),C(""),L(null)}catch($){L($ instanceof Error?$.message:"Failed to disconnect")}}async function J(){if(M)try{await sm(t,M),await Nt(n,"bing"),await T()}catch($){L($ instanceof Error?$.message:"Failed to set site")}}async function G(){if(y.trim())try{const $=await nm(t,y.trim());await Nt(n,"bing"),p($),m(ie=>[$,...ie])}catch($){L($ instanceof Error?$.message:"Inspection failed")}}async function Z($){R(!0),L(null);try{const ie=await oi(t,{urls:[$]}),{succeeded:O,failed:_,total:X}=ie.summary;Se({title:"Bing submission requested",detail:_===0?`${O} URL submitted to Bing.`:`${O}/${X} submitted successfully, ${_} failed.`,tone:_===0?"positive":"caution",dedupeKey:`bing:indexing:${t}:${$}`,dedupeMode:"replace"})}catch(ie){const O=ie instanceof Error?ie.message:"Submission failed";L(O),Se({title:"Bing submission failed",detail:O,tone:"negative",dedupeKey:`bing:indexing:${t}:${$}`,dedupeMode:"replace"})}finally{R(!1)}}async function de(){R(!0),L(null),Se({title:"Submitting URLs to Bing",detail:"Requesting indexing for all currently unindexed URLs.",tone:"neutral",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"});try{const $=await oi(t,{allUnindexed:!0}),{succeeded:ie,failed:O,total:_}=$.summary;Se({title:"Bing submissions requested",detail:O===0?`${ie}/${_} URL${_!==1?"s":""} submitted to Bing.`:`${ie}/${_} submitted successfully, ${O} failed.`,tone:O===0?"positive":"caution",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}catch($){const ie=$ instanceof Error?$.message:"Batch submission failed";L(ie),Se({title:"Bing submissions failed",detail:ie,tone:"negative",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}finally{R(!1)}}if(f)return e.jsx(xe,{className:"surface-card",children:e.jsx("div",{className:"text-sm text-secondary",children:"Loading Bing data..."})});if(!a?.connected)return te()?e.jsxs(xe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(le,{tone:"caution",children:"Not connected"})]}),e.jsx("p",{className:"text-sm text-neutral",children:"Bing Webmaster Tools is not connected for this project."})]}):e.jsxs(xe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(le,{tone:"caution",children:"Not connected"})]}),e.jsx("p",{className:"text-sm text-neutral",children:"Connect Bing Webmaster Tools to inspect URLs, monitor index coverage, and submit pages for indexing."}),e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:"bing-api-key",children:"API Key"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{id:"bing-api-key",type:"password",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",placeholder:"Bing Webmaster Tools API key",value:w,onChange:$=>k($.target.value),onKeyDown:$=>{$.key==="Enter"&&N()}}),e.jsx(De,{size:"sm",disabled:!w.trim(),onClick:Ee(N),children:"Connect"})]}),e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:["Get your API key from"," ",e.jsx("a",{href:"https://www.bing.com/webmasters/",target:"_blank",rel:"noopener noreferrer",className:"text-secondary hover:text-neutral underline underline-offset-2",children:"Bing Webmaster Tools"})]})]}),E&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:E})]});if(!a.siteUrl)return e.jsxs(xe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(le,{tone:"positive",children:"Connected"}),!te()&&e.jsx(De,{size:"sm",variant:"ghost",onClick:Ee(D),children:"Disconnect"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-positive-500"}),e.jsx("span",{className:"text-sm text-strong",children:"Authorized for this project domain"}),e.jsx("span",{className:"text-xs text-muted",children:a.domain})]}),e.jsx("p",{className:"mt-2 text-xs text-muted",children:"The API key is connected, but no Bing site is selected yet. Pick the verified site that should receive inspections and indexing requests."})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",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:"Registered domain"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.domain})]}),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 auth update"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.updatedAt?Bt(a.updatedAt):"—"})]})]}),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:"Select site"}),o.length>0?e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsxs("select",{className:"flex-1 rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none",value:M,onChange:$=>C($.target.value),children:[e.jsx("option",{value:"",children:"Select a site..."}),o.map($=>e.jsxs("option",{value:$.url,children:[$.url,$.verified?" (verified)":""]},$.url))]}),!te()&&e.jsx(De,{size:"sm",disabled:!M,onClick:Ee(J),children:"Set Site"})]}):e.jsx("p",{className:"mt-3 text-xs text-muted",children:"No verified Bing sites are available yet. Verify the domain in Bing Webmaster Tools, then use the page-level refresh to reload everything."})]})]}),E&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:E})]});const se=[{key:"performance",label:"Performance",eyebrow:"Performance",title:"Search performance"},{key:"coverage",label:"Coverage",eyebrow:"Coverage",title:"Index monitoring"},{key:"inspections",label:"Inspections",eyebrow:"Inspection",title:"URL inspection history"}],Q=se.find($=>$.key===B)??se[0];return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(xe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(le,{tone:"positive",children:"Connected"}),!te()&&e.jsx(De,{size:"sm",variant:"ghost",onClick:Ee(D),children:"Disconnect"})]})]}),E&&e.jsx("p",{className:"mb-3 text-xs text-negative-400",children:E}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-positive-500"}),e.jsx("span",{className:"text-sm text-strong",children:"Authorized for this project domain"}),e.jsx("span",{className:"text-xs text-muted",children:a.domain})]}),e.jsxs("p",{className:"mt-2 text-sm text-secondary",children:["This project uses ",e.jsx("code",{children:a.siteUrl}),"."]})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",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:"Selected site"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.siteUrl})]}),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 auth update"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.updatedAt?Bt(a.updatedAt):"—"})]})]})]})]}),e.jsxs(xe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:Q.eyebrow}),e.jsx("h3",{children:Q.title})]}),e.jsx("p",{className:"text-xs text-muted",children:d?.lastInspectedAt?`Last inspected ${Bt(d.lastInspectedAt)}`:"No inspection history yet"})]}),e.jsx("div",{className:"flex gap-1 border-b border-base",children:se.map($=>e.jsx("button",{className:`px-3 py-1.5 text-xs font-medium border-b-2 transition-colors ${B===$.key?"border-mono-200 text-strong":"border-transparent text-muted hover:text-neutral"}`,onClick:()=>U($.key),children:$.label},$.key))}),B==="coverage"&&d&&e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(ea,{label:"Indexed",value:d.summary.indexed,tone:"positive"}),e.jsx(ea,{label:"Not in index",value:d.summary.notIndexed+(d.summary.unknown??0),tone:"negative"}),e.jsx(ea,{label:"Status unknown",value:d.summary.unknown??0,tone:"neutral"}),e.jsx(ea,{label:"Coverage",value:`${d.summary.percentage}%`,tone:"neutral"})]}),d.notIndexed.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("h4",{className:"text-xs font-medium text-secondary",children:["Not Indexed (",d.notIndexed.length,")"]}),!te()&&e.jsx(De,{size:"sm",variant:"ghost",disabled:S,onClick:Ee(de),children:S?"Submitting…":"Submit all to Bing"})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-16",children:"HTTP"}),!te()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:d.notIndexed.map($=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:$.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:$.httpCode??"—"}),!te()&&e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-sm text-secondary hover:text-strong underline underline-offset-2",disabled:S,onClick:()=>{Z($.url)},children:"Submit"})})]},$.id))})]})})]}),(d.unknown??[]).length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("h4",{className:"text-sm font-medium text-secondary",children:["Unknown, not yet confirmed (",(d.unknown??[]).length,")"]}),!te()&&e.jsx(De,{size:"sm",variant:"ghost",disabled:S,onClick:Ee(de),children:S?"Submitting…":"Submit all to Bing"})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Last Crawled"}),!te()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:(d.unknown??[]).map($=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:$.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:$.lastCrawledDate?Bt($.lastCrawledDate):"—"}),!te()&&e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-sm text-secondary hover:text-strong underline underline-offset-2",disabled:S,onClick:()=>{Z($.url)},children:"Submit"})})]},$.id))})]})})]}),d.indexed.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"mb-2 text-xs font-medium text-secondary",children:["Indexed (",d.indexed.length,")"]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Last Crawled"})]})}),e.jsx("tbody",{children:d.indexed.map($=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:$.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:$.lastCrawledDate?Bt($.lastCrawledDate):"—"})]},$.id))})]})})]})]}),B==="coverage"&&!d&&e.jsx("p",{className:"mt-4 text-xs text-muted",children:"No coverage data yet. Inspect URLs to build coverage data."}),B==="inspections"&&e.jsxs("div",{className:"mt-4 space-y-3",children:[!te()&&e.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{type:"text",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",placeholder:"URL to inspect",value:y,onChange:$=>j($.target.value),onKeyDown:$=>{$.key==="Enter"&&G()}}),e.jsx(De,{size:"sm",disabled:!y.trim(),onClick:Ee(G),children:"Inspect"})]}),h&&e.jsxs("div",{className:"rounded border border-base bg-bg-elevated/40 p-3 text-xs space-y-1",children:[e.jsx("div",{className:"font-medium text-strong",children:h.url}),e.jsxs("div",{className:"text-secondary",children:["In Index: ",e.jsx("span",{className:h.inIndex?"text-positive-400":"text-negative-400",children:h.inIndex?"Yes":"No"})," · ","HTTP: ",h.httpCode??"—"," · ","Crawled: ",h.lastCrawledDate??"—"]})]}),u.length>0&&e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-16",children:"Index"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-14",children:"HTTP"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Inspected"})]})}),e.jsx("tbody",{children:u.map($=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:$.url}),e.jsx("td",{className:"py-1.5 px-3",children:e.jsx(le,{tone:$.inIndex?"positive":"negative",children:$.inIndex?"Yes":"No"})}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:$.httpCode??"—"}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:Bt($.inspectedAt)})]},$.id))})]})})]}),B==="performance"&&e.jsx("div",{className:"mt-4",children:x.length===0?e.jsx("p",{className:"text-xs text-muted",children:"No Bing performance data available."}):e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"Query"}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-16",children:Zn[un.Clicks]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-16",children:Zn[un.Impressions]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:Zn[un.CTR]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:Zn[un.Position]})]})}),e.jsx("tbody",{children:x.map(($,ie)=>e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:$.query}),e.jsx("td",{className:"py-1.5 px-3 text-right text-strong",children:$.clicks}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:$.impressions}),e.jsxs("td",{className:"py-1.5 px-3 text-right text-secondary",children:[(Number.isFinite($.ctr)?$.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:$.averagePosition.toFixed(1)})]},ie))})]})})})]})]})}function ry({projectName:t}){const s=Ns(),[n,a]=l.useState("google"),[r,o]=l.useState(!0),[i,d]=l.useState("idle"),[c,u]=l.useState(null),m=l.useRef(null),[x,g]=l.useState(null),[h,p]=l.useState(null),[y,j]=l.useState(0);async function w(M=!1){M||o(!0),u(null);try{const[C,f]=await Promise.all([s.fetchQuery({...$r({client:W,path:{name:t}}),staleTime:Dt}).catch(()=>[]),s.fetchQuery({...Eo({client:W,path:{name:t}}),staleTime:Dt}).catch(()=>null)]),v=C.find(S=>S.connectionType==="gsc")??null;g(v),p(f)}catch(C){u(C instanceof Error?C.message:"Failed to load search engine connections")}finally{o(!1)}}async function k(){if(i!=="idle")return;m.current?.abort();const M=new AbortController;m.current=M;const C=M.signal;d("syncing"),u(null),Se({title:"Refreshing search coverage",detail:"Queueing Google and Bing checks, then reloading the workspaces.",tone:"neutral",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"});const f=[],v=[];try{async function S(){if(!x)return;const L=await Hu(t);if(!L?.id)return;const B=Date.now()+jo;for(;Date.now()<B;){if(C.aborted||(await new Promise(T=>setTimeout(T,vo)),C.aborted))return;const U=await hr(L.id).catch(()=>null);if(!U)break;if(["completed","failed","cancelled"].includes(U.status)){U.status!=="completed"&&f.push(`Google sync ${U.status}`);return}}v.push("Google sync is still running — search data will appear shortly")}async function R(){if(!h?.connected)return;const L=await Wu(t).catch(()=>null);if(!L?.id){f.push("Bing sweep could not be started");return}const B=Date.now()+jo;for(;Date.now()<B;){if(C.aborted||(await new Promise(T=>setTimeout(T,vo)),C.aborted))return;const U=await hr(L.id).catch(()=>null);if(!U)break;if(["completed","failed","cancelled","partial"].includes(U.status)){U.status==="failed"?f.push("Bing sweep failed"):U.status==="partial"&&v.push("Bing sweep finished with some pages unverified");return}}v.push("Bing sweep is still running — coverage will update shortly")}const E=await Promise.allSettled([S(),R()]);for(const L of E)L.status==="rejected"&&f.push(L.reason instanceof Error?L.reason.message:"Sync failed");if(await Promise.all([Nt(s,"gsc"),Nt(s,"bing")]),C.aborted)return;if(d("reloading"),await w(!0),j(L=>L+1),f.length>0){const L=`Partial refresh: ${[...f,...v].join("; ")}`;u(L),Se({title:"Search coverage partially refreshed",detail:L,tone:"caution",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}else v.length>0?Se({title:"Search coverage refresh incomplete",detail:v.join("; "),tone:"caution",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"}):Se({title:"Search coverage refreshed",detail:"Google and Bing workspaces are reloaded with the latest stored coverage.",tone:"positive",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}catch(S){if(!C.aborted){const R=S instanceof Error?S.message:"Refresh failed";u(R),Se({title:"Search coverage refresh failed",detail:R,tone:"negative",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}}finally{C.aborted||d("idle")}}return l.useEffect(()=>(w(),()=>{m.current?.abort()}),[t]),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"flex flex-wrap gap-2",role:"tablist","aria-label":"Search engine workspaces",children:[["google","Google"],["bing","Bing"]].map(([M,C])=>e.jsx("button",{type:"button",role:"tab","aria-selected":n===M,className:`project-subnav-link ${n===M?"project-subnav-link-active":""}`,onClick:()=>a(M),children:C},M))}),!te()&&e.jsxs(De,{type:"button",variant:"outline",size:"sm","aria-label":"Refresh search data",disabled:r||i!=="idle",onClick:()=>{k()},children:[e.jsx(Na,{className:`h-3.5 w-3.5 ${i!=="idle"?"animate-spin":""}`,"aria-hidden":"true"}),r?"Loading…":i==="syncing"?"Refreshing search data…":i==="reloading"?"Reloading workspaces…":"Refresh search data"]})]}),c&&e.jsx("div",{className:"rounded-lg border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:c}),n==="google"&&e.jsx(Dh,{projectName:t,refreshNonce:y}),n==="bing"&&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 engine"}),e.jsx("h2",{children:"Bing Webmaster Tools"})]})}),e.jsx(ay,{projectName:t,refreshNonce:y})]})]})}function Pa({label:t,summary:s,displayValue:n,tooltip:a}){const r=s.value.trim()!==""&&Number.isFinite(Number(s.value)),o=s.progress!==void 0?Math.min(Math.max(s.progress,0),100):0;return e.jsxs("div",{className:"aeo-hero-row",children:[e.jsxs("p",{className:"aeo-hero-row-label",children:[t,(a||s.tooltip)&&e.jsx(Me,{text:a||s.tooltip||""})]}),e.jsx("p",{className:`aeo-hero-row-value ${No[s.tone]}`,children:n??e.jsxs(e.Fragment,{children:[s.value,r?e.jsx("span",{className:"text-faint",children:"%"}):null]})}),e.jsx("div",{className:"aeo-hero-row-bar","aria-hidden":"true",children:e.jsx("div",{className:`metric-card-bar-fill progress-fill-${s.tone}`,style:{width:`${o}%`}})}),e.jsx("p",{className:"aeo-hero-row-detail",children:s.delta})]})}function iy({model:t,sweepRunning:s,hasVisibilityBaseline:n}){const a=t.citationMovement,r=t.mentionMovement,o=t.movementComparison,i=t.recentRuns.find(h=>h.kind===Qs["answer-visibility"]&&(h.status===ja.completed||h.status===ja.partial)),d=h=>h.tone==="positive"?"improved":h.tone==="negative"?"declined":h.gained>0||h.lost>0?"mixed":"steady",c=d(r),u=d(a),m=(()=>{if(s)return"A fresh sweep is running now";if(!n)return"No AI Visibility baseline yet";if(!o.hasPreviousRun)return"Baseline captured. The next sweep will show change.";if(o.querySetChanged)return"Tracking scope changed since the previous sweep";if(c===u)return c==="steady"?"Answer mentions and citation coverage held steady":c==="mixed"?"Answer mention and citation movement was mixed":`Answer mentions and citation coverage ${c}`;const h=c==="mixed"?"Answer mention movement was mixed":c==="steady"?"Answer mentions held steady":`Answer mentions ${c}`,p=u==="mixed"?"citation movement was mixed":u==="steady"?"citation coverage held steady":`citation coverage ${u}`;return`${h}; ${p}`})(),x=[o.addedQueryCount>0&&`${o.addedQueryCount} ${o.addedQueryCount===1?"query":"queries"} added`,o.removedQueryCount>0&&`${o.removedQueryCount} ${o.removedQueryCount===1?"query":"queries"} removed`].filter(Boolean).join(", "),g=`${o.comparableQueryCount} comparable ${o.comparableQueryCount===1?"query":"queries"}`;return e.jsxs("section",{className:"overview-brief","aria-labelledby":"overview-brief-title",children:[e.jsxs("div",{className:"overview-brief-head",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"eyebrow eyebrow-soft",children:["Visibility",e.jsx(Me,{text:"Each sweep records two independent signals: answer mentions (your brand named in the answer text) and source citations (your domain in the engine's source list). They move separately."})]}),e.jsx("h2",{id:"overview-brief-title",className:"overview-brief-title",children:m})]}),i?e.jsxs("p",{className:"overview-brief-updated",children:["Updated ",i.startedAt]}):null]}),n?e.jsxs("div",{className:"overview-brief-grid",children:[e.jsxs("div",{className:"overview-brief-panel overview-brief-coverage",children:[e.jsx("p",{className:"overview-brief-label",children:"Coverage now"}),e.jsxs("div",{className:"aeo-hero-rows",children:[e.jsx(Pa,{label:"Mentioned",summary:t.mentionSummary}),e.jsx(Pa,{label:"Cited",summary:t.visibilitySummary})]}),t.mentionSummary.providerCoverage&&e.jsxs("p",{className:"overview-brief-note",children:["Partial sweep: ",t.mentionSummary.providerCoverage]})]}),e.jsxs("div",{className:"overview-brief-panel",children:[e.jsx("p",{className:"overview-brief-label",children:"Since last sweep"}),o.hasPreviousRun?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"overview-signal-change-list",children:[e.jsxs("div",{className:"overview-signal-change-row",children:[e.jsx("span",{className:"overview-signal-change-label",children:"Mentioned"}),r.gained===0&&r.lost===0?e.jsx("span",{className:"text-secondary",children:"No change"}):e.jsxs("span",{className:"flex gap-3 tabular-nums",children:[r.gained>0&&e.jsxs("span",{className:"text-positive-400",children:["+",r.gained]}),r.lost>0&&e.jsxs("span",{className:"text-negative-400",children:["-",r.lost]})]})]}),e.jsxs("div",{className:"overview-signal-change-row",children:[e.jsx("span",{className:"overview-signal-change-label",children:"Cited"}),a.gained===0&&a.lost===0?e.jsx("span",{className:"text-secondary",children:"No change"}):e.jsxs("span",{className:"flex gap-3 tabular-nums",children:[a.gained>0&&e.jsxs("span",{className:"text-positive-400",children:["+",a.gained]}),a.lost>0&&e.jsxs("span",{className:"text-negative-400",children:["-",a.lost]})]})]})]}),e.jsx("p",{className:`overview-brief-panel-copy ${o.querySetChanged?"text-caution-400/80":""}`,children:o.querySetChanged?`${x||"Query set changed"} · ${g}.`:`${g}.`})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"overview-brief-panel-title",children:"No comparison yet"}),e.jsx("p",{className:"overview-brief-panel-copy",children:Vt()?Hs:"Run another sweep to measure mention and citation movement."})]})]})]}):e.jsx("div",{className:"overview-brief-grid",children:e.jsxs("div",{className:"overview-brief-panel",children:[e.jsx("p",{className:"overview-brief-label",children:"Coverage signals"}),e.jsxs("dl",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-sm font-medium text-heading",children:"Mentioned"}),e.jsx("dd",{className:"mt-1 text-sm text-secondary",children:"Your brand or domain appears in the answer text."})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-sm font-medium text-heading",children:"Cited"}),e.jsx("dd",{className:"mt-1 text-sm text-secondary",children:"Your domain appears in the engine's source list."})]})]}),e.jsx("p",{className:"mt-4 border-t border-subtle pt-4 text-sm font-medium text-strong",children:s?"Your first sweep is running. Results will appear when it completes.":Vt()?Hs:"Complete your first AI Visibility sweep to measure both signals."})]})})]})}function mr({id:t,eyebrow:s,title:n,meta:a,defaultOpen:r=!1,children:o}){return e.jsxs("details",{id:t,className:"overview-disclosure page-section-divider scroll-mt-24",open:r||void 0,children:[e.jsxs("summary",{className:"overview-disclosure-summary",children:[e.jsxs("span",{children:[e.jsx("span",{className:"eyebrow eyebrow-soft",children:s}),e.jsx("span",{className:"overview-disclosure-title",children:n})]}),e.jsxs("span",{className:"overview-disclosure-meta",children:[a&&e.jsx("span",{children:a}),e.jsx(Ws,{className:"overview-disclosure-icon",size:16,"aria-hidden":"true"})]})]}),e.jsx("div",{className:"overview-disclosure-body",children:o})]})}function oy({insights:t,suggestedQueries:s,onManageQueries:n}){const{openEvidence:a}=So(),r=n?s.rows:[];if(t.length===0&&r.length===0)return null;const o=g=>e.jsxs("div",{className:"py-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:g.title}),g.detail?e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-secondary",children:g.detail}):null]}),e.jsx(le,{tone:g.tone,children:g.actionLabel})]}),g.affectedPhrases.length>0?e.jsxs("details",{className:"mt-2",children:[e.jsxs("summary",{className:"w-fit cursor-pointer text-sm font-medium text-secondary transition-colors hover:text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:["Evidence · ",g.affectedPhrases.length," affected ",g.affectedPhrases.length===1?"query":"queries"]}),e.jsx("ul",{className:"mt-2 divide-y divide-subtle border-y border-subtle",children:g.affectedPhrases.map((h,p)=>e.jsxs("li",{className:"flex flex-wrap items-center gap-2 py-2",children:[e.jsx(pr,{state:h.citationState}),e.jsx("span",{className:"min-w-0 flex-1 text-sm text-strong",children:h.query}),h.provider?e.jsx(Cn,{provider:h.provider}):null,!te()&&h.evidenceId?e.jsx(A,{type:"button",variant:"ghost",size:"sm",onClick:()=>{a(h.evidenceId)},children:"View evidence"}):null]},h.evidenceId||`${g.id}-${p}`))})]}):null]},g.id),i=g=>e.jsxs("div",{className:"flex items-center justify-between gap-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted",children:"Suggested query"}),e.jsx("p",{className:"mt-1 text-sm font-medium text-strong",children:g.query}),e.jsx("p",{className:"mt-0.5 text-sm text-secondary",children:g.reason})]}),n?e.jsx(A,{type:"button",variant:"outline",size:"sm",onClick:n,children:"Review in Queries"}):null]},g.query),d=t.slice(0,1),c=r.slice(0,1),u=t.slice(1),m=r.slice(1),x=u.length+m.length;return e.jsxs("section",{className:"page-section-divider","aria-labelledby":"overview-signals-title",children:[e.jsx("div",{className:"section-head",children:e.jsx("h2",{id:"overview-signals-title",children:"Latest signals"})}),e.jsxs("div",{className:"divide-y divide-default border-y border-default",children:[d.map(o),c.map(i)]}),x>0?e.jsxs("details",{className:"mt-2",children:[e.jsxs("summary",{className:"w-fit cursor-pointer text-sm font-medium text-secondary transition-colors hover:text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:[x," more ",x===1?"signal":"signals"]}),e.jsxs("div",{className:"mt-2 divide-y divide-default border-y border-default",children:[u.map(o),m.map(i)]})]}):null]})}function Sy(t){const{projectName:s}=Dl({from:"/projects/$projectName"}),a=qo()?.dashboard.projects.find(h=>h.project.name===s||h.project.id===s)?.project.name??null,r=we({...xu({client:W}),enabled:!a}),o=a??r.data?.find(h=>h.name===s||h.id===s)?.name??null,{commandCenter:i,isLoading:d,latestVisibilityRevision:c,competitorHistoryRevision:u,refetch:m}=pu(o),x=!a&&r.isLoading||d;return!o&&!a&&r.isSuccess&&!d?e.jsx("div",{className:"page-container",children:e.jsxs(xe,{className:"surface-card empty-card",children:[e.jsx("h1",{children:"Project not found"}),e.jsxs("p",{children:['Could not find a project named "',s,'".']}),e.jsx(A,{asChild:!0,children:e.jsx(js,{to:"/",children:"Return to overview"})})]})}):!i||x?e.jsxs("div",{className:"page-skeleton",children:[e.jsxs("div",{className:"page-skeleton-header",children:[e.jsx("div",{className:"skeleton-text h-6 w-48"}),e.jsx("div",{className:"skeleton-text-sm w-32"})]}),e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[1,2,3].map(h=>e.jsxs("div",{className:"page-skeleton-card flex flex-col items-center",children:[e.jsx("div",{className:"skeleton-circle size-20"}),e.jsx("div",{className:"skeleton-text w-16 mt-3"})]},h))}),e.jsxs("div",{className:"page-skeleton-card",children:[e.jsx("div",{className:"skeleton-text w-28"}),e.jsx("div",{className:"space-y-2 mt-2",children:[1,2,3,4].map(h=>e.jsx("div",{className:"skeleton-text-sm w-full"},h))})]})]}):e.jsx(dy,{model:i,refetch:m,latestVisibilityRevision:c,competitorHistoryRevision:u,...t})}function ly({items:t,overflowItems:s,settingsItem:n,activeTab:a}){const r=l.useRef(null),o=l.useRef(null),[i,d]=l.useState(null);l.useLayoutEffect(()=>{const m=r.current,x=o.current;if(!m||!x)return;const g=()=>{const p=m.getBoundingClientRect().width;if(!p)return;const y=Number.parseFloat(getComputedStyle(m).columnGap)||0,j=new Map([...x.querySelectorAll("[data-project-tab]")].map(v=>[v.dataset.projectTab,v.getBoundingClientRect().width])),w=v=>j.get(v)??0,k=v=>v.reduce((S,R)=>S+w(R),0)+Math.max(0,v.length-1)*y,M=[...t.map(v=>v.key),...s.length?["more"]:[],...n?[n.key]:[]];let C=t.map(v=>v.key),f=!1;if(k(M)>p){const v=t.find(E=>E.key===a),S=v?[v.key]:[];f=!!(n&&k([...S,"more",n.key])>p);const R=["more",...n&&!f?[n.key]:[]];for(const E of t)if(E.key!==v?.key){if(k([...S,E.key,...R])>p)break;S.push(E.key)}C=t.filter(E=>S.includes(E.key)).map(E=>E.key)}d(v=>v?.settingsInMore===f&&v.visibleKeys.join()===C.join()?v:{visibleKeys:C,settingsInMore:f})};if(g(),typeof ResizeObserver>"u")return window.addEventListener("resize",g),()=>window.removeEventListener("resize",g);const h=new ResizeObserver(g);return h.observe(m),h.observe(x),()=>h.disconnect()},[t,s,n,a]);const c=i?t.filter(m=>i.visibleKeys.includes(m.key)):t,u=[...t.filter(m=>!c.includes(m)),...s,...i?.settingsInMore&&n?[n]:[]];return e.jsxs("nav",{className:"project-subnav","aria-label":"Project sections",ref:r,children:[e.jsx("div",{className:"project-subnav-measure","aria-hidden":"true",children:e.jsxs("div",{className:"project-subnav-measure-row",ref:o,children:[[...t,...n?[n]:[]].map(m=>e.jsx("span",{className:"project-subnav-link","data-project-tab":m.key,children:m.label},m.key)),e.jsxs("span",{className:"project-subnav-link project-subnav-more-trigger","data-project-tab":"more",children:["More",e.jsx(Ws,{className:"h-3.5 w-3.5","aria-hidden":"true"})]})]})}),c.map(m=>e.jsx(js,{to:m.href,search:x=>({...x,onboarding:void 0}),className:`project-subnav-link ${m.key===a?"project-subnav-link-active project-subnav-current":""}`,"aria-current":m.key===a?"page":void 0,children:e.jsx("span",{className:"project-subnav-label",children:m.label})},m.key)),e.jsxs("div",{className:"project-subnav-trailing",children:[e.jsx(cy,{items:u,activeTab:a}),n&&!i?.settingsInMore&&e.jsx(js,{to:n.href,search:m=>({...m,onboarding:void 0}),className:`project-subnav-link ${a==="settings"?"project-subnav-link-active":""}`,"aria-current":a==="settings"?"page":void 0,children:n.label})]})]})}function cy({items:t,activeTab:s}){const[n,a]=l.useState(!1),r=l.useRef(null),o=l.useRef(null),i=l.useRef("first"),d=l.useId(),c=t.map(m=>m.key).join();if(l.useEffect(()=>{a(!1)},[c]),l.useEffect(()=>{if(!n)return;const m=r.current?.querySelectorAll('[role="menuitem"]');(i.current==="last"?m?.[m.length-1]:m?.[0])?.focus()},[n]),l.useEffect(()=>{if(!n)return;const m=g=>{r.current&&!r.current.contains(g.target)&&a(!1)},x=g=>{g.key==="Escape"&&(a(!1),o.current?.focus())};return document.addEventListener("pointerdown",m),document.addEventListener("keydown",x),()=>{document.removeEventListener("pointerdown",m),document.removeEventListener("keydown",x)}},[n]),t.length===0)return null;const u=t.some(m=>m.key===s);return e.jsxs("div",{className:"project-subnav-more",ref:r,children:[e.jsxs("button",{type:"button",ref:o,className:`project-subnav-link project-subnav-more-trigger ${u?"project-subnav-link-active":""}`,"aria-haspopup":"menu","aria-expanded":n,"aria-controls":n?d:void 0,onClick:()=>{i.current="first",a(m=>!m)},onKeyDown:m=>{m.key!=="ArrowDown"&&m.key!=="ArrowUp"||(m.preventDefault(),i.current=m.key==="ArrowUp"?"last":"first",a(!0))},children:["More",e.jsx(Ws,{className:"h-3.5 w-3.5","aria-hidden":"true"})]}),n?e.jsx("div",{className:"project-subnav-menu",role:"menu",id:d,"aria-label":"More project sections",onKeyDown:m=>{const x=[...m.currentTarget.querySelectorAll('[role="menuitem"]')],g=x.indexOf(document.activeElement),h=m.key==="Home"?0:m.key==="End"?x.length-1:m.key==="ArrowDown"?(g+1)%x.length:m.key==="ArrowUp"?(g-1+x.length)%x.length:null;h!==null&&(m.preventDefault(),x[h]?.focus())},onBlur:m=>{r.current?.contains(m.relatedTarget)||a(!1)},children:t.map(m=>e.jsx(js,{to:m.href,search:x=>({...x,onboarding:void 0}),role:"menuitem",tabIndex:-1,className:`project-subnav-menu-item ${m.key===s?"project-subnav-menu-item-active":""}`,"aria-current":m.key===s?"page":void 0,onClick:()=>a(!1),children:m.label},m.key))}):null]})}function dy({tab:t,model:s,refetch:n,latestVisibilityRevision:a,competitorHistoryRevision:r}){const o=Ol(),i=Ns(),{canWrite:d}=Hn(),[c,u]=l.useState(null),m=l.useRef(null),x=qo(),g=s.project.name,h=we({...ju({client:W,path:{name:g}}),enabled:!te()&&!!g&&(d||t==="portfolio"||t==="overview"||t==="settings"),staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always"}),p=x?x.dashboard.settings.providerStatuses.filter(I=>I.state==="ready").map(I=>ii(I.name)):void 0,y=h.data?.answerVisibilityProviderReady,j=p,w=s.project.providers.map(ii),k=j?.some(I=>w.length===0||w.includes(I))===!0,M=w.length===0||w.includes(Nu),C=we({...wu({client:W}),enabled:!te()&&d&&y===void 0&&M&&!k,staleTime:6e4,retry:!1}),f=M?C.isSuccess?typeof C.data.browserVersion=="string":C.isError?!1:void 0:!1,v=y??Su({projectProviders:w,configuredApiProviders:j,cdpConfigured:f}),S=l.useMemo(()=>{const I=Cu();return I?ku(I.projectTabs):void 0},[]),R=Au(t,S),E=l.useMemo(()=>s.competitors.map(I=>I.domain),[s.competitors]),[L,B]=l.useState(!1),[U,T]=l.useState(!1),N=Pu(),D=Fl({strict:!1}),J=_m(D),G=l.useCallback(I=>{o({to:".",search:he=>Um(he,I)})},[o]),Z=D.manageQueries===!0,de=l.useCallback(()=>{o({to:".",replace:!0,search:I=>({...I,siteHealthRunId:void 0})})},[o]),[se,Q]=l.useState(Z),[$,ie]=l.useState(""),[O,_]=l.useState(!1),[X,ge]=l.useState(null),[H,ae]=l.useState("30d"),[ue,Oe]=l.useState(void 0),[Fe,Pe]=l.useState(!1),[tt,it]=l.useState(null),[ke,Xe]=l.useState(!1),_e=Yo(D),[Ve,He]=l.useState(void 0),[Te,V]=l.useState(void 0),F=l.useCallback(I=>{He(I.search),I.sort&&V(I.sort),o({to:".",search:he=>({...he,...Gm(I)}),replace:!1})},[o]),[z,Ne]=l.useState(!1),Ie=s?.visibilityEvidence??[],ee=s?.project.displayName||s?.project.name||g,We=Ru(),ht=we({...Iu({client:W,path:{name:g}}),enabled:R==="portfolio"&&!!g,staleTime:0,refetchOnMount:"always"}),Ze=we({...$u({client:W,path:{name:g}}),enabled:!te()&&!!g&&(d||R==="portfolio"||R==="overview"||R==="settings"),staleTime:0,refetchOnMount:"always"}),ye=Ze.data?.active??null,Ge=Ze.data!==void 0,It=new Set(ye&&Number(ye.plan.schemaVersion)===2?ye.plan.groups?.map(I=>I.stableKey)??[]:[]),qe={..._e.scope==="group"&&!!_e.groupKey&&Ge&&!It.has(_e.groupKey)?{scope:"all",queryClass:_e.queryClass}:_e,...Ve?{search:Ve}:{}},Ye=ye===null?null:Number(ye.plan.schemaVersion),pt=ye?.revision??0,St=Ge?`${g}:${pt}`:null,Ke=l.useRef(null);l.useEffect(()=>{const I=Ke.current;St!==null&&(Ke.current=St),Fm(I,St)&&(F({scope:"all",queryClass:"all"}),Ne(!1))},[St,F]);const Le={client:W,path:{name:g},query:{scope:qe.scope,...qe.groupKey?{groupKey:qe.groupKey}:{},queryClass:qe.queryClass,...qe.search?{search:qe.search}:{},...Te?{sort:Te}:{},limit:50}},et=Gl({...Tu(Le),enabled:!1,initialPageParam:Le,getNextPageParam:(I,he)=>{if(!I.properties.nextCursor)return;const Ce=he[0]?.measurement.displayedRunId;return{path:Le.path,query:{...Le.query,cursor:I.properties.nextCursor,...Ce?{runId:Ce}:{}}}},placeholderData:Ir,staleTime:0,refetchOnMount:"always"}),Ue=et.data?.pages[0]?.measurement.displayedRunId,Be=we({...Mu({client:W,path:{name:g},query:{revision:pt,...Ue?{runId:Ue}:{}}}),enabled:R==="overview"&&!!g&&ye!==null&&Ye===1,staleTime:0,refetchOnMount:"always"}),$t=Ze.data!==void 0,vt=ht.data!==void 0,Ft=Ze.isPending&&!$t,gt=Ze.isError&&!$t,Y=ht.isPending&&!vt,Re=ht.isError&&!vt,be=Be.data!==void 0,je=bf({activePlanSchemaVersion:h.data?.activeSchemaVersion??Ye,hasDraft:h.data?.draft!==null&&h.data?.draft!==void 0}),Gt=h.data===void 0&&Ze.data===void 0&&(Ze.isLoading||h.isLoading),ze=Ye===2&&J.measurementScope==="group"?J.measurementScopeKey:void 0,ft=Ye===2&&J.measurementScope==="project",Tt=l.useMemo(()=>{if(!(ye?.plan.schemaVersion!==2||!ze))return ye.plan.groups.find(I=>I.stableKey===ze)},[ye,ze]),ls={client:W,path:{name:g},query:{window:H,queryClass:Ye===2&&J.queryClass!=="unknown"?J.queryClass:"non-brand",...ze?{groupKey:ze}:{},...ft?{scope:"all-markets"}:{}}},Mt=R==="overview"&&!!g&&!Gt&&(J.measurementScope==="project"||Ye===2&&J.measurementScope==="group")&&J.queryClass!=="unknown"&&(Ye===2||J.queryClass!=="branded"),Kt=we({...Lu(ls),enabled:Mt,staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always"});qu(g,JSON.stringify([r,s.competitors.map(I=>I.domain).sort(),s.project.canonicalDomain,s.project.ownedDomains,s.project.aliases,s.project.displayName,pt,h.data?.draft?.etag??null]),Mt);const ot=Kt.isError?Kt.data===void 0?"Could not load competitor history. Your pinned competitors remain available.":"Could not refresh competitor history. Showing the last available data.":void 0,cs=l.useMemo(()=>s.competitors.map(I=>({domain:I.domain,label:I.domain,surfaceClass:"direct-competitor",pinned:!0,mentionCount:0,shareOfVoice:null,citationCount:I.citationCount,answeredResults:I.totalQueries,firstSeenAt:null,lastSeenAt:null,sampleUrls:[]})),[s.competitors]),Ct=l.useMemo(()=>{if(ye?.plan.schemaVersion!==2)return cs;const I=ze?Tt?.competitors??[]:ye.plan.groups.flatMap(Ce=>Ce.competitors),he=new Map;for(const Ce of I){const Ut=Ce.domain.trim().toLowerCase();!Ut||he.has(Ut)||he.set(Ut,{domain:Ce.domain,label:Ce.label,surfaceClass:"direct-competitor",pinned:!0,mentionCount:0,shareOfVoice:null,citationCount:0,answeredResults:0,firstSeenAt:null,lastSeenAt:null,sampleUrls:[]})}for(const Ce of cs){const Ut=Ce.domain.trim().toLowerCase();!Ut||he.has(Ut)||he.set(Ut,Ce)}return[...he.values()]},[ye,ze,cs,Tt]),Ts=Ye===2?Ct:cs,zt=Pt({...Eu({client:W}),meta:{skipGlobalErrorToast:!0}}),Zt=h.data!==void 0?"success":h.isError?"error":"pending",Qt=l.useMemo(()=>{const I=et.data?.pages;return I?!Sm(I):!1},[et.data]),dt=l.useMemo(()=>{const I=et.data?.pages,he=I?.[0],Ce=I?.at(-1);if(!(!he||!Ce||Qt))return{...he,properties:{...he.properties,items:I.flatMap(Ut=>Ut.properties.items),nextCursor:Ce.properties.nextCursor}}},[Qt,et.data]),ws=l.useMemo(()=>{if(ye)return ye.plan.schemaVersion===1?Be.data?Af(ye,Be.data):void 0:dt?Cm({overview:dt,activePlan:ye,sort:Te,report:Be.data,reportState:dt.measurement.displayedRunId===void 0?"ready":Be.isFetching&&Be.data===void 0?"loading":Be.isError&&Be.data===void 0?"error":Be.data?"ready":"loading"}):void 0},[ye,Be.data,Be.isError,Be.isFetching,dt]),Ht=Ye===2?Qt?"error":et.isPending?"loading":et.isError&&ws===void 0?"error":"ready":Be.isPending&&!be?"loading":Be.isError&&!be?"error":"ready",ct=(s?.recentRuns??[]).some(I=>I.kind===Qs["answer-visibility"]&&(I.status===ja.running||I.status===ja.queued)),ms=s.queryCounts.total>0,jt=l.useMemo(()=>(s?.project.locations??[]).map(I=>I.label),[s?.project.locations]),es=l.useMemo(()=>new Set(Ie.map(I=>I.location??"")),[Ie]),hs=es.has(""),xs=l.useMemo(()=>[...new Set(Ie.map(I=>I.query))].sort((I,he)=>I.localeCompare(he)),[Ie]),Lt=xs.length>0||s.queryCounts.total>0,ne=Lt||ye!==null,fe=d&&!Lt&&Ze.data===void 0&&Ze.isPending,re=d&&h.isError&&!h.isFetching,oe=d&&!re&&(fe||v===void 0||h.isFetching),$e=!oe&&!re&&ne&&v===!0,Wt=d&&!oe&&!$e,ps=we({...Lo({client:W,path:{name:g}}),enabled:!te()&&!Vt()&&!!g,retry:!1}).data?.find(I=>I.kind===Qs["answer-visibility"]),P=ps?.enabled&&ps.nextRunAt?`Next AI sweep ${new Date(ps.nextRunAt).toLocaleString()}`:null,me=l.useMemo(()=>{const I=[...es].filter(Boolean);return I.length>1?I:jt},[es,jt]);l.useEffect(()=>{if(ue===void 0||ue===""||!g){it(null),Xe(!1);return}Xe(!0),Du(g,ue,20).then(I=>{it(I),Xe(!1)}).catch(()=>{it(null),Xe(!1)})},[ue,g]);const st=l.useMemo(()=>{if(!tt)return null;const I=new Map;for(const he of tt){for(const[Ce,Ut]of Object.entries(he.providerRuns??{}))I.set(`${he.query}::${Ce}`,Ut.map(gs=>({runId:gs.runId,citationState:gs.citationState,createdAt:gs.createdAt,answerMentioned:gs.answerMentioned,visibilityState:gs.visibilityState,visibilityTransition:gs.visibilityTransition,mentionState:gs.mentionState,mentionTransition:gs.mentionTransition})));(!he.providerRuns||Object.keys(he.providerRuns).length===0)&&I.set(`${he.query}::`,he.runs.map(Ce=>({runId:Ce.runId,citationState:Ce.citationState,createdAt:Ce.createdAt,answerMentioned:Ce.answerMentioned,visibilityState:Ce.visibilityState,visibilityTransition:Ce.visibilityTransition,mentionState:Ce.mentionState,mentionTransition:Ce.mentionTransition})))}return I},[tt]),Ae=l.useMemo(()=>{const I=ue!==void 0?Ie.filter(he=>ue===""?!he.location:he.location===ue):Ie;return st?I.map(he=>{const Ce=st.get(`${he.query}::${he.provider}`)??st.get(`${he.query}::`);return Ce?{...he,runHistory:Ce}:he}):I},[Ie,ue,st]);async function ut(){if(!(c!==g||!d||te()||Vt()||We.isPending||ct||!$e))try{await We.mutateAsync({projectName:g,projectLabel:ee,sourceAction:"project-run"}),u(null),n()}catch{}}function ds(){o({to:"/setup",search:{experience:"legacy",setupProject:g}})}async function _t(){T(!0);try{await Qu(g),Se({title:"Project deleted",detail:`${ee} was removed.`,tone:"positive",dedupeKey:`project:delete:${g}`,dedupeMode:"drop"}),o({to:"/"}),n()}catch(I){console.error("Failed to delete project:",I)}finally{T(!1)}}async function Yt(){const I=$.split(`
|
|
8
|
-
`).map(he=>he.trim()).filter(Boolean);if(I.length!==0){_(!0);try{await Gu(g,I),n(),ie("")}finally{_(!1)}}}async function $a(I){ge(I);try{await Fu(g,[I]),n()}catch(he){Se({title:"Could not remove query",detail:he instanceof Error?he.message:`Failed to remove "${I}"`,tone:"negative",dedupeKey:"query:remove",dedupeMode:"replace"})}finally{ge(null)}}async function kt(I){const he=I.trim();if(!he)return!1;try{return await Ku(g,[he]),n(),!0}catch(Ce){return Se({title:"Could not add competitor",detail:Ce instanceof Error?Ce.message:`Failed to add ${he}`,tone:"negative",dedupeKey:"competitor:add",dedupeMode:"replace"}),!1}}async function Ss(I){const he=s.competitors.find(Ce=>Ce.domain===I);if(!he)return Se({title:"Could not remove competitor",detail:`Could not find ${I} in the tracked competitor list`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"}),!1;try{return await _u(g,he.id),n(),!0}catch(Ce){return Se({title:"Could not remove competitor",detail:Ce instanceof Error?Ce.message:`Failed to remove ${he.domain}`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"}),!1}}async function gn(I){const he=I.trim();if(!he||!ze||Ye!==2||!d||te()||zt.isPending)return!1;try{const Ce=await zt.mutateAsync({client:W,path:{name:g},headers:{"Idempotency-Key":sy()},body:{expectedActiveRevision:pt,groupKey:ze,domain:he}});return Promise.allSettled([h.refetch()]),Se({title:Ce.draftCreated?"Competitor added to a market draft":"Market competitor updated",detail:`Publish the Advanced Measurement draft before ${he} is used in future market runs.`,tone:"positive",dedupeKey:`competitor:market-pin:${ze}:${he}`,dedupeMode:"replace"}),!0}catch(Ce){return Se({title:"Could not add market competitor",detail:Ce instanceof Error?Ce.message:`Failed to add ${he} to the market draft.`,tone:"negative",dedupeKey:"competitor:market-pin:error",dedupeMode:"replace"}),!1}}async function Pn(I,he){const Ce=await Uu(I,he);return await i.invalidateQueries({queryKey:Bu({client:W})}),i.setQueryData(Vu({client:W,path:{name:I}}),Ce),ny(i,Ce),he.providers!==void 0&&await i.invalidateQueries({queryKey:zu({client:W,path:{name:I}}),exact:!0}),Ce}const Jt=`/projects/${encodeURIComponent(s.project.name)}`,Ta=[{key:"overview",label:"AI Visibility",href:Jt},{key:"search-console",label:"Search Engines",href:`${Jt}/search-console`},{key:"activity",label:"Activity",href:`${Jt}/activity`},{key:"technical-aeo",label:"Site Health",href:`${Jt}/technical-aeo`},{key:"conversions",label:"Conversions",href:`${Jt}/conversions`},{key:"local",label:"Local Presence",href:`${Jt}/local`},{key:"queries",label:"Queries",href:`${Jt}/queries`},{key:"backlinks",label:"Backlinks",href:`${Jt}/backlinks`}],Rn=[{key:"report",label:"Report",href:`${Jt}/report`},{key:"history",label:"Change History",href:`${Jt}/history`}],In=Ta.filter(I=>Da(I.key,S)),Jn=Rn.filter(I=>Da(I.key,S)),tn=Da("settings",S)?{key:"settings",label:"Settings",href:`${Jt}/settings`}:null;return e.jsxs("div",{className:"page-container",children:[e.jsxs("div",{className:"page-header",children:[e.jsxs("div",{className:"page-header-left",children:[e.jsx("h1",{className:"page-title",children:s.project.displayName||s.project.name}),e.jsxs("p",{className:"page-subtitle",children:[s.project.canonicalDomain," · ",s.contextLabel]}),!te()&&e.jsxs("div",{className:"tag-row",children:[e.jsx("span",{className:"tag",children:s.project.country}),e.jsx("span",{className:"tag",children:s.project.language.toUpperCase()}),s.project.tags.map(I=>e.jsx("span",{className:"tag",children:I},I))]})]}),e.jsxs("div",{className:Vt()?"page-header-right min-w-0 flex-wrap sm:shrink sm:justify-end":"page-header-right",children:[e.jsx("p",{className:"text-sm text-muted",children:R==="overview"?J.from||J.to?`${J.from?.slice(0,10)??"First measurement"} to ${J.to?.slice(0,10)??"Latest measurement"}`:"Recent measurements":s.dateRangeLabel}),!te()&&(Vt()?e.jsx(Ou,{projectName:g,running:ct}):e.jsxs("div",{className:"flex items-center gap-3",children:[P?e.jsx("p",{className:"text-sm text-secondary",children:P}):null,e.jsx(De,{type:"button",variant:"outline",disabled:We.isPending||ct||oe,onClick:re?()=>{h.refetch()}:Wt?ds:I=>{m.current=I.currentTarget,u(g)},children:We.isPending?"Starting…":ct?"AI sweep running…":oe?"Checking AI readiness…":re?"Retry AI readiness":Wt?"Set up AI Visibility":"Run AI sweep"})]}))]})]}),!te()&&!Vt()&&e.jsx(ty,{open:c===g,projectLabel:ee,onOpenChange:I=>u(I?g:null),onConfirm:Ee(ut),onClosed:()=>m.current?.focus(),disabled:We.isPending||ct||!$e}),e.jsx(ly,{items:In,overflowItems:Jn,settingsItem:tn,activeTab:R}),R==="portfolio"&&!te()?e.jsx(Zg,{projectName:g,canEdit:d,queries:ht.data??[],isQueryLoading:Y,isQueryError:Re,onRetryQueries:()=>{ht.refetch()},publishedPlan:ye,onCreateQueries:async I=>(await N.mutateAsync({projectName:g,queries:[...I]}),(await ht.refetch({throwOnError:!0})).data??[]),onManageProjectQueries:()=>{o({to:"/projects/$projectName",params:{projectName:g},search:{manageQueries:!0}})},onPublished:()=>{Promise.all([h.refetch(),Ze.refetch()]).finally(()=>{o({to:"/projects/$projectName",params:{projectName:g}})})}},g):R==="overview"?Gt?e.jsxs("div",{role:"status","aria-live":"polite",children:[e.jsx("span",{className:"sr-only",children:"Loading project overview"}),e.jsx("div",{className:"h-32 animate-pulse rounded-md bg-surface-subtle","aria-hidden":"true"})]}):e.jsxs(e.Fragment,{children:[gt?e.jsxs("div",{role:"alert",className:"mb-5 flex flex-wrap items-center gap-3 border-y border-negative-800/40 bg-negative-950/20 py-4 text-sm text-negative",children:[e.jsx("span",{children:"Could not check the advanced measurement setup. Existing project-wide results remain available."}),e.jsx(A,{type:"button",size:"sm",variant:"outline",onClick:()=>{Ze.refetch()},children:"Retry setup check"})]}):null,e.jsx(Fx,{projectName:g,selection:J,showUnmeasuredFallback:!ye&&!ms&&J.measurementScope==="project"&&J.queryClass==="all"&&!J.provider&&!J.model&&!J.location&&!J.from&&!J.to&&!J.revision&&!J.measurementRunId&&!J.queryKey,onSelectionChange:G,onManageQueries:te()?void 0:()=>{o({to:"/projects/$projectName/queries",params:{projectName:g},search:I=>({...I,queryWorkspace:"tracked",trackingQueryId:void 0})})},fallback:e.jsx(vf,{mode:je,canEdit:d&&!te()&&!Ft&&!gt,simpleOverview:e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"page-section-divider",children:e.jsx(Xx,{projectName:s.project.name,competitorDomains:E,analyticsRevision:a})}),e.jsx(iy,{model:s,sweepRunning:ct,hasVisibilityBaseline:ms}),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:"Competitive"}),e.jsx("h2",{children:"Where competitors are winning"}),e.jsx("p",{className:"supporting-copy",children:"Latest measured results against pinned competitors."})]})}),ms?e.jsxs("div",{className:"aeo-hero competitive-summary",children:[e.jsx(Hm,{summary:s.mentionShareSummary,projectLabel:s.project.displayName||s.project.name,competitorDomains:E},s.project.name),e.jsx("div",{className:"competitive-gaps",children:e.jsxs("div",{className:"aeo-hero-rows",children:[e.jsx(Pa,{label:"Mention gaps",summary:s.mentionGaps,displayValue:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-primary",children:s.mentionGaps.value}),e.jsxs("span",{className:"text-faint",children:[" / ",s.queryCounts.total]})]}),tooltip:"Queries where a competitor was mentioned in the answer but your brand was not."}),e.jsx(Pa,{label:"Citation gaps",summary:s.gapQueries,displayValue:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-primary",children:s.gapQueries.value}),e.jsxs("span",{className:"text-faint",children:[" / ",s.queryCounts.total]})]}),tooltip:"Queries where a competitor was cited as a source but you were not."})]})})]}):e.jsx("p",{className:"text-sm text-secondary",children:"Competitive mention and citation gaps appear after the first AI Visibility sweep."})]}),e.jsxs(mr,{id:"evidence-section",eyebrow:"Tracked coverage",title:"Query evidence",meta:`${s.queryCounts.total} ${s.queryCounts.total===1?"query":"queries"}`,defaultOpen:!0,children:[!te()&&e.jsx("div",{className:"mb-3 flex items-center justify-end",children:e.jsx(De,{type:"button",variant:"outline",size:"sm",onClick:()=>Q(!se),children:se?"Done":"Manage queries"})}),!te()&&se&&e.jsxs("div",{className:"mb-3 rounded-lg border border-base bg-bg-elevated/40 p-3",children:[xs.length>0?e.jsx("ul",{className:"mb-3 max-h-64 divide-y divide-mono-800/60 overflow-y-auto rounded border border-default",children:xs.map(I=>e.jsxs("li",{className:"flex items-center justify-between gap-3 px-3 py-2",children:[e.jsx("span",{className:"min-w-0 truncate text-sm text-strong",title:I,children:I}),e.jsx("button",{type:"button",className:"shrink-0 rounded px-1.5 py-0.5 text-xs text-muted transition-colors hover:text-negative-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-negative-500 disabled:opacity-50","aria-label":`Remove query ${I}`,title:`Stop tracking "${I}"`,disabled:X!==null,onClick:()=>{$a(I)},children:X===I?"Removing…":"Remove"})]},I))}):e.jsx("p",{className:"mb-3 text-xs text-muted",children:"No queries tracked yet. Add some below."}),e.jsx("textarea",{className:"w-full resize-none 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",rows:3,placeholder:"Enter queries to add, one per line",value:$,onChange:I=>ie(I.target.value)}),e.jsxs("div",{className:"mt-2 flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-muted",children:[$.split(`
|
|
9
|
-
`).filter(I=>I.trim()).length," to add"]}),e.jsx(De,{type:"button",size:"sm",disabled:!$.trim()||O,onClick:Ee(Yt),children:O?"Adding...":"Add queries"})]})]}),s.project.locations.length>0&&e.jsxs("div",{className:"filter-row mb-3",role:"toolbar","aria-label":"Location filters",children:[e.jsx("button",{className:`filter-chip ${ue===void 0?"filter-chip-active":""}`,type:"button","aria-pressed":ue===void 0,onClick:()=>{Oe(void 0)},children:"All locations"}),s.project.locations.map(I=>e.jsx("button",{className:`filter-chip ${ue===I.label?"filter-chip-active":""}`,type:"button","aria-pressed":ue===I.label,onClick:()=>{Oe(I.label),Pe(!1)},children:I.label},I.label)),hs&&e.jsx("button",{className:`filter-chip ${ue===""?"filter-chip-active":""}`,type:"button","aria-pressed":ue==="",onClick:()=>{Oe(""),Pe(!1)},children:"No location"}),me.length>1&&ue===void 0&&e.jsx("button",{className:`filter-chip filter-chip-compare ${Fe?"filter-chip-active":""}`,type:"button","aria-pressed":Fe,onClick:()=>Pe(I=>!I),title:"Side-by-side location comparison",children:"Compare"})]}),e.jsx(oh,{evidence:Ae,compareLocations:Fe})]}),e.jsxs(mr,{eyebrow:"Analysis",title:"Citation and engine diagnostics",meta:"Deep dive",defaultOpen:te(),children:[e.jsx(dx,{projectName:s.project.name}),s.providerScores.length>1&&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:"Model breakdown"}),e.jsxs("h2",{children:["Citation rate by model ",e.jsx(Me,{text:"Per-model citation rate in the latest sweep. The same query set can perform differently across engines."})]})]})}),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",{scope:"col",children:"Model"}),e.jsx("th",{scope:"col",children:"Citation rate"}),e.jsx("th",{scope:"col",children:"Cited queries"})]})}),e.jsx("tbody",{children:s.providerScores.map(I=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"flex flex-col items-start gap-0.5",children:[e.jsx(Cn,{provider:I.provider}),I.model&&e.jsx("span",{className:"text-[11px] font-mono text-muted",children:I.model})]})}),e.jsx("td",{children:e.jsxs("span",{className:"font-semibold text-strong",children:[I.score,"%"]})}),e.jsxs("td",{className:"text-muted",children:[I.cited," of ",I.total]})]},`${I.provider}::${I.model??"unknown"}`))})]})})]})]}),!te()&&e.jsx(mr,{eyebrow:"Run history",title:"Recent execution history",meta:`${s.recentRuns.length} recent`,children:e.jsx("div",{className:"run-list",children:s.recentRuns.map(I=>e.jsx(xm,{run:I},I.id))})})]}),report:ws,reportState:Ht,onOpenSetup:te()?void 0:()=>{o({to:"/projects/$projectName/portfolio",params:{projectName:g}})},onRetryReport:()=>{Ye===2?Promise.all([et.refetch(),Be.refetch()]):Be.refetch()},onViewChange:I=>{F({scope:I.scope,...I.groupKey?{groupKey:I.groupKey}:{},queryClass:I.queryClass,...I.search?.trim()?{search:I.search.trim()}:{}})},onLoadMore:I=>{I===dt?.properties.nextCursor&&et.fetchNextPage()},onPropertyExpand:()=>{z&&Be.isError&&Be.refetch(),Ne(!0)},onRetryEvidence:()=>{Be.refetch()},renderPropertyLink:Ye===2&&!te()?({id:I,name:he})=>e.jsx(js,{to:"/projects/$projectName/properties/$targetKey",params:{projectName:g,targetKey:I},className:"text-link hover:underline",children:he}):void 0,isViewLoading:et.isPlaceholderData,isLoadingMore:et.isFetchingNextPage,isLoadMoreError:et.isFetchNextPageError,viewSearch:qe.search??""},`${g}:${pt}`)},`${g}:${JSON.stringify({...J,queryKey:void 0,answer:void 0})}`),J.measurementScope==="project"?e.jsxs("details",{className:"page-section-divider",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3 text-sm font-medium text-heading",children:"Project signals"}),e.jsx(oy,{insights:s.insights,suggestedQueries:s.suggestedQueries,onManageQueries:te()?void 0:()=>{o({to:"/projects/$projectName/queries",params:{projectName:g},search:I=>({...I,queryWorkspace:"tracked",trackingQueryId:void 0})})}})]}):null,Mt?e.jsxs("details",{className:"page-section-divider",children:[e.jsx("summary",{className:"min-h-11 cursor-pointer py-3 text-sm font-medium text-heading",children:"Competitor history"}),e.jsx("p",{className:"pb-3 text-sm text-secondary",children:"History for this scope uses the time window below."}),e.jsx(eh,{window:H,landscape:Kt.data,pinnedFallback:Ts,canWrite:d,isEmbed:te(),onWindowChange:ae,onPin:ze&&d&&!te()?gn:!ft&&d&&!te()?kt:void 0,onUnpin:ze||ft||!d||te()?void 0:Ss,onAddCompetitor:ze&&d&&!te()?gn:!ft&&d&&!te()?kt:void 0,error:ot,onRetry:Mt?()=>{Kt.refetch()}:void 0,isLoading:Mt&&Kt.isPending&&Kt.data===void 0,scopeLabel:ze?`${Tt?.label??ze} group`:ft?"All markets":"Project-wide"})]}):null]}):R==="settings"?e.jsxs(e.Fragment,{children:[e.jsx(Hf,{project:{...s.project,displayName:s.project.displayName??s.project.name,defaultLocation:s.project.defaultLocation??null},onUpdateProject:async(I,he)=>{await Pn(I,he)},onRefresh:()=>{n()}}),e.jsx(Yf,{project:s.project,onSave:async I=>{await Pn(s.project.name,I)}}),d&&!te()?e.jsxs("section",{className:"page-section-divider",children:[e.jsx("h2",{className:"text-lg font-semibold text-heading",children:"Advanced measurement"}),e.jsx("p",{className:"supporting-copy mt-1 mb-3",children:"Measure individual properties, locations, or site sections with separate query sets."}),Zt==="pending"?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading setup…"}):Zt==="error"?e.jsxs("div",{role:"alert",className:"flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:"Could not load advanced measurement setup."}),e.jsx(A,{type:"button",size:"sm",variant:"outline",onClick:()=>{h.refetch()},children:"Retry"})]}):e.jsx(A,{type:"button",variant:"outline",onClick:()=>{o({to:"/projects/$projectName/portfolio",params:{projectName:g}})},children:Il(je.setupAction)})]}):null,e.jsx(Xf,{projectName:s.project.name}),e.jsx(ey,{projectName:s.project.name}),d&&!te()?e.jsxs("section",{className:"page-section-divider",children:[e.jsx("h2",{className:"text-lg font-semibold text-negative-400",children:"Delete project"}),e.jsx("p",{className:"supporting-copy mt-1 mb-3",children:"Permanently deletes this project and all its queries, competitors, runs, and snapshots."}),L?e.jsxs(xe,{className:"surface-card p-6 border-negative-800/60",children:[e.jsx("h3",{className:"text-base font-semibold text-negative-400 mb-2",children:"Delete project?"}),e.jsxs("p",{className:"text-sm text-secondary mb-4",children:["This will permanently delete ",e.jsx("strong",{className:"text-strong",children:s.project.displayName||s.project.name})," and all its queries, competitors, runs, and snapshots. This cannot be undone."]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(A,{type:"button",variant:"destructive",disabled:U,onClick:Ee(_t),children:U?"Deleting...":"Yes, delete project"}),e.jsx(A,{type:"button",variant:"outline",disabled:U,onClick:()=>B(!1),children:"Cancel"})]})]}):e.jsxs(De,{type:"button",variant:"outline",onClick:()=>B(!0),children:[e.jsx(Go,{className:"h-4 w-4 text-secondary"}),"Delete project"]})]}):null]}):R==="report"?e.jsx($f,{projectName:s.project.name}):R==="queries"||R==="discovery"?e.jsx(ip,{projectName:g,queryWorkspace:D.queryWorkspace==="research"||R==="discovery"&&D.queryWorkspace===void 0?"research":"tracked",onQueryWorkspaceChange:I=>G({queryWorkspace:I,trackingQueryId:void 0}),researchMode:D.researchMode==="test"?"test":"find",onResearchModeChange:I=>G({researchMode:I}),selection:J,onSelectionChange:G,trackingQueryId:typeof D.trackingQueryId=="string"?D.trackingQueryId:void 0,onTrackingQueryIdChange:I=>G({trackingQueryId:I})}):R==="technical-aeo"?e.jsx(pm,{projectName:s.project.name,projectId:s.project.id,initialRunId:D.siteHealthRunId,onReleaseInitialRun:de}):R==="conversions"?e.jsxs(e.Fragment,{children:[e.jsx(pg,{projectName:s.project.name},`${s.project.id}:performance`),e.jsx(tg,{projectId:s.project.id,projectName:s.project.name},s.project.id)]}):R==="history"?e.jsx($p,{projectName:s.project.name}):R==="activity"?e.jsx(wh,{projectName:s.project.name}):R==="backlinks"?e.jsx(cx,{projectName:s.project.name}):R==="local"?e.jsx(Fh,{projectName:s.project.name,projectId:s.project.id}):R==="search-console"?e.jsx(ry,{projectName:s.project.name}):null]})}export{Sy as ProjectPage,ly as ProjectSubnav,ty as ProjectSweepConfirmation,ny as patchProjectDashboardCache};
|