@canonry/canonry 4.177.3 → 4.178.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/assets/{AuditHistoryPanel-YZvGU1la.js → AuditHistoryPanel-BmKdyRrR.js} +1 -1
- package/assets/assets/{BacklinksPage-CB2uJWWy.js → BacklinksPage-DtqKPVLV.js} +1 -1
- package/assets/assets/{ChartPrimitives-BoYe2M-i.js → ChartPrimitives-B_LDVvTy.js} +1 -1
- package/assets/assets/{HistoryPage-D9IxxbQ9.js → HistoryPage-yyJsQiJQ.js} +1 -1
- package/assets/assets/{MeasurementPropertyPage-CxgnnPdp.js → MeasurementPropertyPage-hjW4iYtr.js} +1 -1
- package/assets/assets/ProjectPage-DZKpnPvq.js +9 -0
- package/assets/assets/{RunRow-2KxOta8F.js → RunRow-BZeBFb22.js} +1 -1
- package/assets/assets/{RunsPage-ya8vTkyd.js → RunsPage-tnXHsK_R.js} +1 -1
- package/assets/assets/{SettingsPage-lTy3o2bo.js → SettingsPage-Djj5k8vv.js} +1 -1
- package/assets/assets/{SiteHealthSection-Cyu7MIv2.js → SiteHealthSection-BkDncS11.js} +3 -3
- package/assets/assets/{TrafficPage-DjhKfw57.js → TrafficPage-nJggXVh-.js} +1 -1
- package/assets/assets/{TrafficSourceDetailPage-Pwi-Dl9Q.js → TrafficSourceDetailPage-zxONbSn-.js} +1 -1
- package/assets/assets/{extract-error-message-I1FVWHLH.js → extract-error-message-NpQu2vBm.js} +1 -1
- package/assets/assets/{index-DQVTRT9J.css → index-D0GbiVhZ.css} +1 -1
- package/assets/assets/index-Dwwnkd_V.js +83 -0
- package/assets/assets/{react-sigma_core.esm.min-BX6mOEq5.js → react-sigma_core.esm.min-CxMdd8U8.js} +1 -1
- package/assets/index.html +2 -2
- package/dist/{chunk-QRE3DAAU.js → chunk-A7FB2BVW.js} +2 -2
- package/dist/{chunk-7ABFIVKO.js → chunk-O7J5WFVZ.js} +361 -100
- package/dist/{chunk-6XUWDSLN.js → chunk-SXKA4OXZ.js} +1356 -907
- package/dist/{chunk-PQT3ECM3.js → chunk-T4JH77O6.js} +107 -0
- package/dist/{chunk-5EH666EO.js → chunk-YIQMTOEZ.js} +2970 -2054
- package/dist/cli.js +87 -5
- package/dist/index.js +4 -4
- package/dist/{intelligence-service-CHZGHFGS.js → intelligence-service-YISV327N.js} +2 -2
- package/dist/mcp.js +5 -380
- package/package.json +8 -8
- package/assets/assets/ProjectPage-CPmaXzhL.js +0 -9
- package/assets/assets/index-BeLVKN3H.js +0 -83
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{r as l,j as e,L as as,n as Cs,u as Ie,o as Et,B as yr,C as Eo,h as qo,k as Oo,D as Go}from"./vendor-tanstack-Dock0eH1.js";import{M as jr,I as Je,T as oe,t as Fo,a as _o,u as Nr,C as Uo,P as Js,B as P,h as Bo,b as Vo,c as Ko,d as pe,i as J,e as ft,f as Me,g as an,j as zo,k as U,l as Qo,m as Ho,n as Wo,o as Yo,p as wr,q as Xo,r as Jo,S as Ls,s as Zo,v as el,w as Ts,x as qt,y as tl,z as hi,A as Sr,G as $t,D as Ba,E as sl,F as nl,H as al,J as il,K as xi,L as Se,N as rl,O as ol,Q as oa,R as ll,U as cl,V as dl,W as ul,X as ml,Y as hl,Z as xl,_ as pl,$ as gl,a0 as fl,a1 as bl,a2 as vl,a3 as yl,a4 as jl,a5 as Nl,a6 as Cr,a7 as Os,a8 as wl,a9 as kr,aa as Kn,ab as Sl,ac as Ye,ad as Cl,ae as kl,af as Al,ag as zn,ah as Pl,ai as Rl,aj as Il,ak as Zs,al as $l,am as Tl,an as Ml,ao as Ar,ap as Ta,aq as Ll,ar as Pr,as as Dl,at as Va,au as El,av as ql,aw as Ol,ax as Gl,ay as Fl,az as _l,aA as Ul,aB as hn,aC as Ds,aD as Bl,aE as Vl,aF as Kl,aG as zl,aH as Rr,aI as Ql,aJ as Hl,aK as Wl,aL as Yl,aM as Xl,aN as Ir,aO as Jl,aP as Zl,aQ as ec,aR as tc,aS as sc,aT as nc,aU as ac,aV as ic,aW as rc,aX as oc,aY as lc,aZ as cc,a_ as dc,a$ as uc,b0 as mc,b1 as hc,b2 as xc,b3 as pc,b4 as gc,b5 as fc,b6 as ts,b7 as bc,b8 as it,b9 as vc,ba as yc,bb as jc,bc as Nc,bd as wc,be as Sc,bf as Cc,bg as kc,bh as Ac,bi as Pc,bj as Rc,bk as Ic,bl as $c,bm as Tc,bn as Mc,bo as Lc,bp as Dc,bq as Ec,br as qc,bs as Oc,bt as Gc,bu as Fc,bv as _c,bw as Uc,bx as Bc,by as Vc,bz as Kc,bA as zc,bB as Qc,bC as Hc,bD as Wc,bE as Yc,bF as Xc,bG as Jc,bH as Zc,bI as ed,bJ as td,bK as sd,bL as la,bM as nd,bN as ad,bO as pi,bP as id,bQ as rd,bR as od,bS as ld,bT as cd,bU as dd,bV as ud,bW as md,bX as hd,bY as xd,bZ as pd,b_ as gd,b$ as $r,c0 as fd,c1 as bd,c2 as vd,c3 as yd,c4 as jd,c5 as Nd,c6 as wd,c7 as gi,c8 as Sd,c9 as ca,ca as Cd,cb as kd,cc as Ad,cd as Pd,ce as Rd,cf as Id,cg as $d,ch as Tr,ci as Td,cj as Md,ck as Ld,cl as Dd,cm as Ed,cn as qd,co as Pn,cp as Od,cq as Gd,cr as Fd,cs as fi,ct as _d}from"./index-Dwwnkd_V.js";import{R as Ud}from"./RunRow-BZeBFb22.js";import{u as pn,D as Hs,a as Es,b as Mr,M as Un,c as os,S as Bd}from"./SiteHealthSection-BkDncS11.js";import{e as Vd,q as Qn,U as Kd,r as zd,L as Qd,s as Lr,i as Hd,P as Hn,D as Dr,t as Wd,u as Yd,E as Xd,C as Wn,v as Jd}from"./vendor-lucide-nYKv-BB7.js";import{f as gn,C as Gs,a as ns,b as Ut,c as Ws,d as Ht,e as rt,g as qs,M as Er,h as qr,i as Or,o as us,j as Ss,p as Zd}from"./ChartPrimitives-B_LDVvTy.js";import{u as eu,t as tu,e as su,a as ut}from"./extract-error-message-NpQu2vBm.js";import{R as fn,C as bn,X as vn,Y as yn,T as jn,L as Gr,A as zs,a as Fr,b as nu,d as _r,e as au}from"./vendor-recharts-D8rt5lKn.js";import{A as iu}from"./AuditHistoryPanel-BmKdyRrR.js";import{a as ru,b as ou}from"./v2-overview-adapter-COMP5UGt.js";import"./vendor-radix-4UOaVWza.js";import"./vendor-markdown-Bn7fRwrx.js";import"./vendor-yaml-GWJz5H2G.js";function Bn(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 lu(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 i=t;i<=s&&(a.push(i),!(a.length>=n));i=cu(i,1));return a}function cu(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 i=a.getUTCFullYear(),r=String(a.getUTCMonth()+1).padStart(2,"0"),o=String(a.getUTCDate()).padStart(2,"0");return`${i}-${r}-${o}`}function du(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 uu(t,s){const n=du(t,s);return n===null?null:Math.round(n*100)}function da(t,s,n="vs prior 7 days"){return t.deltaPct===null?t.prior===0?"First baseline week":"":t.deltaPct>0?`Up ${t.deltaPct}% ${n} (${Bn(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${Bn(t.prior)} ${s})`:`Flat ${n} (${Bn(t.prior)} ${s})`}const Ur=30;function bi(t){return Math.round(t*10)/10}function mu(t){return t.prior>=Ur&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% vs prior`:`${t.deltaAbs>0?"+":""}${bi(t.deltaAbs)} vs ${bi(t.prior)}`}function hu(t,s,n){return t.prior>=Ur&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% ${n}`:`${t.deltaAbs>0?"+":""}${Bn(Math.round(t.deltaAbs))} ${s} ${n}`}const xu=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function Br(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function Vr(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 Kr(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(Br).map(Vr).filter(Boolean)):new Set}function zr(t,s){const n=Br(t).map(Vr).filter(Boolean).filter(a=>!xu.has(a)).filter(a=>!s.has(a));return[...new Set(n)].sort().join(" ")}function pu(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function gu(t,s){const n=Kr(t);if(s.length<=1||n.size===0)return[...s];const a=new Set,i=[];for(const r of s){if(r.category!=="content"){i.push(r);continue}const o=zr(pu(r),n);!o||a.has(o)||(a.add(o),i.push(r))}return i}function fu(t){const s=Kr(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const a=new Set;return n.filter(i=>{const r=zr(i.query,s);return!r||a.has(r)?!1:(a.add(r),!0)})}const bu=1e6;function vu(t,s="USD"){return new Intl.NumberFormat("en-US",{style:"currency",currency:s}).format(t/bu)}const Qr={queryClass:"all"},yu=["all","non-brand","branded"];function ju(t){return typeof t=="string"&&yu.includes(t)}function Nu(t){const s=ju(t.class)?t.class:Qr.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 wu(t,s){return s===null||t===null?!1:t!==s}function Su(t){return{scope:t.scope==="group"&&t.groupKey?`group:${t.groupKey}`:void 0,class:t.queryClass===Qr.queryClass?void 0:t.queryClass}}const As=[{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],vi={"non-brand":"Non-brand",branded:"Branded",pooled:"All queries"},Cu={"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."},ku="Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other.";function Au(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 Pu({breakdown:t,projectLabel:s,competitorDomains:n}){const a=t.projectMentionSnapshots+t.competitorMentionSnapshots;if(a===0)return null;const i=new Map(t.perCompetitor.map(o=>[o.domain,o.mentionSnapshots])),r=[{label:`${s} (you)`,mentions:t.projectMentionSnapshots,isYou:!0},...n.map(o=>({label:o,mentions:i.get(o)??0,isYou:!1}))].sort((o,m)=>m.mentions-o.mentions||(o.label<m.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(Je,{text:ku})]}),e.jsx("th",{scope:"col",className:"mention-share-share",children:"Share"})]})}),e.jsx("tbody",{className:"mention-share-rows",children:r.map(o=>{const m=o.mentions/a*100;return e.jsxs("tr",{className:"mention-share-row",children:[e.jsx("th",{scope:"row",className:`mention-share-row-label ${o.isYou?"text-heading font-medium":"text-secondary"}`,children:o.label}),e.jsx("td",{"aria-hidden":"true",children:e.jsx("div",{className:"mention-share-bar",children:e.jsx("div",{className:`mention-share-bar-fill ${o.isYou?"bg-positive-500/70":"bg-mono-500/60"}`,style:{width:`${m>0?Math.max(m,1.5):0}%`}})})}),e.jsx("td",{className:"mention-share-count",children:o.mentions}),e.jsxs("td",{className:"mention-share-share",children:[m.toFixed(1),"%"]})]},o.label)})})]})}function Ru({summary:t,projectLabel:s,competitorDomains:n}){const[a,i]=l.useState("non-brand"),r=l.useId(),o=t.scope==="pooled",m=!o&&t.branded.snapshotsTotal>0,c=m?a:"non-brand",h=o?"pooled":c,p=c==="branded"?t.branded:t.breakdown,u=c==="branded"?t.breakdown:t.branded,v=Au(p,{hasCompetitors:n.length>0,unavailable:t.unavailable===!0,noRun:t.breakdown.snapshotsTotal===0&&t.branded.snapshotsTotal===0,otherClassHasData:u.snapshotsTotal>0}),j=h==="non-brand"?jr[t.tone]:"text-secondary";function b(g){const f=As.findIndex(O=>O.value===c);let k=null;g.key==="ArrowRight"||g.key==="ArrowDown"?k=(f+1)%As.length:g.key==="ArrowLeft"||g.key==="ArrowUp"?k=(f-1+As.length)%As.length:g.key==="Home"?k=0:g.key==="End"&&(k=As.length-1),k!==null&&(g.preventDefault(),i(As[k].value),g.currentTarget.querySelectorAll('[role="radio"]')[k]?.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:r,className:"mention-share-label-text",children:"Mention share"}),e.jsx(Je,{text:Cu[h]})]}),m?e.jsx("div",{role:"radiogroup","aria-labelledby":r,className:"segmented flex-wrap",onKeyDown:b,children:As.map(g=>{const f=g.value===c;return e.jsx("button",{type:"button",role:"radio","aria-checked":f,tabIndex:f?0:-1,onClick:()=>i(g.value),className:`segmented-option min-h-11 ${f?"segmented-option-active":""}`,children:g.label},g.value)})}):e.jsx("span",{className:"mention-share-class",children:vi[h]})]}),v.numeric?e.jsxs("p",{className:`mention-share-value ${j}`,children:[v.headline,e.jsx("span",{className:"text-faint",children:"%"})]}):e.jsx("p",{className:"mention-share-value-text",children:v.headline}),e.jsxs("p",{className:"mention-share-caption",children:[e.jsx("span",{className:"mention-share-caption-scope",children:vi[h]}),` · ${v.detail}`]}),o&&e.jsx("p",{className:"mention-share-note",children:"Set a brand name to split branded from non-brand."}),v.showRows&&e.jsx(Pu,{breakdown:p,projectLabel:s,competitorDomains:n})]})}function Ma({state:t,label:s}){return e.jsx(oe,{tone:_o(t),children:s??Fo(t)})}function yi({history:t,maxDots:s=12}){const n=t.slice(-s);if(n.length===0)return e.jsx("span",{className:"text-[11px] text-faint",children:"No data"});const a={cited:"bg-positive-400","not-cited":"bg-mono-600",lost:"bg-negative-400",emerging:"bg-caution-400 ring-1 ring-caution-300/60"},i={cited:"rounded-full","not-cited":"rounded-sm",lost:"rotate-45 rounded-[1px]",emerging:"rounded-full"},r=n.length-1,o=new Date(n[0].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),m=new Date(n[r].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),c=n.map((h,p)=>{const u=new Date(h.createdAt).toLocaleDateString();return`${p===r?"Latest run, ":""}${u}: ${h.citationState}${h.model?`, model ${h.model}`:""}`}).join("; ");return e.jsxs("div",{className:"flex items-center gap-1",role:"img","aria-label":`Citation history across ${n.length} runs. ${c}`,children:[e.jsx("span",{className:"text-[9px] text-faint shrink-0","aria-hidden":"true",children:o}),e.jsx("div",{className:"flex items-center gap-[3px]",title:`${n.length} runs`,"aria-hidden":"true",children:n.map((h,p)=>{const u=!!(h.model&&p>0&&n[p-1]?.model&&n[p-1].model!==h.model),v=p===r;return e.jsx("span",{className:`h-2.5 w-2.5 ${i[h.citationState]??"rounded-sm"} ${a[h.citationState]??"bg-mono-700"} ${u?"ring-1 ring-caution-300/80 ring-offset-1 ring-offset-bg":""} ${v?"outline outline-1 outline-offset-2 outline-mono-400":""}`,title:[h.citationState,new Date(h.createdAt).toLocaleDateString(),h.model?`model ${h.model}`:null,u?"model changed":null,v?"latest run":null].filter(Boolean).join(" · ")},`${h.runId}:${h.createdAt}`)})}),e.jsxs("span",{className:"text-[9px] shrink-0 text-secondary","aria-hidden":"true",children:[m," ",e.jsx("span",{className:"text-faint",children:"latest"})]})]})}function La(t){const s=new Map;for(const a of t)for(const i of a.runHistory){const r=s.get(i.createdAt);r?r.states.push(i.citationState):s.set(i.createdAt,{states:[i.citationState],runId:i.runId})}return[...s.entries()].sort(([a],[i])=>a.localeCompare(i)).map(([a,{states:i,runId:r}])=>({runId:r,createdAt:a,citationState:i.includes("cited")?"cited":i.includes("emerging")?"emerging":"not-cited"}))}const Iu=320;function $u(t){return[t.phrase,t.location??"",...t.rawItems.map(s=>s.provider)].join(" ")}function ji(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 Ni(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 wi(t,s){const n=s==="mentions"?"mentioned":"cited",a=s==="mentions"?"Mentioned":"Cited";if(t.length===0)return"Awaiting first run";if(t.length===1)return"First observation";const i=t[t.length-1].citationState,r=t[t.length-2].citationState;if(r!=="cited"&&i==="cited")return`Newly ${n}`;if(r==="cited"&&i!=="cited")return"Lost since last run";let o=0;for(let m=t.length-1;m>=0&&t[m].citationState===i;m--)o++;return i==="cited"?o<=1?`${a} in latest run`:`${a} for ${o} runs`:o<=1?`Not ${n} in latest run`:`Not ${n} across ${o} runs`}function Tu(t,s){return t.map(n=>Hr(n,s))}function Hr(t,s){return s==="citations"?t:{...t,citationState:ji(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:ji(n,s)}))}}function Si(t,s){const n=s==="mentions"?"mention":"citation",a=s==="mentions"?"Mention":"Citation";if(t.length===0)return{key:s,label:`${a} pending`,tone:"pending"};const i=t[t.length-1].citationState,r=t.length>=2?t[t.length-2].citationState:null,o=i==="cited"||i==="emerging",m=r==="cited"||r==="emerging";return i==="lost"||r!==null&&m&&!o?{key:s,label:`Lost ${n}`,tone:"negative"}:i==="emerging"||r!==null&&!m&&o?{key:s,label:`New ${n}`,tone:"positive"}:r===null&&o?{key:s,label:`First ${n}`,tone:"positive"}:o?{key:s,label:s==="mentions"?"Still mentioned":"Still cited",tone:"neutral"}:{key:s,label:`No ${n}`,tone:"neutral"}}function Mu(t){const s=La(Tu(t,"mentions")),n=La(t);return[Si(s,"mentions"),Si(n,"citations")]}function Lu({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 Ci({items:t}){return e.jsx("div",{className:"mt-1 flex flex-wrap gap-1","aria-label":"Latest run mention and citation signals",children:Mu(t).map(s=>e.jsx(Lu,{signal:s},s.key))})}function Du({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:a}=Nr(),[i,r]=l.useState(new Set),[o,m]=l.useState("mentions"),[c,h]=l.useState(n),p=l.useMemo(()=>{const O=new Map;for(const q of t){const A=q.query,d=s?q.location??null:null,y=s?JSON.stringify([A,d]):A,S=O.get(y)??{key:y,phrase:A,location:d,items:[],rawItems:[]};S.items.push(Hr(q,o)),S.rawItems.push(q),O.set(y,S)}return[...O.values()]},[t,o,s]),u=pn({rows:p,getSearchText:$u}),v=u.rows.map(O=>O.key),j=v.length>0&&v.every(O=>i.has(O)),b=O=>{r(q=>{const A=new Set(q);return A.has(O)?A.delete(O):A.add(O),A})},g=o==="mentions"?"mentioned":"cited",f=o==="mentions"?"Mention History":"Citation History",k=o==="mentions"?"mentioned":"cited";return e.jsxs("div",{children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"View by"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-bg-elevated/60 border border-subtle",role:"tablist","aria-label":"Citation tracking view",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":o==="mentions",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${o==="mentions"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>m("mentions"),children:"Mentions"}),e.jsx("button",{type:"button",role:"tab","aria-selected":o==="citations",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${o==="citations"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>m("citations"),children:"Citations"})]}),e.jsx("span",{className:"text-[11px] text-muted",children:o==="mentions"?"Brand or domain in answer text":"Brand or domain in source links"}),e.jsxs("div",{className:"ml-auto flex items-center gap-3",children:[e.jsx("button",{type:"button",className:"text-[11px] text-secondary hover:text-strong",onClick:()=>{r(O=>{const q=new Set(O);for(const A of v)j?q.delete(A):q.add(A);return q})},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:()=>h("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:()=>h("detailed"),children:"Detailed"})]})]})]})]}),p.length>0?e.jsx(Hs,{value:u.query,onChange:u.setQuery,label:"Filter tracked queries",placeholder:"Filter query, location, or provider",className:"mb-3 max-w-md"}):null,e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{style:{width:"2rem"}}),e.jsx("th",{scope:"col",children:"Query"}),e.jsx("th",{scope:"col",children:"Status"}),e.jsx("th",{scope:"col",children:f}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:u.rows.map(({key:O,phrase:q,location:A,items:d,rawItems:y})=>{const S=i.has(O),V=d.map($=>$.citationState),K=V.includes("cited")?"cited":V.includes("emerging")?"emerging":V.includes("lost")?"lost":V.every($=>$==="pending")?"pending":"not-cited",w=La(d),T=d.filter($=>$.citationState===Uo.cited||$.citationState==="emerging").length,F=wi(w,o);return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"cursor-pointer hover:bg-mono-800/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>b(O),onKeyDown:$=>{($.key==="Enter"||$.key===" ")&&($.preventDefault(),b(O))},tabIndex:0,role:"button","aria-expanded":S,children:[e.jsx("td",{children:e.jsx(Vd,{size:14,className:`transition-transform duration-150 text-muted ${S?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-heading",children:q}),s&&e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-muted",children:A??"No location"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:d.map($=>e.jsx(Js,{provider:$.provider},$.id))})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ma,{state:K,label:Ni(K,o)}),e.jsxs("span",{className:"text-[11px] text-muted",title:`${T} of ${d.length} engines ${k}`,children:[T,"/",d.length]})]})}),e.jsx("td",{children:e.jsx(yi,{history:w})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:F}),e.jsx(Ci,{items:y})]}),e.jsx("td",{})]}),S&&d.map(($,H)=>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(Js,{provider:$.provider})}),e.jsx("td",{children:e.jsx(Ma,{state:$.citationState,label:Ni($.citationState,o)})}),e.jsx("td",{children:e.jsx(yi,{history:$.runHistory})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:wi($.runHistory,o)}),e.jsx(Ci,{items:[y[H]??$]})]}),e.jsx("td",{children:e.jsx(P,{variant:"ghost",size:"sm",type:"button",onClick:ye=>{ye.stopPropagation(),a($.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(Ou,{item:$,onViewFull:()=>a($.id)})})]})]},$.id))]},O)})})]})}),u.totalRows===0&&u.hasQuery?e.jsx("p",{className:"supporting-copy mt-3",children:"No tracked queries match this filter."}):null,e.jsx(Es,{page:u.page,pageSize:u.pageSize,visibleRows:u.rows.length,totalRows:u.totalRows,onPageChange:u.setPage,itemLabel:u.hasQuery?"matches":"queries"}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",g==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function Eu(t){const s=(t.matchedTerms??[]).filter(i=>i.trim().length>2),n=[...(t.mentionedCompetitorDomains??[]).flatMap(i=>{const r=Vo(i);return r.length>=4?[r]:[]}),...t.recommendedCompetitors??[]].filter(i=>i.trim().length>2),a=[];return s.length>0&&a.push({terms:s,className:"answer-highlight-brand"}),n.length>0&&a.push({terms:n,className:"answer-highlight-competitor"}),a}function ki(t,s){const n=s.toLowerCase().replace(/^www\./,"");return(t.citedCompetitorDomains??[]).some(a=>a.toLowerCase().replace(/^www\./,"")===n)}function qu(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 Ou({item:t,onViewFull:s}){if(!(t.answerSnippet.trim().length>0))return e.jsx("p",{className:"text-[11px] text-muted italic",children:"No answer text captured for this run."});const{body:a,truncated:i}=qu(t.answerSnippet,Iu),r=Eu(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:Bo(a,r)}),(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(o=>e.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[11px] ${ki(t,o)?"border-negative-900/40 bg-negative-950/30 text-negative":"border-mono-700/60 bg-bg-elevated/60 text-neutral"}`,children:[o,ki(t,o)?" · competitor source":""]},`c-${o}`)),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(o=>e.jsx("span",{className:"rounded-full border border-negative-900/40 bg-negative-950/30 px-2 py-0.5 text-[11px] text-negative",children:o},`co-${o}`)),t.mentionedCompetitorDomains.length>4&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.mentionedCompetitorDomains.length-4," more"]})]})]}),i&&e.jsx("button",{type:"button",className:"text-[11px] font-medium text-positive-400 hover:text-positive",onClick:o=>{o.stopPropagation(),s()},children:"View full answer →"})]})}function Gu({competitors:t,onSelectCompetitor:s,onRemoveCompetitor:n,activeFilter:a}){if(t.length===0)return e.jsx("p",{className:"text-sm text-muted",children:"No competitors configured. Add competitors to track overlap."});const i=s!=null,r=n!=null;return e.jsx("div",{className:"competitor-table-wrap",children:e.jsxs("table",{className:"competitor-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Domain"}),e.jsx("th",{children:"Pressure"}),e.jsx("th",{children:"Citations"}),e.jsx("th",{children:"Queries"}),r&&e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{children:t.map(o=>{const m=a!=null&&a.toLowerCase()===o.domain.toLowerCase(),c=[i?"cursor-pointer hover:bg-mono-800/30 transition-colors":"",m?"bg-negative-950/20":""].filter(Boolean).join(" ");return e.jsxs("tr",{className:c,onClick:i?()=>s(o.domain):void 0,title:i?`Filter answers to queries where ${o.domain} surfaced`:void 0,children:[e.jsx("td",{className:"font-medium text-heading",children:o.domain}),e.jsx("td",{children:e.jsx(oe,{tone:Ko(o.pressureLabel),children:o.pressureLabel})}),e.jsx("td",{className:"text-neutral tabular-nums",children:o.totalQueries>0?`${o.citationCount} / ${o.totalQueries}`:"—"}),e.jsx("td",{className:"text-muted text-xs",children:o.citedQueries.length>0?o.citedQueries.join(", "):"Not cited"}),r&&e.jsx("td",{className:"text-right",children:e.jsx("button",{type:"button",className:"rounded px-1.5 py-0.5 text-xs text-muted transition-colors hover:text-negative-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-negative-500","aria-label":`Remove competitor ${o.domain}`,title:`Remove ${o.domain}`,onClick:h=>{h.stopPropagation(),n(o.domain)},children:"Remove"})})]},o.id)})})]})})}function Rn({label:t,value:s,tone:n}){const a=n==="positive"?"text-positive-400":n==="negative"?"text-negative-400":"text-strong";return e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:t}),e.jsx("p",{className:`mt-2 text-2xl font-semibold ${a}`,children:s})]})}const Fu=6,en="__other__",Ys="_socialTotal";function _u(t,s=Fu){const n=new Map;for(const p of t)n.set(p.source,(n.get(p.source)??0)+p.sessions);const a=[...n.entries()].sort((p,u)=>u[1]!==p[1]?u[1]-p[1]:p[0].localeCompare(u[0])),i=a.slice(0,s),r=new Set(i.map(([p])=>p)),o=Math.max(0,a.length-s),m=new Map;for(const p of t){let u=m.get(p.date);u||(u={date:p.date,[Ys]:0},m.set(p.date,u));const v=r.has(p.source)?p.source:en;u[v]=(u[v]??0)+p.sessions,u[Ys]=(u[Ys]??0)+p.sessions}const c=[...m.values()].sort((p,u)=>String(p.date).localeCompare(String(u.date))),h=i.map(([p])=>p);return o>0&&h.push(en),{data:c,sources:h,otherCount:o}}function Xs(t){return t.replace(/\+/g," ")}function Wr(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const Ai="_totalSessions",Pi="_organicSessions";function Uu(t,s){const n=new Map;for(const o of s)n.set(o.date,{[Ai]:o.sessions,[Pi]:o.organicSessions});for(const o of t.days){let m=n.get(o.date);m||(m={[Ai]:0,[Pi]:0},n.set(o.date,m));for(const c of o.bySource)m[c.source]=(m[c.source]??0)+c.sessions}const a=[...n.entries()].sort(([o],[m])=>o.localeCompare(m)).map(([o,m])=>({date:o,...m})),i=a.map(o=>o.date),r=i.length>0?{start:i[0],end:i[i.length-1]}:null;return{data:a,sources:t.sources,dateRange:r}}const Bu=["7d","30d","90d","all"],js=rt,Da=Ht.textDim,Yr=Ht.textFaint,rn=25;function Vu(t){return Mr(t.landingPage)}const Ku=25,zu=10,ua={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0};function In(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function Xr(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 Qu({projectName:t}){const{data:s,isLoading:n,isError:a}=eu(t);if(n)return e.jsx(pe,{className:"p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading server activity…"})});if(a)return e.jsx(pe,{className:"p-5",children:e.jsx("div",{className:"text-sm text-negative-400",children:"Failed to load server activity."})});const i=s?.sources??[];return e.jsxs("section",{children:[e.jsx("div",{className:"flex items-baseline justify-between mb-3",children:e.jsxs("div",{children:[e.jsx("div",{className:"eyebrow",children:"Server activity (last 24h)"}),e.jsx("h2",{className:"text-lg font-semibold text-primary",children:"Server activity"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["Crawler, AI fetch, and referral activity from connected sources."," ",!J()&&e.jsx(as,{to:"/traffic",className:"text-link hover:underline",children:"Manage sources →"})]})]})}),i.length===0?e.jsx(pe,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-secondary",children:["No server traffic source connected yet."," ",!J()&&e.jsxs(e.Fragment,{children:[e.jsx(as,{to:"/traffic",className:"text-link hover:underline",children:"Connect a traffic source"})," ","to surface bot crawls and AI referrals straight from server logs."]})]})}):e.jsx(pe,{className:"overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-bg-elevated/50 text-[10px] uppercase tracking-wide text-muted",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Source"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Status"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Crawler hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI sessions 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Last sync"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium","aria-label":"open"})]})}),e.jsx("tbody",{children:i.map(r=>e.jsxs("tr",{className:"border-t border-default",children:[e.jsx("td",{className:"px-4 py-3 text-heading",children:r.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(oe,{tone:tu(r.status),children:r.status})}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:r.totals24h.crawlerHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:r.totals24h.aiUserFetchHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:r.totals24h.aiReferralLandedHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right text-secondary text-xs",children:r.lastSyncedAt?Xr(r.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:J()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(as,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:r.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},r.id))})]})})]})}function Hu({projectName:t}){return e.jsxs("div",{className:"space-y-10",children:[e.jsx(Qu,{projectName:t}),e.jsx(Wu,{projectName:t})]})}function Wu({projectName:t}){const s=Cs(),[n,a]=l.useState(null),[i,r]=l.useState(null),[o,m]=l.useState(!0),[c,h]=l.useState(!1),[p,u]=l.useState(!1),[v,j]=l.useState(null),[b,g]=l.useState(null),[f,k]=l.useState("sessions"),[O,q]=l.useState("desc"),[A,d]=l.useState("sessions"),[y,S]=l.useState("desc"),[V,K]=l.useState("sessions"),[w,T]=l.useState("desc"),[F,$]=l.useState("sessions"),[H,ye]=l.useState("desc"),[ge,z]=l.useState(ua),[ee,ie]=l.useState([]),[W,B]=l.useState([]),[R,se]=l.useState(!1),[le,de]=l.useState("30d");async function X(G){m(!0),j(null);try{const ke=await s.fetchQuery({...zo({client:U,path:{name:t}}),staleTime:an});if(G.current)return;if(a(ke),!ke.connected){r(null),z(ua),ie([]),B([]),m(!1);return}const fe=le==="all"?void 0:le,he=await s.fetchQuery({...Qo({client:U,path:{name:t},query:fe?{window:fe}:void 0}),staleTime:an}).then(Wt=>Wt),Mt=he.windowStart||he.windowEnd?{...he.windowStart?{startDate:he.windowStart}:{},...he.windowEnd?{endDate:he.windowEnd}:{}}:void 0,[ct,Pt,Lt]=await Promise.all([s.fetchQuery({...Ho({client:U,path:{name:t},query:fe?{window:fe}:void 0}),staleTime:an}).catch(()=>ua),s.fetchQuery({...Wo({client:U,path:{name:t},query:fe?{window:fe}:void 0}),staleTime:an}).catch(()=>[]),s.fetchQuery({...Yo({client:U,path:{name:t},query:Mt}),staleTime:an}).catch(()=>[])]);if(G.current)return;r(he),z(ct),ie(Pt),B(Lt),m(!1)}catch(ke){if(G.current)return;j(ke instanceof Error?ke.message:"Failed to load GA4 data"),m(!1)}}l.useEffect(()=>{const G={current:!1};return X(G),()=>{G.current=!0}},[t,le,s]);async function Ae(){h(!0),j(null),g(null);try{const G=await wr(t);g(`Synced ${G.rowCount.toLocaleString()} page rows, ${G.aiReferralCount.toLocaleString()} AI and ${G.socialReferralCount.toLocaleString()} social referral rows (${G.days} days)`),await ft(s,"ga"),await X({current:!1})}catch(G){j(G instanceof Error?G.message:"Sync failed")}finally{h(!1)}}async function _(){u(!0),j(null),g(null);try{await Xo(t),await ft(s,"ga"),a({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),r(null),g("GA4 disconnected")}catch(G){j(G instanceof Error?G.message:"Disconnect failed")}finally{u(!1)}}function ae(G){Pe.setPage(1),f===G?q(ke=>ke==="desc"?"asc":"desc"):(k(G),q("desc"))}function Ne(G){A===G?S(ke=>ke==="desc"?"asc":"desc"):(d(G),S("desc"))}function Le(G){V===G?T(ke=>ke==="desc"?"asc":"desc"):(K(G),T("desc"))}const Fe=l.useMemo(()=>i?.topPages?[...i.topPages].sort((G,ke)=>{const fe=G[f],he=ke[f];return typeof fe=="string"&&typeof he=="string"?O==="asc"?fe.localeCompare(he):he.localeCompare(fe):O==="asc"?fe-he:he-fe}):[],[i?.topPages,f,O]),Pe=pn({rows:Fe,getSearchText:G=>Mr(G.landingPage),pageSize:zu}),Qe=l.useMemo(()=>i?.aiReferrals?[...i.aiReferrals].sort((G,ke)=>{const fe=G[A],he=ke[A];return typeof fe=="string"&&typeof he=="string"?y==="asc"?fe.localeCompare(he):he.localeCompare(fe):y==="asc"?fe-he:he-fe}):[],[i?.aiReferrals,A,y]),ue=l.useMemo(()=>i?.aiReferralLandingPages?[...i.aiReferralLandingPages].sort((G,ke)=>{const fe=G[F],he=ke[F];return typeof fe=="string"&&typeof he=="string"?H==="asc"?fe.localeCompare(he):he.localeCompare(fe):H==="asc"?fe-he:he-fe}):[],[i?.aiReferralLandingPages,F,H]),we=pn({rows:ue,getSearchText:Vu,pageSize:Ku}),Ze=we.totalRows>0?`${we.totalRows.toLocaleString()} ${we.hasQuery?we.totalRows===1?"match":"matches":we.totalRows===1?"row":"rows"}`:we.hasQuery&&(i?.aiReferralLandingPages.length??0)>0?"0 matches":"No landing-page rows";function _e(G){we.setPage(1),F===G?ye(ke=>ke==="desc"?"asc":"desc"):($(G),ye("desc"))}const He=l.useMemo(()=>i?.socialReferrals?[...i.socialReferrals].sort((G,ke)=>{const fe=G[V],he=ke[V];return typeof fe=="string"&&typeof he=="string"?w==="asc"?fe.localeCompare(he):he.localeCompare(fe):w==="asc"?fe-he:he-fe}):[],[i?.socialReferrals,V,w]),{socialChartData:$e,socialChartSources:Ce,socialOtherCount:E}=l.useMemo(()=>{const G=_u(W);return{socialChartData:G.data,socialChartSources:G.sources,socialOtherCount:G.otherCount}},[W]),{chartData:M,chartSources:L,dateRange:je}=l.useMemo(()=>{const G=Uu(ge,ee);return{chartData:G.data,chartSources:G.sources,dateRange:G.dateRange}},[ge,ee]);if(o&&!n)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!n?.connected)return J()?e.jsx(pe,{className:"p-5",children:e.jsx("div",{className:"text-sm text-secondary",children:"No Google Analytics 4 property connected yet."})}):e.jsx(Yu,{projectName:t,onConnected:()=>{(async()=>(await ft(s,"ga"),await X({current:!1})))()}});const qe=i?.organicSharePctDisplay??"0%",Y=i?.channelBreakdown?.organic.sharePctDisplay??qe,Be=i?.channelBreakdown?.organic.sessions??i?.totalOrganicSessions??0,mt=i?.aiSessionsDeduped??0,ot=i?.channelBreakdown?.ai.sessions??i?.aiSessionsBySession??0,De=i?.channelBreakdown?.ai.sharePctDisplay??i?.aiSharePctBySessionDisplay??"0%",Oe=i?.paidAiSessionsBySession??0,xt=i?.paidAiSharePctBySessionDisplay??"0%",We=i?new Set(i.aiReferrals.map(G=>G.source.toLowerCase())).size:0,Ve=Qe[0]??null,Te=i?.totalDirectSessions??0,jt=i?.directSharePctDisplay??"0%",Tt=i?.channelBreakdown?.direct.sessions??Te,Ue=i?.channelBreakdown?.direct.sharePctDisplay??jt,Ge=i?.channelBreakdown?.other.sessions??i?.otherSessions??0,bt=i?.channelBreakdown?.other.sharePctDisplay??i?.otherSharePctDisplay??"0%",Ke=i?.socialSessions??0,Nt=i?.socialSharePctDisplay??"0%",kt=i?.channelBreakdown?.social.sessions??Ke,vt=i?.channelBreakdown?.social.sharePctDisplay??Nt,At=i?new Set(i.socialReferrals.map(G=>G.source.toLowerCase())).size:0,lt=He[0]??null;return e.jsxs(e.Fragment,{children:[v&&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:v}),b&&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:b}),e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-positive-500"}),e.jsxs("span",{className:"text-xs text-secondary",children:["Property ",e.jsx("span",{className:"text-neutral",children:n.propertyId}),n.clientEmail&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"text-muted",children:n.clientEmail})]})]})]}),!J()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(P,{variant:"outline",size:"sm",disabled:c,onClick:Me(Ae),children:[e.jsx(Qn,{className:`w-3.5 h-3.5 mr-1.5 ${c?"animate-spin":""}`}),c?"Syncing…":"Sync"]}),e.jsxs(P,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:p,onClick:Me(_),children:[e.jsx(Kd,{className:"w-3.5 h-3.5 mr-1.5"}),"Disconnect"]})]})]}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4 flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Traffic Overview"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Site Traffic",e.jsx(Je,{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.`})]})]}),e.jsx("div",{className:"segmented",role:"group","aria-label":"Traffic time period",children:Bu.map(G=>e.jsx("button",{type:"button","aria-pressed":le===G,className:`segmented-option ${le===G?"segmented-option-active":""}`,onClick:()=>de(G),children:G==="all"?"All":G},G))})]}),i?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(ma,{value:In(i.totalSessions),label:"Total Sessions",subtitle:i.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(ma,{value:In(i.totalOrganicSessions),label:"Organic Sessions",subtitle:`${qe} of total`,tone:"positive"}),e.jsx(ma,{value:i.totalUsers===null?"—":In(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."}),!J()&&e.jsxs(P,{variant:"outline",size:"sm",disabled:c,onClick:Me(Ae),children:[e.jsx(Qn,{className:`w-3.5 h-3.5 mr-1.5 ${c?"animate-spin":""}`}),"Sync from GA4"]})]})]}),i&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Traffic Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Traffic by channel",e.jsx(Je,{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."})]})]}),je&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(je.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(je.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),M.length>0&&e.jsxs(pe,{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:L.length>0?"AI vs. total sessions":"All sessions (baseline)"}),L.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),L.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(fn,{width:"100%",height:"100%",children:e.jsxs(bn,{data:M,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(vn,{dataKey:"date",tick:ns,tickLine:!1,axisLine:{stroke:Gs},tickFormatter:gn}),e.jsx(yn,{tick:ns,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(jn,{...Ws,labelFormatter:Ut,formatter:(G,ke)=>{const fe=typeof G=="number"?G.toLocaleString():String(G??0),he=String(ke??"");return he==="_totalSessions"?[fe,"Total Sessions"]:he==="_organicSessions"?[fe,"Organic Sessions"]:[fe,he]}}),e.jsx(Gr,{wrapperStyle:{fontSize:11,color:Ht.text},formatter:G=>G==="_totalSessions"?"Total Sessions":G==="_organicSessions"?"Organic Sessions":G}),e.jsx(zs,{type:"monotone",dataKey:"_totalSessions",stroke:Ht.textFaint,fill:Ht.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),L.map((G,ke)=>e.jsx(zs,{type:"monotone",dataKey:G,stackId:"ai",stroke:js[ke%js.length],fill:js[ke%js.length],fillOpacity:.4,strokeWidth:1.5},G))]})})})]}),e.jsxs(pe,{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(Jt,{label:"Organic",value:Y,hint:`${Be.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(Jt,{label:"Social",value:vt,hint:`${kt.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(Jt,{label:"Direct",value:Ue,hint:`${Tt.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(Jt,{label:"Visitors from AI (at least)",value:De,hint:Oe>0?`${ot.toLocaleString()} sessions · ${Oe.toLocaleString()} paid`:`${ot.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(Jt,{label:"Other channels",value:bt,hint:`${Ge.toLocaleString()} sessions`,tone:"neutral",tooltip:"Remaining GA4 session default channel groups after Known AI, Organic Search, Organic/Paid Social, and Direct are accounted for. This is a residual bucket, not a single source. It can include Referral, Email, Paid Search, Display, Cross-network, Shopping, Video, Affiliates, SMS, Mobile Push Notifications, Paid Other, and unclassified traffic."})]}),Ve&&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:Ve.source})," via ",Ve.medium,", accounting for ",Ve.sessions.toLocaleString()," sessions.",Oe>0&&e.jsxs("span",{children:[" Paid AI: ",Oe.toLocaleString()," sessions (",xt,")."]})]})]}),e.jsxs(pe,{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?`${We} 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(_t,{label:"Source",sortKey:"source",current:A,dir:y,onSort:Ne,align:"left"}),e.jsx(_t,{label:"Medium",sortKey:"medium",current:A,dir:y,onSort:Ne,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(_t,{label:"Sessions",sortKey:"sessions",current:A,dir:y,onSort:Ne,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"})]})}),e.jsx("tbody",{children:Qe.map(G=>e.jsx(Ju,{referral:G,totalSessions:mt},`${G.source}:${G.medium}:${G.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(pe,{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:Ze})]}),i.aiReferralLandingPages.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Hs,{value:we.query,onChange:we.setQuery,label:"Filter landing page URLs or query parameters",placeholder:"Filter URL or query parameters",className:"mb-4 max-w-md"}),we.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(_t,{label:"Landing Page",sortKey:"landingPage",current:F,dir:H,onSort:_e,align:"left"}),e.jsx(_t,{label:"Source",sortKey:"source",current:F,dir:H,onSort:_e,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(_t,{label:"Sessions",sortKey:"sessions",current:F,dir:H,onSort:_e,align:"right"})]})}),e.jsx("tbody",{children:we.rows.map(G=>e.jsx(Zu,{row:G},`${G.landingPage}:${G.source}:${G.medium}:${G.sourceDimension}`))})]})}),e.jsx(Es,{page:we.page,pageSize:we.pageSize,visibleRows:we.rows.length,totalRows:we.totalRows,onPageChange:we.setPage,itemLabel:we.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:()=>we.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(Je,{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.length>0&&e.jsxs(pe,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social sessions"})]}),E>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",Ce.length-1," sources · ",E," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(fn,{width:"100%",height:"100%",children:e.jsxs(bn,{data:$e,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(vn,{dataKey:"date",tick:ns,tickLine:!1,axisLine:{stroke:Gs},tickFormatter:gn}),e.jsx(yn,{tick:ns,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(jn,{...Ws,labelFormatter:Ut,formatter:(G,ke)=>{const fe=typeof G=="number"?G.toLocaleString():String(G??0),he=String(ke??"");if(he===Ys)return[fe,"Total Social"];if(he===en){const Mt=`Other (${E} source${E===1?"":"s"})`;return[fe,Mt]}return[fe,Xs(he)]}}),e.jsx(zs,{type:"monotone",dataKey:Ys,stroke:Yr,fill:Ht.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),Ce.map((G,ke)=>{const he=G===en?Da:js[ke%js.length];return e.jsx(zs,{type:"monotone",dataKey:G,stackId:"social",stroke:he,fill:he,fillOpacity:.4,strokeWidth:1.5},G)})]})})}),e.jsx(tm,{sources:Ce,otherCount:E})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.5fr)]",children:[e.jsxs(pe,{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(Jt,{label:"Social Sessions",value:In(Ke),hint:`${Ke.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(Jt,{label:"Share of Traffic",value:Nt,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(Jt,{label:"Platforms",value:String(At),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."})]}),lt&&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:`${lt.source} via ${lt.medium}`,children:Wr(Xs(lt.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:lt.medium,children:["via ",Xs(lt.medium)," · ",lt.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(Jt,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(Jt,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(Jt,{label:"Platforms",value:"0",hint:"known platforms",tone:"neutral",tooltip:"Number of distinct social media platforms detected."})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3 text-sm text-secondary",children:[e.jsx("p",{className:"mb-1.5 text-neutral",children:"Monitoring social media traffic via GA4 channel grouping"}),e.jsx("p",{className:"text-xs text-muted",children:"Sessions classified as Organic Social or Paid Social by GA4 will appear here. Google maintains the source-to-channel mapping, which includes Facebook, Instagram, X/Twitter, LinkedIn, Reddit, Pinterest, Snapchat, and other platforms."})]})]})]}),e.jsxs(pe,{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?He.length>rn&&!R?`Top ${rn} of ${He.length}`:`${He.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(_t,{label:"Source",sortKey:"source",current:V,dir:w,onSort:Le,align:"left"}),e.jsx(_t,{label:"Medium",sortKey:"medium",current:V,dir:w,onSort:Le,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(_t,{label:"Sessions",sortKey:"sessions",current:V,dir:w,onSort:Le,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(_t,{label:"Users",sortKey:"users",current:V,dir:w,onSort:Le,align:"right"})]})}),e.jsx("tbody",{children:(R?He:He.slice(0,rn)).map(G=>e.jsx(em,{referral:G,totalSessions:Ke},`${G.source}:${G.medium}:${G.channelGroup}`))})]})}),He.length>rn&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>se(G=>!G),className:"rounded-md border border-base px-3 py-1.5 text-xs text-secondary transition-colors hover:border-strong hover:text-strong",children:R?`Show top ${rn}`:`Show all ${He.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(Je,{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(Hs,{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(_t,{label:"Landing Page",sortKey:"landingPage",current:f,dir:O,onSort:ae,align:"left"}),e.jsx(_t,{label:"Sessions",sortKey:"sessions",current:f,dir:O,onSort:ae,align:"right"}),e.jsx(_t,{label:"Organic",sortKey:"organicSessions",current:f,dir:O,onSort:ae,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"})]})}),e.jsx("tbody",{children:Pe.rows.map(G=>e.jsx(Xu,{page:G},G.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(Es,{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 ${Xr(i.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:i?`${i.topPages.length} pages · ${i.aiReferrals.length} AI rows · ${i.socialReferrals.length} social rows`:""})]})]})}function Yu({projectName:t,onConnected:s}){const[n,a]=l.useState(""),[i,r]=l.useState(null),[o,m]=l.useState(null),[c,h]=l.useState(!1),[p,u]=l.useState(null),v=l.useRef(null),j=l.useCallback(g=>{const f=g.target.files?.[0];if(!f)return;u(null),r(f.name);const k=new FileReader;k.onload=()=>{const O=k.result;try{const q=JSON.parse(O);if(!q.client_email||!q.private_key){u("JSON file is missing required fields: client_email and private_key. Make sure you downloaded a service account key (not an OAuth client)."),m(null);return}m(O)}catch{u("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),m(null)}},k.onerror=()=>{u("Failed to read file."),m(null)},k.readAsText(f)},[]);async function b(){if(u(null),!n.trim()){u("Property ID is required.");return}if(!o){u("Please upload a service account key file.");return}h(!0);try{await Jo(t,{propertyId:n.trim(),keyJson:o});try{await wr(t)}catch{}s()}catch(g){u(g instanceof Error?g.message:"Failed to connect GA4")}finally{h(!1)}}return e.jsxs(pe,{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."}),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}),e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{htmlFor:"ga4-property-id",className:"block text-xs font-medium text-secondary mb-1.5",children:"GA4 Property ID"}),e.jsx("input",{id:"ga4-property-id",type:"text",placeholder:"e.g. 123456789",value:n,onChange:g=>a(g.target.value),className:"w-full rounded-lg bg-bg-elevated/60 border border-default px-3 py-2 text-sm text-strong placeholder-mono-600 focus:outline-none focus:ring-1 focus:ring-mono-600"}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:"Find this in GA4 → Admin → Property Settings. It's a numeric ID, not the Measurement ID (G-XXXXXX)."})]}),e.jsxs("div",{className:"mb-5",children:[e.jsx("label",{className:"block text-xs font-medium text-secondary mb-1.5",children:"Service Account Key File"}),e.jsx("input",{ref:v,type:"file",accept:".json,application/json",onChange:j,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>v.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(zd,{className:"w-4 h-4 shrink-0"}),i?e.jsx("span",{className:"text-strong truncate",children:i}):e.jsx("span",{children:"Upload .json key file"})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Download from Google Cloud Console → IAM & Admin → Service Accounts → Keys → Add Key → JSON. The service account must have ",e.jsx("span",{className:"text-secondary",children:"Viewer"})," access on the GA4 property."]})]}),e.jsx(P,{variant:"default",size:"sm",disabled:c||!n.trim()||!o,onClick:Me(b),children:c?"Connecting & syncing…":"Connect GA4"})]})}function _t({label:t,sortKey:s,current:n,dir:a,onSort:i,align:r}){const o=n===s;return e.jsx("th",{className:`py-1 ${r==="right"?"text-right":"text-left"}`,children:e.jsxs("button",{type:"button",className:"font-medium cursor-pointer select-none hover:text-neutral transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-400 rounded",onClick:()=>i(s),"aria-label":`Sort by ${t}${o?` (currently ${a==="asc"?"ascending":"descending"})`:""}`,children:[t,o&&e.jsx("span",{className:"ml-0.5",children:a==="asc"?"↑":"↓"})]})})}const Jr={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function ma({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 ${Jr[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Jt({value:t,label:s,hint:n,tone:a,tooltip:i}){return e.jsxs("div",{className:"rounded-lg border border-default bg-bg/40 px-4 py-3 flex flex-col",children:[e.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1 flex items-center gap-1",children:[s,i&&e.jsx(Je,{text:i})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${Jr[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Xu({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 Zr={session:"Session",first_user:"First Visit",manual_utm:"UTM"},eo={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 Ju({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=Zr[t.sourceDimension]??t.sourceDimension,i=eo[t.sourceDimension]??"",r=t.trafficClass==="paid"?"Paid":"Organic",o=t.trafficClass==="paid"?"Paid AI traffic inferred from paid/cpc/sponsored UTM values or a GA4 paid channel group":"AI traffic without a paid attribution signal";return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 text-strong max-w-[220px] truncate",title:t.source,children:t.source}),e.jsx("td",{className:"py-1.5 text-muted max-w-[180px] truncate",title:t.medium,children:t.medium}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:`inline-block text-[10px] px-1.5 py-0.5 rounded-full border ${t.trafficClass==="paid"?"border-caution-700 text-caution-300":"border-strong text-secondary"}`,title:o,children:r})}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:i,children:a})}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[n,"%"]})]})}function Zu({row:t}){const s=Zr[t.sourceDimension]??t.sourceDimension,n=eo[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(Un,{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 em({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=t.channelGroup==="Paid Social"?"Paid":"Organic",i=Xs(t.source),r=Xs(t.medium);return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 pr-3 text-strong truncate",title:t.source,children:i}),e.jsx("td",{className:"py-1.5 pr-3 text-muted truncate",title:t.medium,children:r}),e.jsx("td",{className:"py-1.5 pr-3",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:`GA4 channel group: ${t.channelGroup}`,children:a})}),e.jsx("td",{className:"py-1.5 text-right text-info-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[n,"%"]}),e.jsx("td",{className:"py-1.5 text-right text-strong tabular-nums",children:t.users.toLocaleString()})]})}function tm({sources:t,otherCount:s}){const n=[{key:Ys,color:Yr,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const i=t[a];if(i===en)n.push({key:en,color:Da,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const r=Xs(i);n.push({key:i,color:js[a%js.length]??Da,label:Wr(r,32),tooltip:r})}}return e.jsx("div",{className:"mt-3 flex flex-wrap gap-x-4 gap-y-1.5 text-[11px] text-secondary",children:n.map(a=>e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 max-w-[260px]",title:a.tooltip,children:[e.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-sm shrink-0",style:{backgroundColor:a.color},"aria-hidden":"true"}),e.jsx("span",{className:"truncate",children:a.label})]},a.key))})}function to({windows:t,value:s,onChange:n,label:a,formatOption:i,disabled:r=!1}){return e.jsx("div",{className:"segmented",role:"group","aria-label":a,children:t.map(o=>e.jsx("button",{type:"button","aria-pressed":s===o,disabled:r,className:`segmented-option ${s===o?"segmented-option-active":""}`,onClick:()=>n(o),children:i?i(o):o},o))})}function sm(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 nm=["7d","30d","90d","all"],$n=500,Ri=[{key:"clicks",label:"Clicks",color:rt[1],format:t=>t.toLocaleString()},{key:"impressions",label:"Impressions",color:rt[4],format:t=>t.toLocaleString()},{key:"ctr",label:"CTR",color:qs.caution,format:t=>`${(t*100).toFixed(1)}%`},{key:"position",label:"Avg position",color:rt[2],inverted:!0,format:t=>t.toFixed(1)}],bs=25,am="canonry:google-oauth-complete",im=new Intl.NumberFormat(void 0,{maximumFractionDigits:1});function rm(t,s,n){if(!t)return"no comparison period";const a=t.days;if(!t.comparable)return"property-level comparison unavailable";const i=t.change[s];if(i===null||!Number.isFinite(i)){const c=t.prior[s],h=t.trailing[s];return c!==null&&h!==null&&c<=0&&h>0?`new in the last ${a}d`:c===null||c<=0?`no prior ${a}d to compare`:h===null?`no value in the last ${a}d`:"comparison unavailable"}if(i===0)return`→ no change vs prior ${a}d`;const r=Math.abs(i*100),o=r<.1?"<0.1%":`${im.format(r)}%`;return`${(n?i<0:i>0)?"↑":"↓"} ${o} vs prior ${a}d`}function Ii(t){return t.contents?.reduce((s,n)=>s+Number(n.submitted||0),0)??0}function $i(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 Ti(t){return t.isPending?"Processing":Number(t.errors??0)>0?"Errors":Number(t.warnings??0)>0?"Warnings":"Success"}function om({projectName:t,refreshNonce:s}){const n=Cs(),[a,i]=l.useState(!1),[r,o]=l.useState([]),[m,c]=l.useState([]),[h,p]=l.useState([]),[u,v]=l.useState(null),[j,b]=l.useState([]),[g,f]=l.useState([]),[k,O]=l.useState(null),[q,A]=l.useState(""),[d,y]=l.useState(""),[S,V]=l.useState("30"),[K,w]=l.useState(!1),[T,F]=l.useState("30d"),[$,H]=l.useState(["clicks","impressions"]),[ye,ge]=l.useState(!0),[z,ee]=l.useState(null),[ie,W]=l.useState(0),[B,R]=l.useState({startDate:"",endDate:"",query:"",page:""}),[se,le]=l.useState(0),[de,X]=l.useState(!1),[Ae,_]=l.useState(0),[ae,Ne]=l.useState(!1),[Le,Fe]=l.useState(""),[Pe,Qe]=l.useState(!0),[ue,we]=l.useState(!1),[Ze,_e]=l.useState(!1),[He,$e]=l.useState(!1),[Ce,E]=l.useState(!1),[M,L]=l.useState(!1),[je,qe]=l.useState(!1),[Y,Be]=l.useState(null),[mt,ot]=l.useState(!1),[De,Oe]=l.useState(!1),[xt,We]=l.useState(null),[Ve,Te]=l.useState(null),[jt,Tt]=l.useState([]),[Ue,Ge]=l.useState(new Set),[bt,Ke]=l.useState({}),[Nt,kt]=l.useState(new Set),[vt,At]=l.useState(""),[lt,G]=l.useState(null),[ke,fe]=l.useState(""),[he,Mt]=l.useState(!1),[ct,Pt]=l.useState(!1),[Lt,Wt]=l.useState(!1),[Dt,is]=l.useState(!1),[nt,ms]=l.useState("indexed"),[wt,hs]=l.useState(null),Ot=!!(B.query.trim()||B.page.trim()||wt),Yt=wt!==null,Bt=l.useMemo(()=>{if(!wt)return h;const{key:x,dir:D}=wt;return[...h].sort((Z,ce)=>{const ze=x===Ls.CTR?Number.isFinite(Z.ctr)?Z.ctr:0:Z[x],Xe=x===Ls.CTR?Number.isFinite(ce.ctr)?ce.ctr:0:ce[x];return D==="asc"?ze-Xe:Xe-ze})},[h,wt]),et=pn({rows:Bt,pageSize:os}),xs=ae?et.rows:Bt,Gt=pn({rows:(xt??[]).filter(x=>x.path.toLowerCase().includes(vt.trim().toLowerCase())),pageSize:os}),[St,ps]=l.useState([]),[dt,Zt]=l.useState(null),[C,be]=l.useState(1),ve=l.useMemo(()=>{if(St.length<2)return null;const x=St[St.length-1],D=St[St.length-2];return{indexed:x.indexed-D.indexed,notIndexed:x.notIndexed-D.notIndexed}},[St]);l.useEffect(()=>{be(1)},[Y,nt,dt]);const I=l.useMemo(()=>dt?(Y?.reasonGroups??[]).find(x=>x.reason===dt):void 0,[Y,dt]),Q=l.useMemo(()=>Y?nt==="indexed"?Y.indexed:nt==="deindexed"?Y.deindexed:nt==="notIndexed"?dt?I?.urls??[]:(Y.reasonGroups??[]).length===0?Y.notIndexed:[]:[]:[],[Y,nt,dt,I]),me=Math.max(1,Math.ceil(Q.length/bs)),te=Math.min(Math.max(1,C),me),ne=(te-1)*bs,Ee=l.useMemo(()=>Y?.indexed.slice(ne,ne+bs)??[],[Y,ne]),es=l.useMemo(()=>Y?.notIndexed.slice(ne,ne+bs)??[],[Y,ne]),pt=l.useMemo(()=>Y?.deindexed.slice(ne,ne+bs)??[],[Y,ne]),Fs=l.useMemo(()=>(I?.urls??[]).slice(ne,ne+bs),[I,ne]),[N,re]=l.useState(!1),[at,Re]=l.useState(null),[gt,rs]=l.useState(null),[Vt,Xt]=l.useState(null);function ko(x,D){const Z=su(x),ce=sm(Z);ce?(rs(ce),Re(null)):(rs(null),Re(Z.message||D))}const Ft=r.find(x=>x.connectionType==="gsc"),ks=(Ft?.scopes??[]).includes("https://www.googleapis.com/auth/webmasters"),ta=jt.length>0?jt:(xt??[]).map(x=>x.path),si=ta.filter(x=>xt?.some(D=>D.path===x&&D.isSitemapsIndex)).length,Ao=si===1?"Resubmit sitemap index":si>1?"Resubmit sitemap indexes":"Resubmit all sitemaps",Po=h.length>0||j.length>0||g.length>0,sa=Zo(),na=el();async function ni(x,D=!1){if(!x){c([]),A("");return}_e(!0);try{const{sites:Z}=await n.fetchQuery({...xl({client:U,path:{name:t}}),staleTime:D?0:$t});c(Z),A(x.propertyId??Z[0]?.siteUrl??""),rs(null)}catch(Z){c([]),ko(Z,"Failed to load Search Console properties")}finally{_e(!1)}}async function sn(x){E(!0);const D=x??se;try{const Z=Ot?$n:os,ce=Ot?0:D,ze={limit:String(Z)};B.startDate&&(ze.startDate=B.startDate),B.endDate&&(ze.endDate=B.endDate),B.query&&(ze.query=B.query),B.page&&(ze.page=B.page),ce>0&&(ze.offset=String(ce)),T&&T!=="all"&&!B.startDate&&(ze.window=T);const Xe=await n.fetchQuery({...nl({client:U,path:{name:t},query:ze}),staleTime:$t}),tt=Xe.rows;Ot?(X(!1),p(tt),_(tt.length),Ne(!0)):(X(ce+tt.length<Xe.totalMatching),p(tt),_(0),Ne(!1))}catch(Z){p([]),X(!1),_(0),Re(Z instanceof Error?Z.message:"Failed to load GSC performance data")}finally{E(!1)}}async function aa(){try{const x={};B.startDate&&(x.startDate=B.startDate),B.endDate&&(x.endDate=B.endDate),T&&T!=="all"&&!B.startDate&&(x.window=T);const D=await n.fetchQuery({...sl({client:U,path:{name:t},query:x}),staleTime:$t});v(D)}catch{v(null)}}async function kn(x=!1){L(!0);try{const D=Le.trim()||void 0,Z={limit:"20"};D&&(Z.url=D);const[ce,ze]=await Promise.all([n.fetchQuery({...ml({client:U,path:{name:t},query:Z}),staleTime:x?0:$t}),n.fetchQuery({...hl({client:U,path:{name:t}}),staleTime:x?0:$t})]);b(ce),f(ze)}catch(D){b([]),f([]),Re(D instanceof Error?D.message:"Failed to load GSC inspection history")}finally{L(!1)}}async function ai(x=!1){ot(!0);try{const[D,Z]=await Promise.all([n.fetchQuery({...rl({client:U,path:{name:t}}),staleTime:x?0:$t}),n.fetchQuery({...ol({client:U,path:{name:t}}),staleTime:x?0:$t}).catch(()=>[])]);Be(D),ps(Z)}catch(D){Be(null),ps([]),Re(D instanceof Error?D.message:"Failed to load coverage data")}finally{ot(!1)}}async function ii(x){re(!0),Re(null);try{const D=await xi(t,{urls:x}),{succeeded:Z,failed:ce,total:ze}=D.summary;Se({title:"Indexing requested",detail:ce===0?`${Z} URL${Z!==1?"s":""} submitted for indexing.`:`${Z}/${ze} submitted successfully, ${ce} failed.`,tone:ce===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(D){Re(D instanceof Error?D.message:"Failed to request indexing")}finally{re(!1)}}async function Ro(){re(!0),Re(null);try{const x=await xi(t,{urls:[],allUnindexed:!0}),{succeeded:D,failed:Z,total:ce}=x.summary;Se({title:"Indexing requested",detail:Z===0?`${D} unindexed URL${D!==1?"s":""} submitted for indexing.`:`${D}/${ce} submitted successfully, ${Z} failed.`,tone:Z===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(x){Re(x instanceof Error?x.message:"Failed to request indexing")}finally{re(!1)}}async function ia(){Oe(!0),Re(null);try{const x=await oa(t);n.setQueryData(ll({client:U,path:{name:t}}),x),We(x.sitemaps),Te(x.summary),Tt(x.preferredSubmissionUrls),Ge(new Set),Ke({}),x.sitemaps.length===0&&Xt("No sitemaps found in this GSC property. Submit one here to start Google processing it.")}catch(x){Re(x instanceof Error?x.message:"Failed to list sitemaps")}finally{Oe(!1)}}async function Io(x){const D=Ue.has(x);if(Ge(Z=>{const ce=new Set(Z);return D?ce.delete(x):ce.add(x),ce}),!(D||bt[x])){kt(Z=>new Set(Z).add(x));try{const Z=await oa(t,x);Ke(ce=>({...ce,[x]:Z.sitemaps}))}catch(Z){Re(Z instanceof Error?Z.message:"Failed to load sitemap files")}finally{kt(Z=>{const ce=new Set(Z);return ce.delete(x),ce})}}}async function _s(x){if(!ks||x.length===0)return;const D=[...new Set(x)];Pt(!0),Re(null),G({completed:0,total:D.length});let Z=0,ce=0,ze=0,Xe=null;try{for(let yt=0;yt<D.length;yt+=50){const st=D.slice(yt,yt+50);try{const xe=await cl(t,st);Z+=xe.summary.accepted,ce+=xe.summary.failed,ze+=st.length,G({completed:ze,total:D.length})}catch(xe){ze+=st.length;const gs=st.length,nn=D.length-ze,An=xe instanceof Error?xe.message:"The batch request failed",fs=`${Z} accepted, ${ce} failed, ${gs} unconfirmed, ${nn} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;Xe=`Sitemap submission stopped after a batch request failed. ${fs} ${An}`,Re(Xe),Se({title:"Sitemap resubmission partially completed",detail:fs,tone:"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"});return}}const tt=D.length;Se({title:ce===0?"Sitemap submitted to Google":"Some sitemap submissions need attention",detail:ce===0?"Google accepted the sitemap submission/refetch request; indexing is not guaranteed.":`Google accepted ${Z}/${tt} sitemap submissions; ${ce} failed. Indexing is not guaranteed.`,tone:ce===0?"positive":"caution",dedupeKey:`gsc:sitemap-submit:${t}`,dedupeMode:"replace"}),fe("")}catch(tt){Re(tt instanceof Error?tt.message:"Failed to submit sitemap to Google")}finally{Pt(!1),G(null),await ia(),Xe&&Re(Xe)}}async function $o(){Pt(!0);const x=xt??[];try{const D=x.filter(ce=>ce.isSitemapsIndex),Z=[];for(let ce=0;ce<D.length;ce+=4)(await Promise.all(D.slice(ce,ce+4).map(async Xe=>{const tt=bt[Xe.path];if(tt)return tt;const yt=await oa(t,Xe.path);return Ke(st=>({...st,[Xe.path]:yt.sitemaps})),yt.sitemaps}))).forEach((Xe,tt)=>{Z.push(...Xe.length>0?Xe.map(yt=>yt.path):[D[ce+tt].path])});await _s([...x.filter(ce=>!ce.isSitemapsIndex).map(ce=>ce.path),...Z])}catch(D){Re(D instanceof Error?D.message:"Failed to load sitemap files"),Pt(!1)}}async function ri(x){Mt(!0),Re(null);try{await dl(t,"gsc",x),await ft(n,"google"),o(D=>D.map(Z=>Z.connectionType==="gsc"?{...Z,sitemapUrl:x}:Z)),Se({title:"Default sitemap updated",detail:x,tone:"positive",dedupeKey:`gsc:sitemap-default:${t}`,dedupeMode:"replace"})}catch(D){Re(D instanceof Error?D.message:"Failed to set the default sitemap")}finally{Mt(!1)}}async function oi(x){try{await na.mutateAsync({projectName:t,projectLabel:t,opts:x?{sitemapUrl:x}:void 0})}catch{}}async function li(){Qe(!0),Re(null);try{const[x,D]=await Promise.all([Sr().catch(()=>null),n.fetchQuery({...Ba({client:U,path:{name:t}}),staleTime:$t}).catch(()=>[])]);i(!!x?.google?.configured),o(D);const Z=D.find(ce=>ce.connectionType==="gsc");await Promise.all([ni(Z),sn(),aa(),kn(),ai(),Z?.propertyId?ia():Promise.resolve()])}finally{Qe(!1)}}l.useEffect(()=>{li()},[t,s]),l.useEffect(()=>{le(0),ee(null),R(x=>x.startDate||x.endDate?{...x,startDate:"",endDate:""}:x),W(x=>x+1),aa()},[T]);const ci=l.useRef(!1);l.useEffect(()=>{if(!ci.current){ci.current=!0;return}le(0),et.setPage(1),sn(0)},[ie]);function ra(x){const D=z===x?null:x;ee(D),R(Z=>({...Z,startDate:D??"",endDate:D??""})),W(Z=>Z+1)}const di=l.useRef(!1);l.useEffect(()=>{if(!di.current){di.current=!0;return}le(0),sn(0)},[Yt]);async function ui(){if(!a){Re("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}we(!0),Re(null),Xt(null);try{let x=function(xe){if(xe.source!==ce||xe.origin!==ze||!xe.data||typeof xe.data!="object")return;const gs=xe.data;gs.type!==am||gs.connectionType!=="gsc"||st(!0)};const{authUrl:D,redirectUri:Z}=await il(t,"gsc");if(!D.startsWith("https://accounts.google.com/")){Re("Unexpected OAuth redirect URL. Please try again.");return}const ce=window.open(D,"_blank","width=600,height=700");if(!ce){window.location.assign(D);return}const ze=Z?new URL(Z).origin:window.location.origin;let Xe=!1,tt=null;const yt=()=>{tt!==null&&window.clearInterval(tt),window.removeEventListener("message",x)},st=async xe=>{if(!Xe){Xe=!0,yt(),Xt(xe?"Google connected. Refreshing access…":"Refreshing Google connection…");try{await ft(n,"google"),await li()}finally{Xt(null)}}};window.addEventListener("message",x),Xt("Finish the Google consent flow in the popup. This page will refresh automatically."),tt=window.setInterval(()=>{ce.closed&&st(!1)},1e3)}catch(x){Re(x instanceof Error?x.message:"Failed to start OAuth flow")}finally{we(!1)}}async function To(){Re(null),Xt(null);try{await al(t,"gsc"),await ft(n,"google"),o(x=>x.filter(D=>D.connectionType!=="gsc")),c([]),A("")}catch(x){Re(x instanceof Error?x.message:"Failed to disconnect")}}async function Mo(){if(q){$e(!0),Re(null);try{await pl(t,"gsc",q),await ft(n,"google"),o(x=>x.map(D=>D.connectionType==="gsc"?{...D,propertyId:q}:D)),Se({title:"GSC property updated",detail:`${t} is now linked to ${q}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(x){Re(x instanceof Error?x.message:"Failed to save GSC property")}finally{$e(!1)}}}async function Lo(){Re(null),Xt(null);try{await sa.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(S,10)||void 0,full:K||void 0}}),await ft(n,"gsc")}catch{}}async function mi(){if(d.trim()){qe(!0),Re(null),Xt(null);try{const x=await ul(t,d.trim());await ft(n,"gsc"),O(x),y(""),await kn()}catch(x){Re(x instanceof Error?x.message:"Failed to inspect URL")}finally{qe(!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"})]})}),gt&&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:gt.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:gt.message}),(Ts(gt.enableUrl)||Ts(gt.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[Ts(gt.enableUrl)&&e.jsx("a",{href:Ts(gt.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 ↗"}),Ts(gt.indexingApiUrl)&&e.jsx("a",{href:Ts(gt.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:()=>rs(null),children:"×"})]})}),at&&e.jsxs("div",{className:"mb-3 rounded-lg border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:[at,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>Re(null),children:"×"})]}),Vt&&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:[Vt,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>Xt(null),children:"×"})]}),Pe?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[Ft?e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 px-1 text-xs text-muted",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-positive-500"}),e.jsx("span",{className:"text-neutral",children:"Authorized"})]}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsx("code",{className:"text-secondary",children:Ft.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Coverage measured"," ",Y?.lastInspectedAt?qt(Y.lastInspectedAt):"never"]}),e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:Me(To),children:"Disconnect"})]}):e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(oe,{tone:a?"caution":"negative",children:a?"Ready to connect":"App credentials missing"})]}),e.jsxs("div",{className:"mt-3 rounded-lg border border-default bg-surface px-4 py-5",children:[e.jsx("p",{className:"text-sm text-neutral",children:a?"Generate a Google OAuth link for this project and have the client sign in with a Google account that already has access to the correct Search Console property.":"Set Google OAuth client credentials first. Once configured, you can generate a consent link for this project domain."}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[a?e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:ue,onClick:Me(ui),children:ue?"Opening…":"Connect Google Search Console"}):e.jsx(P,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(as,{to:"/settings",children:"Open Settings"})}),!a&&e.jsx("p",{className:"text-xs text-muted",children:"The same Google OAuth app credentials are shared across all projects."})]})]})]}),(Ft||Po)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs(pe,{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(Je,{text:`Tile percentages compare the trailing half of the selected window with the prior equal-length half. 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 ${$n.toLocaleString()} matching rows while the table shows ${os} per page.`})]}),u?.window?.startDate&&u.window.endDate&&e.jsxs("p",{className:"text-xs text-muted",children:[u.window.startDate," to ",u.window.endDate,(u.window.daysSinceLatestData??0)>0&&` · latest data ${u.window.daysSinceLatestData} day${u.window.daysSinceLatestData===1?"":"s"} ago`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(to,{windows:nm,value:T,onChange:x=>{F(x),le(0),et.setPage(1)},label:"Search Console time period",formatOption:x=>x==="all"?"All":x}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:Ce,onClick:()=>{le(0),et.setPage(1),sn(0),aa()},children:Ce?"Loading…":"Apply filters"})]})]}),u&&u.daily.length>0&&(()=>{const{totals:x,daily:D,trends:Z,periodComparison:ce}=u,Xe=Ri.filter(xe=>$.includes(xe.key)).map(xe=>({dataKey:xe.key,label:xe.label,color:xe.color,axisId:xe.key,inverted:xe.inverted,formatValue:xe.format,trend:ye?Z?.[xe.key]??null:null})),tt=xe=>x[xe]??null,yt=new Map(D.map(xe=>[xe.date,xe])),st=D.length===0?[]:lu(D[0].date,D[D.length-1].date).map(xe=>yt.get(xe)??{date:xe});return e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:Ri.map(xe=>{const gs=$.includes(xe.key),nn=tt(xe.key),An=nn===null;return e.jsxs("button",{type:"button","aria-pressed":gs,disabled:An,className:`rounded-md border px-3 py-2 text-left transition-colors ${gs?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${An?"cursor-not-allowed opacity-50":""}`,onClick:()=>{H(fs=>fs.includes(xe.key)?fs.length===1?fs:fs.filter(Do=>Do!==xe.key):[...fs,xe.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:gs?xe.color:"transparent",border:`1px solid ${xe.color}`}}),e.jsx("span",{className:"text-xs text-secondary",children:xe.label})]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:nn===null?"—":xe.format(nn)}),e.jsx("span",{className:"block text-[11px] tabular-nums text-muted",children:rm(ce,xe.key,xe.inverted)})]},xe.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:ye,onChange:xe=>ge(xe.target.checked)}),"Trend line"]})}),e.jsx("div",{className:"mt-1",children:e.jsx(Er,{data:st,xKey:"date",series:Xe,xTickFormatter:gn,labelFormatter:Ut,onSelectX:ra,selectedX:z})}),e.jsx("div",{role:"group","aria-label":"Filter the table to a single day",children:D.map(xe=>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":z===xe.date,onClick:()=>ra(xe.date),children:[Ut(xe.date),": ",xe.clicks," clicks, ",xe.impressions," impressions"]},xe.date))}),z&&e.jsxs("div",{className:"mt-1 flex items-center gap-2 text-xs",children:[e.jsxs("span",{className:"text-secondary",children:["Table showing ",Ut(z)]}),e.jsxs("button",{type:"button",className:"text-link hover:underline",onClick:()=>ra(z),children:["Show all ",x.days," days"]})]}),x.position!==null&&(x.positionDays??x.days)<x.days&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Average position covers ",x.positionDays," of ",x.days," days. The rest have no property-level position recorded."]}),(x.position===null||x.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:B.startDate,onChange:x=>R(D=>({...D,startDate:x.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:B.endDate,onChange:x=>R(D=>({...D,endDate:x.target.value}))}),e.jsx(Hs,{value:B.query,onChange:x=>R(D=>({...D,query:x})),label:"Filter search queries",placeholder:"Contains query…"}),e.jsx(Hs,{value:B.page,onChange:x=>R(D=>({...D,page:x})),label:"Filter page URLs",placeholder:"Contains page URL…"})]}),h.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Date"}),e.jsx("th",{className:"text-left",children:"Query"}),e.jsx("th",{className:"text-left",children:"Page"}),Object.values(Ls).map(x=>e.jsx("th",{className:"text-right","aria-sort":wt?.key===x?wt.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:()=>{et.setPage(1),hs(D=>D?.key===x?D.dir==="desc"?{key:x,dir:"asc"}:null:{key:x,dir:"desc"})},children:[tl[x],wt?.key===x?wt.dir==="desc"?" ↓":" ↑":""]})},x))]})}),e.jsx("tbody",{children:xs.map((x,D)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:x.date}),e.jsx("td",{className:"max-w-xs truncate text-strong",children:x.query}),e.jsx("td",{className:"max-w-xs text-secondary",children:e.jsx(Un,{value:x.page})}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:x.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:x.impressions.toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[(Number.isFinite(x.ctr)?x.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:x.position.toFixed(1)})]},`${x.date}:${x.query}:${x.page}:${D}`))})]})}),e.jsx(Es,{page:ae?et.page:Math.floor(se/os)+1,pageSize:os,visibleRows:xs.length,totalRows:ae?Ae:void 0,hasNextPage:ae?void 0:de,disabled:Ce,itemLabel:ae?"matches":"rows",onPageChange:x=>{if(ae){et.setPage(x);return}const D=(x-1)*os;le(D),sn(D)}}),ae&&Ae>=$n?e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Results are capped at ",$n.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(pe,{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(Je,{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:[Y&&Y.notIndexed.length>0&&e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:N,onClick:()=>{Ro()},children:N?"Requesting…":`Request indexing (${Y.notIndexed.length})`}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:mt,onClick:()=>{ai(!0)},children:mt?"Loading…":"Reload saved coverage"})]})]}),Y&&Y.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const x=Y.summary.indexed+Y.summary.notIndexed,D=x>0?Y.summary.indexed/x:0,Z=x>0?Y.summary.notIndexed/x:0,ce=54,ze=2*Math.PI*ce,Xe=ze*(1-D),tt=ze*Z,yt=ze*D;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:ce,fill:"none",stroke:Ht.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:ce,fill:"none",stroke:qs.positiveDeep,strokeWidth:"14",strokeDasharray:ze,strokeDashoffset:Xe,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),Y.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:ce,fill:"none",stroke:Ht.textFaint,strokeWidth:"14",strokeDasharray:`${tt} ${ze-tt}`,strokeDashoffset:-yt,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:[(D*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:Y.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:Y.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:["Not indexed",(Y.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-faint",children:["· ",(Y.reasonGroups??[]).length," ",(Y.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),Y.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:Y.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(x=>{const D=x==="indexed"?Y.indexed.length:x==="notIndexed"?Y.notIndexed.length:Y.deindexed.length,Z=x==="indexed"?"Indexed":x==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",role:"tab","aria-selected":nt===x,className:`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${nt===x?"border-accent text-heading":"border-transparent text-secondary hover:border-mono-600 hover:text-strong"}`,onClick:()=>{ms(x),Zt(null)},children:[Z," (",D,")"]},x)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[nt==="indexed"&&Y.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:Ee.map(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:x.url}),e.jsx("td",{className:"text-secondary",children:x.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:x.crawlTime?x.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:x.isMobileFriendly===!0?"Yes":x.isMobileFriendly===!1?"No":"—"})]},x.id))})]}),nt==="notIndexed"&&!dt&&(Y.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:(Y.reasonGroups??[]).map(x=>e.jsxs("tr",{className:"cursor-pointer hover:bg-surface-inset-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>Zt(x.reason),onKeyDown:D=>{(D.key==="Enter"||D.key===" ")&&(D.preventDefault(),Zt(x.reason))},tabIndex:0,role:"button","aria-label":`View ${x.reason} pages`,children:[e.jsx("td",{className:"text-strong",children:x.reason}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:x.count})]},x.reason))})]}),nt==="notIndexed"&&!dt&&(Y.reasonGroups??[]).length===0&&Y.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:es.map(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:x.url}),e.jsx("td",{className:"text-secondary",children:x.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:x.coverageState??"Unknown"})]},x.id))})]}),nt==="notIndexed"&&dt&&(()=>{const x=(Y.reasonGroups??[]).find(D=>D.reason===dt);return x?e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsxs("button",{type:"button",className:"text-xs text-secondary hover:text-strong transition-colors",onClick:()=>Zt(null),children:["←"," Back to reasons"]})}),e.jsxs("div",{className:"mb-3 flex items-center justify-between rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:x.reason}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[x.count," affected page",x.count!==1?"s":""]})]}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:N,onClick:()=>{ii(x.urls.map(D=>D.url))},children:N?"Requesting…":`Request indexing (${x.count})`})]}),e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Last Crawl"}),e.jsx("th",{className:"w-8"})]})}),e.jsx("tbody",{children:Fs.map(D=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:D.url}),e.jsx("td",{className:"text-secondary",children:D.crawlTime?D.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-strong transition-colors",disabled:N,onClick:()=>{ii([D.url])},title:"Request indexing",children:"Index"})})]},D.id))})]})]}):null})(),nt==="deindexed"&&Y.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:pt.map((x,D)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:x.url}),e.jsx("td",{className:"text-secondary",children:x.previousState}),e.jsx("td",{className:"text-secondary",children:x.currentState}),e.jsx("td",{className:"text-secondary",children:x.transitionDate.split("T")[0]})]},`${x.url}-${D}`))})]}),(nt==="indexed"&&Y.indexed.length===0||nt==="notIndexed"&&!dt&&Y.notIndexed.length===0||nt==="deindexed"&&Y.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),e.jsx(Es,{page:te,pageSize:bs,visibleRows:Math.min(bs,Q.length-ne),totalRows:Q.length,onPageChange:be,itemLabel:"URLs"})]}),e.jsxs("div",{className:"mt-4 border-t border-default pt-3",children:[e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between text-left text-xs text-secondary hover:text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400","aria-expanded":Dt,onClick:()=>is(x=>!x),children:[e.jsx("span",{children:"Coverage history"}),e.jsx("span",{children:Dt?"Hide snapshots":St.length>0?`View ${St.length} snapshots`:"View history"})]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["Current: ",Y.summary.indexed.toLocaleString()," indexed, ",Y.summary.notIndexed.toLocaleString()," not indexed.",ve&&e.jsxs(e.Fragment,{children:[" Since the last snapshot: ",ve.indexed>=0?"+":"",ve.indexed.toLocaleString()," indexed, ",ve.notIndexed>=0?"+":"",ve.notIndexed.toLocaleString()," not indexed."]})]}),Dt&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:St.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:St.map(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:x.date}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:x.indexed.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:x.notIndexed.toLocaleString()})]},x.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:mt?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),e.jsxs(pe,{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(Je,{text:"Submitting asks Google to refetch these sitemaps. Indexing is not guaranteed."})]})]}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:De||!Ft?.propertyId,onClick:()=>{ia()},children:De?"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:ke,onChange:x=>fe(x.target.value),onKeyDown:x=>x.key==="Enter"&&void _s([ke.trim()])}),e.jsx(P,{type:"button",size:"sm",disabled:!ks||ct||!ke.trim(),onClick:()=>{_s([ke.trim()])},children:ct?"Submitting…":"Submit sitemap to Google"})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:!ks||ct||ta.length===0,onClick:()=>{_s(ta)},children:ct?"Resubmitting…":Ao}),e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:!ks||ct||!xt?.length,onClick:()=>{$o()},children:"Resubmit all files"}),Ve&&e.jsxs("span",{className:"text-xs text-muted",children:["Top level: ",Ve.indexes," index",Ve.indexes===1?"":"es",", ",Ve.files," file",Ve.files===1?"":"s"]}),lt&&e.jsxs("span",{className:"text-xs text-secondary",children:["Submitting ",lt.completed,"/",lt.total]})]}),!ks&&Ft&&e.jsxs("div",{className:"mt-2 flex items-center gap-2 text-xs text-caution",children:[e.jsx("span",{children:"Reconnect to let Canonry submit sitemaps. Your current Canonry OAuth grant is read-only."}),e.jsx("button",{type:"button",className:"text-secondary underline hover:text-strong",onClick:Me(ui),children:"Reconnect"})]}),xt&&e.jsx("div",{className:"mt-3 overflow-x-auto",children:xt.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Hs,{value:vt,onChange:x=>{At(x),Gt.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:Gt.rows.flatMap(x=>{const D=Ii(x),Z=$i(x),ce=Ti(x),ze=bt[x.path]??[],Xe=Ue.has(x.path),tt=e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs text-strong",children:e.jsx(Un,{value:x.path})}),e.jsx("td",{className:"text-secondary",children:x.isSitemapsIndex?e.jsx("button",{type:"button",className:"text-secondary hover:text-strong","aria-expanded":Xe,"aria-label":`${Xe?"Collapse":"Expand"} files in ${x.path}`,onClick:()=>{Io(x.path)},children:Nt.has(x.path)?"Loading…":`${Xe?"▾":"▸"} Index${bt[x.path]?` (${ze.length})`:""}`}):"Sitemap"}),e.jsx("td",{className:"text-secondary",children:ce}),e.jsx("td",{className:"text-secondary",children:x.lastSubmitted?x.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:x.lastDownloaded?x.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:D.toLocaleString()}),e.jsx("td",{className:"max-w-48 text-secondary",children:Z||"—"}),e.jsx("td",{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:!ks||ct,onClick:()=>{_s([x.path])},children:x.lastSubmitted?"Resubmit to Google":"Submit to Google"}),Ft?.sitemapUrl===x.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:he,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{ri(x.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:na.isPending,onClick:()=>{oi(x.path)},children:"Inspect URLs"})]})})]},x.path),yt=x.isSitemapsIndex&&Xe?ze.map(st=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs pl-6 text-secondary",children:e.jsx(Un,{value:st.path})}),e.jsx("td",{className:"text-secondary",children:"File"}),e.jsx("td",{className:"text-secondary",children:Ti(st)}),e.jsx("td",{className:"text-secondary",children:st.lastSubmitted?st.lastSubmitted.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:st.lastDownloaded?st.lastDownloaded.split("T")[0]:"—"}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:Ii(st).toLocaleString()}),e.jsx("td",{className:"text-secondary",children:$i(st)||"—"}),e.jsx("td",{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:!ks||ct,onClick:()=>{_s([st.path])},children:"Resubmit"}),Ft?.sitemapUrl===st.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:he,title:"Use this sitemap by default for Canonry GSC operations.",onClick:()=>{ri(st.path)},children:"Set as default"}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong",disabled:na.isPending,onClick:()=>{oi(st.path)},children:"Inspect URLs"})]})})]},`${x.path}:${st.path}`)):[];return[tt,...yt]})})]}),e.jsx(Es,{page:Gt.page,pageSize:os,visibleRows:Gt.rows.length,totalRows:Gt.totalRows,onPageChange:Gt.setPage,itemLabel:"sitemaps"})]}):e.jsx("p",{className:"text-sm text-muted",children:"No sitemaps found for this property."})})]}),e.jsxs(pe,{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:d,onChange:x=>y(x.target.value),onKeyDown:x=>x.key==="Enter"&&void mi()}),e.jsx(P,{type:"button",size:"sm",disabled:je||!Ft?.propertyId||!d.trim(),onClick:Me(mi),children:je?"Inspecting…":"Inspect URL"})]}),k&&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:k.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:k.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:hi(k.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:qt(k.crawlTime)})]})]})]}),e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Inspection log"})]}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:M,onClick:()=>{kn(!0)},children:M?"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:Le,onChange:x=>Fe(x.target.value)}),e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:M,onClick:()=>{kn(!0)},children:"Apply filter"})]}),j.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:j.map(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:x.url}),e.jsx("td",{className:"text-neutral",children:x.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:x.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:x.coverageState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:hi(x.isMobileFriendly??null)}),e.jsx("td",{className:"text-secondary",children:qt(x.inspectedAt)})]},x.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No inspection history yet."})]}),e.jsxs(pe,{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"})]})}),g.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:g.map(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:x.url}),e.jsx("td",{className:"text-secondary",children:x.previousState??"Unknown"}),e.jsx("td",{className:"text-neutral",children:x.currentState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:qt(x.transitionDate)})]},`${x.url}:${x.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No deindexed transitions recorded."})]})]}),Ft&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-default pt-3",children:e.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 text-left",onClick:()=>Wt(x=>!x),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 ${Lt?"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"})]})}),Lt&&e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(pe,{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(Je,{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:q,disabled:Ze||m.length===0,onChange:x=>A(x.target.value),children:m.length===0?e.jsx("option",{value:"",children:Ze?"Loading properties…":"No properties available"}):m.map(x=>e.jsxs("option",{value:x.siteUrl,children:[x.siteUrl," · ",x.permissionLevel]},x.siteUrl))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:Ze,onClick:()=>{ni(Ft,!0)},children:Ze?"Refreshing…":"Refresh properties"}),e.jsx(P,{type:"button",size:"sm",disabled:!q||He,onClick:Me(Mo),children:He?"Saving…":"Save property"})]})]})]}),e.jsxs(pe,{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:x=>V(x.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:K,onChange:x=>w(x.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(P,{type:"button",size:"sm",disabled:sa.isPending||!Ft.propertyId,onClick:Me(Lo),children:sa.isPending?"Queueing…":"Queue sync"}),!Ft.propertyId&&e.jsx("p",{className:"text-xs text-caution-400",children:"Select a Search Console property before queueing a sync."})]})]})]})})]})]})]})}const lm=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function cm({projectName:t,projectId:s}){const n=Cs(),[a,i]=l.useState(null),[r,o]=l.useState(null),[m,c]=l.useState(!1),h=Ie(Ba({client:U,path:{name:t}})),p=h.data?.find(_=>_.connectionType==="gbp"),u=!!p,v=a?{locationName:a}:void 0,j=Ie({...gl({client:U,path:{name:t}}),enabled:u}),b=Ie({...fl({client:U,path:{name:t},query:v}),enabled:u}),g=Ie({...bl({client:U,path:{name:t},query:v}),enabled:u}),f=Ie({...vl({client:U,path:{name:t},query:v}),enabled:u}),k=Ie({...yl({client:U,path:{name:t},query:v}),enabled:u}),O=Ie({...jl({client:U,path:{name:t},query:v}),enabled:u}),q=Ie({queryKey:["gbp-section-insights",t],queryFn:()=>Nl(t),enabled:u});function A(){ft(n,"gbp")}const d=Et({...wl(),onSuccess:_=>{Cr({id:_.runId,projectId:s,kind:Os["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"})}}),y=l.useSyncExternalStore(kr,Kn,Kn),S=Object.values(y.runs).some(_=>_.kind===Os["gbp-sync"]&&_.projectId===s),V=d.isPending||S,K=Et({...Sl(),onSuccess:()=>A()});if(l.useEffect(()=>{if(!a||!j.data)return;const _=j.data.locations.filter(ae=>ae.selected);(_.length<=1||!_.some(ae=>ae.locationName===a))&&i(null)},[a,j.data]),l.useEffect(()=>{if(!r||!j.data)return;(a?[a]:j.data.locations.filter(ae=>ae.selected).map(ae=>ae.locationName)).includes(r)||o(null)},[r,j.data,a]),h.isLoading)return null;if(!p){const _=[{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(pe,{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:_.map((ae,Ne)=>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:Ne+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 w=b.data,T=j.data?.locations??[],F=T.filter(_=>_.selected),$=g.data?.keywords??[],H=f.data?.lodging??[],ye=k.data?.placeActions??[],ge=O.data?.places??[],z=T.length>0?T[0].accountName:p.domain,ee=a?T.find(_=>_.locationName===a)?.displayName??null:null,ie=a?T.filter(_=>_.locationName===a):F,W=new Set(ie.map(_=>_.locationName)),B=H.filter(_=>W.has(_.locationName)),R=ye.filter(_=>W.has(_.locationName)),se=ge.filter(_=>W.has(_.locationName)),le=new Set(F.map(_=>_.locationName)),de=a?$:$.filter(_=>le.has(_.locationName)),X=!a&&F.length>1,Ae=(q.data??[]).filter(_=>!_.dismissed&&lm.has(_.type)&&(!ee||_.query===ee||_.query===a||_.title.startsWith(ee)));return e.jsx("section",{className:"page-section-divider",children:e.jsxs(pe,{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(Je,{text:"How AI answer engines and Maps surface this business: performance, search terms, and how your public listing compares to the profile you control."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oe,{tone:"positive",children:"Connected"}),!J()&&e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:V,onClick:()=>d.mutate({client:U,path:{name:t},body:{}}),children:V?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-muted",children:[z?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-secondary",children:z})," · "]}):null,j.data?`${j.data.totalSelected} of ${j.data.totalDiscovered} locations tracked`:"Loading locations…"]}),F.length>1&&e.jsxs("div",{className:"mb-5 max-w-xs",children:[e.jsx("label",{htmlFor:"local-presence-location",className:"mb-1 block text-sm font-medium text-secondary",children:"Location"}),e.jsxs("select",{id:"local-presence-location",value:a??"",onChange:_=>i(_.target.value||null),className:"w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-strong focus:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",children:[e.jsx("option",{value:"",children:"All locations"}),F.map(_=>e.jsx("option",{value:_.locationName,children:_.displayName},_.id))]})]}),F.length===0?e.jsxs("p",{className:"text-sm text-muted",children:["No locations are tracked yet. Open ",e.jsx("span",{className:"font-medium text-neutral",children:"Manage locations"})," below to track the one(s) for this business."]}):e.jsxs(e.Fragment,{children:[Ae.length>0&&e.jsxs("div",{className:"mb-6 grid gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Needs attention"}),Ae.map(_=>e.jsx("div",{className:["insight-card",Nm(_.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:[_.title,_.recommendation?.reason&&e.jsx(Je,{text:_.recommendation.reason})]})},_.id))]}),w&&e.jsx(km,{performance:w.performance,freshness:w.freshness,timeseries:w.timeseries}),w?.profileCompleteness&&e.jsx(dm,{summary:w.profileCompleteness}),ie.length>0&&e.jsx(um,{locations:ie,lodging:B,places:se,placeActions:R,expandedLocation:r,onToggleExpanded:_=>{o(ae=>ae===_?null:_)}}),e.jsxs("div",{className:"mb-2",children:[e.jsxs("div",{className:"section-head section-head-inline mb-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search terms"}),g.data&&g.data.total>0&&e.jsxs("span",{className:"text-[11px] text-faint",children:[g.data.thresholdedPct,"% privacy-thresholded"]})]}),de.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:de.slice(0,25).map(_=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-neutral",children:_.keyword}),X&&e.jsx("td",{className:"text-muted",children:T.find(ae=>ae.locationName===_.locationName)?.displayName??_.locationName}),e.jsx("td",{className:"text-right font-mono text-strong",children:_.valueCount!==null?_.valueCount.toLocaleString():e.jsxs("span",{className:"text-muted",title:"Privacy floor — Google withheld the exact count",children:["<",_.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-faint",children:[_.periodStart,"–",_.periodEnd]})]},`${_.locationName}:${_.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(_=>!_),"aria-expanded":m,children:[e.jsx("span",{"aria-hidden":"true",children:m?"▾":"▸"})," Manage locations (",T.length,")"]}),m&&e.jsx("div",{className:"mt-3",children:T.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"}),!J()&&e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:T.map(_=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:_.displayName}),e.jsx("td",{className:"text-muted",children:_.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(oe,{tone:_.selected?"positive":"neutral",children:_.selected?"Tracked":"Not tracked"})}),!J()&&e.jsx("td",{className:"text-right",children:e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:K.isPending,onClick:()=>K.mutate({client:U,path:{name:t,locationName:_.locationName},body:{selected:!_.selected}}),children:_.selected?"Untrack":"Track"})})]},_.id))})]})})]})]})})}function dm({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:on(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:on(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:on(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:on(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:on(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(Je,{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 ${jm(a.tone)}`,children:a.value}),a.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-faint",children:a.detail})]},a.label))})]})}function um({locations:t,lodging:s,places:n,placeActions:a,expandedLocation:i,onToggleExpanded:r}){const o=new Map(s.map(h=>[h.locationName,h])),m=new Map(n.map(h=>[h.locationName,h])),c=new Map;for(const h of a){const p=c.get(h.locationName)??[];p.push(h),c.set(h.locationName,p)}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(Je,{text:J()?"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest sync, not that every Google product lacks the information.":"Each column names the Google surface it came from. Missing or empty means that surface did not return a value in the latest Canonry sync, not that every Google product lacks the information."})]}),e.jsxs("span",{className:"text-[11px] text-faint",children:[t.length," location",t.length===1?"":"s"]})]}),e.jsx("div",{className:"data-table-wrapper",children:e.jsxs("table",{className:"data-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"min-w-[14rem]",children:"Location"}),e.jsx("th",{className:"min-w-[15rem]",children:"Owner profile"}),e.jsx("th",{className:"min-w-[11rem]",children:"Hotel data"}),e.jsx("th",{className:"min-w-[11rem]",children:"Public Maps"}),e.jsx("th",{className:"min-w-[10rem]",children:"CTAs"}),e.jsx("th",{className:"text-right",children:"Detail"})]})}),e.jsx("tbody",{children:t.map(h=>{const p=o.get(h.locationName)??null,u=m.get(h.locationName)??null,v=c.get(h.locationName)??[],j=i===h.locationName;return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-strong",children:h.displayName}),e.jsx("p",{className:"mt-1 text-xs text-faint",children:h.primaryCategoryDisplayName??"Primary category not returned"}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[e.jsx(oe,{tone:h.selected?"positive":"neutral",children:h.selected?"Tracked":"Not tracked"}),h.openStatus&&h.openStatus!=="OPEN"&&e.jsx(oe,{tone:h.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:so(h.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(hm,{location:h})}),e.jsx("td",{children:e.jsx(xm,{lodging:p})}),e.jsx("td",{children:e.jsx(gm,{place:u,mapsUri:h.mapsUri})}),e.jsx("td",{children:e.jsx(bm,{actions:v})}),e.jsx("td",{className:"text-right",children:e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>r(h.locationName),children:j?"Hide":"Details"})})]}),j&&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(ym,{location:h,lodging:p,place:u,placeActions:v})})})]},h.id)})})]})})]})}function mm(t){return[{label:"Description",tone:Ms(t.description)?"positive":"neutral",value:Ms(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:Ms(t.primaryPhone)?"positive":"neutral",value:Ms(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:Ms(t.websiteUri)?"positive":"neutral",value:Ms(t.websiteUri)?"set":"not returned"},{label:"Secondary",tone:t.additionalCategories.length>0?"positive":"neutral",value:t.additionalCategories.length>0?String(t.additionalCategories.length):"not returned"},{label:"Service area",tone:t.serviceArea?"positive":"neutral",value:t.serviceArea?"set":"not returned"}]}function hm({location:t}){const s=mm(t);return e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>e.jsxs(oe,{tone:n.tone,children:[n.label," ",n.value]},n.label))})}function xm({lodging:t}){return e.jsx(Ka,{...pm(t)})}function pm(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 gm({place:t,mapsUri:s}){return e.jsx(Ka,{...fm(t,s)})}function fm(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 bm({actions:t}){return e.jsx(Ka,{...vm(t)})}function vm(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 Ka({tone:t,label:s,detail:n}){return e.jsxs("div",{children:[e.jsx(oe,{tone:t,children:s}),e.jsx("p",{className:"mt-1.5 text-xs leading-5 text-faint",children:n})]})}function ym({location:t,lodging:s,place:n,placeActions:a}){const i=s?Sm(s.attributes):[];return e.jsxs("div",{className:"grid gap-5 text-xs lg:grid-cols-3",children:[e.jsxs(ha,{title:"Owner profile · Business Information",children:[e.jsx(Rt,{label:"Primary category",value:t.primaryCategoryDisplayName??"Not returned"}),e.jsx(Rt,{label:"Secondary categories",value:t.additionalCategories.length>0?t.additionalCategories.join(", "):"Not returned"}),e.jsx(Rt,{label:"Description",value:Ms(t.description)?t.description:"Not returned"}),e.jsx(Rt,{label:"Hours",value:t.regularHours?"Returned by Google":"Not returned"}),e.jsx(Rt,{label:"Service area",value:t.serviceArea?"Returned by Google":"Not returned"}),e.jsx(Rt,{label:"Phone",value:t.primaryPhone??"Not returned"}),e.jsx(Rt,{label:"Website",value:t.websiteUri??"Not returned"}),e.jsx(Rt,{label:"Open status",value:so(t.openStatus)}),e.jsx(Rt,{label:"Opening date",value:t.openingDate??"Not returned"})]}),e.jsx(ha,{title:"Hotel data · Lodging API",children:s?e.jsxs(e.Fragment,{children:[e.jsx(Rt,{label:"Last checked",value:Mi(s.syncedAt)}),e.jsx(Rt,{label:"Groups returned",value:String(s.populatedGroupCount)}),e.jsx(Rt,{label:"Populated groups",value:i.length>0?i.join(", "):"None returned"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Lodging API snapshot was stored for this location."})}),e.jsxs(ha,{title:"Public listing + CTAs",children:[n?e.jsxs(e.Fragment,{children:[e.jsx(Rt,{label:"Places tier",value:n.tier}),e.jsx(Rt,{label:"Last checked",value:Mi(n.syncedAt)}),e.jsx(Rt,{label:"Public signals",value:n.amenities.length>0?n.amenities.join(", "):"No supported signals detected"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Places Details snapshot was stored for this location."}),t.mapsUri&&e.jsx("a",{href:t.mapsUri,target:"_blank",rel:"noopener noreferrer",className:"inline-block text-muted hover:text-neutral",children:"View on Google Maps →"}),e.jsx("div",{className:"mt-3 border-t border-default pt-3",children:a.length===0?e.jsx("p",{className:"leading-5 text-muted",children:"No placeActionLinks returned."}):e.jsx("div",{className:"grid gap-2",children:a.map(r=>e.jsxs("div",{className:"grid gap-0.5",children:[e.jsxs("span",{className:"font-medium text-neutral",children:[Yn(r.placeActionType),r.isPreferred?" · preferred":""]}),e.jsxs("span",{className:"text-faint",children:[Yn(r.providerType),r.uri?` · ${wm(r.uri)}`:""]})]},r.placeActionLinkName))})})]})]})}function ha({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 Rt({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 on(t,s,n){return t===s?"positive":t===0?n:"caution"}function jm(t){switch(t){case"positive":return"text-positive";case"caution":return"text-caution";case"negative":return"text-negative";case"neutral":return"text-neutral"}}function Nm(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function Ms(t){return typeof t=="string"&&t.trim().length>0}function so(t){return t?Yn(t):"Not returned"}function Yn(t){return t?t.toLowerCase().split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"Unknown"}function wm(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function Mi(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Sm(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&Cm(n)).map(([s])=>Yn(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function Cm(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function km({performance:t,freshness:s,timeseries:n}){const a=t.totals,i=Cl.filter(b=>(a[b]??0)>0),r=kl.filter(b=>(a[b]??0)>0),o=Object.keys(a).filter(b=>(a[b]??0)>0&&Al(b)==="other").sort((b,g)=>(a[g]??0)-(a[b]??0)),m=Object.keys(a).filter(b=>(a[b]??0)===0).sort(),c=n.map(b=>{const g={date:b.date};for(const[f,k]of Object.entries(b.metrics))g[f]=k;return g}),h=n.find(b=>b.pending)?.date,p=n.length>0?n[n.length-1].date:void 0,u=c.length>0,v=s.dataThroughDate?`Data through ${Ut(s.dataThroughDate)}${s.pendingDays>0?` · ${s.pendingDays}d pending`:""}`:null,j=[...i,...o];return e.jsxs("div",{className:"mb-6 grid gap-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Profile actions · daily"}),v&&e.jsx("span",{className:"text-[11px] text-muted",children:v})]}),!u||i.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No profile action activity yet — run a sync."}):e.jsxs(e.Fragment,{children:[e.jsx(Li,{data:c,metrics:i,kind:"line",firstPending:h,lastDate:p}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-x-5 gap-y-1",children:j.map(b=>e.jsxs("span",{className:"text-sm text-secondary",children:[zn(b)," ",e.jsx("span",{className:"font-mono text-heading",children:(a[b]??0).toLocaleString()})]},b))})]})]}),u&&r.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(Li,{data:c,metrics:r,kind:"area",firstPending:h,lastDate:p})]}),m.length>0&&e.jsxs("p",{className:"text-xs text-faint",children:["Not active: ",m.map(b=>zn(b)).join(", ")]})]})}function Li({data:t,metrics:s,kind:n,firstPending:a,lastDate:i}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(fn,{width:"100%",height:"100%",children:e.jsxs(bn,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Fr,{stroke:qr,vertical:!1}),e.jsx(vn,{dataKey:"date",tick:ns,tickLine:!1,axisLine:{stroke:Gs},tickFormatter:gn,minTickGap:24}),e.jsx(yn,{tick:ns,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(jn,{...Ws,labelFormatter:Ut,formatter:(r,o)=>[typeof r=="number"?r.toLocaleString():String(r??0),zn(String(o??""))]}),e.jsx(Gr,{wrapperStyle:{fontSize:11,color:Ht.text},formatter:r=>zn(r)}),a&&i&&e.jsx(nu,{x1:a,x2:i,fill:Ht.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:Ht.textDim,fontSize:10}}),s.map((r,o)=>n==="line"?e.jsx(_r,{type:"monotone",dataKey:r,stroke:rt[o%rt.length],strokeWidth:2,dot:!1,isAnimationActive:!1},r):e.jsx(zs,{type:"monotone",dataKey:r,stackId:"reach",stroke:rt[o%rt.length],fill:rt[o%rt.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},r))]})})})}function Am(t){return Or(us(String(t)))}function Pm(t){return Ss(us(String(t)))}function xa({children:t,label:s="More info",placement:n="top",className:a}){const i=l.useId(),[r,o]=l.useState(!1);return e.jsxs("span",{className:`relative inline-flex ${a??""}`,children:[e.jsx("button",{type:"button","aria-label":s,"aria-describedby":r?i:void 0,className:"inline-flex h-4 w-4 items-center justify-center rounded-full text-muted hover:text-strong focus:text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),onFocus:()=>o(!0),onBlur:()=>o(!1),children:e.jsx(Wd,{className:"h-3.5 w-3.5","aria-hidden":!0})}),r&&e.jsx("span",{id:i,role:"tooltip",className:`absolute z-50 w-64 rounded border border-strong bg-bg-elevated px-3 py-2 text-xs font-normal leading-relaxed text-strong shadow-lg ${n==="top"?"bottom-full mb-2":"top-full mt-2"} left-1/2 -translate-x-1/2 whitespace-normal`,children:t})]})}const Tn=os;function Us(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function pa(t){return t.toLocaleString()}function Rm(t){const s=Number(t);return Number.isFinite(s)?`${(s*100).toFixed(1)}%`:"—"}function Im(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 $m(t){const s=t.filter(n=>n.kind===Os["backlink-extract"]&&!Ar(n.status));return s.length===0?null:s.reduce((n,a)=>n.createdAt>a.createdAt?n:a)}function Tm(t,s){const n=new Date(t??s).getTime(),a=Math.max(0,Math.floor((Date.now()-n)/1e3));if(a<60)return`${a}s`;const i=Math.floor(a/60),r=a%60;return r===0?`${i}m`:`${i}m ${r}s`}function Mm({projectName:t}){const[s,n]=l.useState(null),[a,i]=l.useState(null),[r,o]=l.useState([]),[m,c]=l.useState(null),[h,p]=l.useState(null),[u,v]=l.useState(null),[j,b]=l.useState(Date.now()),[g,f]=l.useState(0),[k,O]=l.useState(!0),[q,A]=l.useState(!1),[d,y]=l.useState(null),S=l.useCallback(async()=>{O(!0),y(null);try{const[z,ee,ie,W,B]=await Promise.all([Pl().catch(()=>null),Rl(t,{excludeCrawlers:!0}).catch(()=>null),Il(t,{limit:Tn,offset:g,excludeCrawlers:!0}).catch(se=>{if(se instanceof Zs&&se.code==="NOT_FOUND")return null;throw se}),$l(t).catch(()=>[]),Tl(t).catch(()=>[])]);c(z),n(ee),i(ie),o(W);const R=$m(B);p(R)}catch(z){y(z instanceof Error?z.message:"Failed to load backlinks")}finally{O(!1)}},[t,g]);l.useEffect(()=>{S()},[S]),l.useEffect(()=>{if(!h)return;const z=h.id;let ee=!1;const ie=async()=>{try{const B=await Ta(z);if(ee)return;Ar(B.status)?(p(null),v(B),await S()):p(R=>R?.id===B.id?{...R,...B}:R)}catch{}},W=window.setInterval(()=>{ie()},3e3);return()=>{ee=!0,window.clearInterval(W)}},[h,S]),l.useEffect(()=>{if(!h)return;const z=window.setInterval(()=>b(Date.now()),1e3);return()=>window.clearInterval(z)},[h]),l.useEffect(()=>{if(!u||u.status==="failed")return;const z=window.setTimeout(()=>v(null),1e4);return()=>window.clearTimeout(z)},[u]);async function V(){A(!0),y(null);try{const z=await Ll(t);p(z)}catch(z){z instanceof Zs&&z.code==="MISSING_DEPENDENCY"?y("DuckDB is not installed. Visit the Backlinks admin page to install it."):y(z instanceof Error?z.message:"Failed to trigger extract")}finally{A(!1)}}const K=l.useMemo(()=>r.slice().sort((z,ee)=>z.queriedAt.localeCompare(ee.queriedAt)).map(z=>({date:z.queriedAt,linkingDomains:z.totalLinkingDomains})),[r]),w=a?.rows??[],T=a?.total??0,F=s?.excludedLinkingDomains??0,$=Math.floor(g/Tn)+1;return l.useEffect(()=>{g>0&&g>=T&&f(0)},[g,T]),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"})]})}),d&&e.jsx(pe,{className:"surface-card p-4 mb-4 border-negative-800/60",children:e.jsx("p",{className:"text-sm text-negative",children:d})}),h&&e.jsx(pe,{className:"surface-card p-4 mb-4 border-info-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Qd,{className:"h-5 w-5 text-info-400 animate-spin shrink-0 mt-0.5","aria-hidden":!0}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"Extract running"}),e.jsx(oe,{tone:"neutral",children:h.status}),e.jsxs("span",{className:"text-sm text-secondary tabular-nums",children:[Tm(h.startedAt??null,h.createdAt)," elapsed · refreshing every 3s"]}),e.jsxs("span",{className:"sr-only",children:["now=",j]})]}),e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Refreshing this project from the current Common Crawl release."})]})]})}),u&&!h&&e.jsx(pe,{className:`surface-card p-4 mb-4 ${u.status==="failed"?"border-negative-800/60":"border-positive-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[u.status==="failed"?e.jsx("span",{className:"h-5 w-5 shrink-0 mt-0.5 text-negative-400 text-lg leading-none","aria-hidden":!0,children:"!"}):e.jsx(Lr,{className:"h-5 w-5 text-positive-400 shrink-0 mt-0.5","aria-hidden":!0}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:`text-sm font-medium ${u.status==="failed"?"text-negative":"text-positive"}`,children:u.status==="failed"?"Extract failed":"Extract complete"}),u.error?e.jsx("p",{className:"text-sm text-secondary mt-1",children:Ml(u.error)}):u.status!=="failed"?e.jsx("p",{className:"text-sm text-secondary mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),H()]});function H(){return k?e.jsx(pe,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading backlinks…"})}):ye()}function ye(){const z=s!==null&&s.totalLinkingDomains>0,ee=u?.status==="failed",ie=s!==null&&s.totalLinkingDomains===0&&!ee,W=m?.status==="ready",B=m?.status==="failed",R=m&&(m.status==="downloading"||m.status==="querying"||m.status==="queued");return z?ge(e.jsxs(e.Fragment,{children:[!J()&&e.jsxs(e.Fragment,{children:[e.jsxs(P,{type:"button",variant:"outline",size:"sm",disabled:q||h!==null,onClick:Me(V),children:[e.jsx(Dr,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":q?"Queuing…":"Re-run extract"]}),e.jsx(xa,{label:"About re-running",children:"Re-queries the current release for this project without downloading it again."})]}),!J()&&e.jsx(P,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Us("/backlinks"),children:"Open admin"})})]})):e.jsx(pe,{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(Hd,{className:"h-5 w-5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1",children:[!m&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No release sync yet"}),e.jsx("p",{className:"text-sm text-muted mt-1",children:"Run a workspace release sync to populate backlinks for every project in this workspace."}),!J()&&e.jsx("div",{className:"mt-4",children:e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Us("/backlinks"),children:"Set up backlinks"})})})]}),R&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Sync in progress"}),e.jsxs("p",{className:"text-sm text-muted mt-1",children:["A workspace release sync is running (",m.status,m.phaseDetail?` — ${m.phaseDetail}`:"","). Backlinks will appear here once it finishes."]}),!J()&&e.jsx("div",{className:"mt-4",children:e.jsx(P,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Us("/backlinks"),children:"View sync status"})})})]}),B&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Last sync failed"}),e.jsx("p",{className:"text-sm text-muted mt-1",children:m.error??"The workspace release sync failed. Retry from the Backlinks admin page."}),!J()&&e.jsx("div",{className:"mt-4",children:e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Us("/backlinks"),children:"Go to Backlinks admin"})})})]}),W&&!R&&!ie&&!ee&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No backlinks yet for this project"}),e.jsxs("p",{className:"text-sm text-secondary mt-1",children:["Release ",e.jsx("code",{className:"text-neutral",children:m.release})," is ready. Run an extract for this project."]}),!J()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(P,{type:"button",size:"sm",disabled:q||h!==null,onClick:Me(V),children:[e.jsx(Hn,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":q?"Queuing…":"Run extract"]}),e.jsx(xa,{label:"About extraction",children:"Queries the current release for this project without downloading it again."})]})]}),ee&&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."}),!J()&&e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Us("/backlinks"),children:"Go to Backlinks admin"})})})]}),ie&&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."]}),!J()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(P,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Us("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(P,{type:"button",variant:"outline",size:"sm",disabled:q||h!==null,onClick:Me(V),children:[e.jsx(Hn,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),h?"Extract running…":q?"Queuing…":"Re-run extract"]}),e.jsxs(xa,{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 ge(z){if(!s)return null;const ee="Linking hosts",ie="linking hosts",W="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:pa(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 ",ie]}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:pa(s.totalHosts)})}),e.jsxs("p",{className:"metric-card-sub",children:["aggregate ",ie," 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:Rm(s.top10HostsShare)})}),e.jsxs("p",{className:"metric-card-sub",children:["share of ",ie," 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"})," · ",W," ",e.jsx("code",{className:"text-secondary",children:s.release})," · queried ",Im(s.queriedAt),F>0&&e.jsxs(e.Fragment,{children:[" · ",F," excluded domain",F===1?"":"s"]})]}),K.length>=2&&e.jsxs(pe,{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(fn,{width:"100%",height:"100%",children:e.jsxs(bn,{data:K,margin:{top:8,right:12,bottom:0,left:12},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"bl-gradient",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:rt[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:rt[0],stopOpacity:0})]})}),e.jsx(vn,{dataKey:"date",tick:ns,stroke:Gs,tickFormatter:Am}),e.jsx(yn,{tick:ns,stroke:Gs,allowDecimals:!1}),e.jsx(jn,{contentStyle:Ws.contentStyle,labelStyle:Ws.labelStyle,itemStyle:Ws.itemStyle,labelFormatter:Pm}),e.jsx(zs,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:rt[0],fill:"url(#bl-gradient)",strokeWidth:2})]})})})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Top referring domains"}),e.jsx(pe,{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:ee})]})}),e.jsxs("tbody",{children:[w.map(B=>e.jsxs("tr",{className:"border-b border-mono-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-strong",children:B.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-secondary tabular-nums",children:pa(B.numHosts)})]},B.linkingDomain)),w.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-muted",colSpan:2,children:F>0&&T===0?`Every referring domain in this ${W} was a crawler/proxy host (${F} hidden).`:`No referring domains in this ${W}.`})})]})]})}),e.jsx(Es,{page:$,pageSize:Tn,visibleRows:w.length,totalRows:T,onPageChange:B=>f((B-1)*Tn)})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:z})]})}}function Lm({projectName:t}){const s=Ie({...Dl({client:U,path:{name:t}}),staleTime:Pr}),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:Va(a)})]});if(!n)return null;if(n.status==="no-data")return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsx("h2",{children:"Citation + answer-mention coverage"})]})}),e.jsx("p",{className:"text-sm text-muted",children:n.reason==="no-queries"?"Add queries to start tracking AI citations.":"Run a sweep to see which engines cite this project."})]});const{providersCiting:i,providersMentioning:r,providersConfigured:o}=n.summary;return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsxs("h2",{className:"flex items-center gap-2",children:["Cited by ",i," of ",o," engines",e.jsx(Je,{text:"An engine is ‘citing’ when our domain appears in its grounding source list (the structured citation/search-result attribution it returns alongside the answer). Counts each configured engine that cites the project on at least one tracked query in the latest snapshot per (query × provider)."})]}),e.jsxs("p",{className:"text-base text-neutral flex items-center gap-2",children:["Mentioned in ",r," of ",o," engine answers",e.jsx(Je,{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(Dm,{data:n}),e.jsx(Em,{data:n}),n.competitorGaps.length>0&&e.jsx(Fm,{data:n})]})}function Dm({data:t}){const{totalQueries:s,queriesCitedAndMentioned:n,queriesCitedOnly:a,queriesMentionedOnly:i,queriesInvisible:r}=t.summary;return e.jsxs("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4 mb-4",children:[e.jsx(Mn,{label:"Cited + mentioned",value:`${n} / ${s}`,helper:"In sources AND named in answer",tone:n>0?"positive":"neutral"}),e.jsx(Mn,{label:"Cited only",value:`${a} / ${s}`,helper:"In sources, not named in answer",tone:a>0?"positive-dim":"neutral"}),e.jsx(Mn,{label:"Mentioned only",value:`${i} / ${s}`,helper:"Named in answer, no source link",tone:i>0?"caution":"neutral"}),e.jsx(Mn,{label:"Invisible",value:`${r} / ${s}`,helper:"No engine cites or mentions",tone:r>0?"negative":"neutral"})]})}function Mn({label:t,value:s,helper:n,tone:a}){const i=a==="positive"?"text-positive":a==="positive-dim"?"text-positive-400/70":a==="caution"?"text-caution":a==="negative"?"text-negative":"text-heading";return e.jsxs("div",{className:"rounded-md border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:t}),e.jsx("p",{className:`mt-1 text-2xl font-semibold tabular-nums ${i}`,children:s}),e.jsx("p",{className:"text-[11px] text-muted",children:n})]})}function Em({data:t}){const s=l.useMemo(()=>{const n=new Set;for(const a of t.byQuery)for(const i of a.providers)n.add(i.provider);return Array.from(n).sort()},[t.byQuery]);return t.byQuery.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No query coverage rows."}):e.jsxs("div",{children:[e.jsx(qm,{}),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(Js,{provider:n})},n)),e.jsx("th",{className:"text-right",children:"Cite"}),e.jsx("th",{className:"text-right",children:"Ment"})]})}),e.jsx("tbody",{children:t.byQuery.map(n=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:n.query}),s.map(a=>{const i=n.providers.find(r=>r.provider===a);return e.jsx("td",{className:"text-center",children:i==null?e.jsx(Yd,{className:"inline h-3.5 w-3.5 text-mono-700","aria-label":"no data"}):e.jsx(Om,{provider:i})},a)}),e.jsx("td",{className:"text-right tabular-nums",children:e.jsxs("span",{className:n.totalProviders>0&&n.citedCount===n.totalProviders?"text-positive":n.citedCount>0?"text-positive-400/70":"text-muted",children:[n.citedCount,"/",n.totalProviders]})}),e.jsx("td",{className:"text-right tabular-nums",children:e.jsxs("span",{className:n.totalProviders>0&&n.mentionedCount===n.totalProviders?"text-info-300":n.mentionedCount>0?"text-info-400/70":"text-muted",children:[n.mentionedCount,"/",n.totalProviders]})})]},n.queryId))})]})})]})}function qm(){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(Qs,{active:!0,tone:"cited"}),e.jsx("span",{children:"cited (in sources)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Qs,{active:!0,tone:"mentioned"}),e.jsx("span",{children:"mentioned (in answer)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Qs,{active:!1,tone:"cited"}),e.jsx(Qs,{active:!1,tone:"mentioned"}),e.jsx("span",{children:"neither"})]})]})}function Om({provider:t}){const s=Gm(t);return e.jsxs("span",{className:"inline-flex items-center justify-center gap-1",title:s,children:[e.jsx(Qs,{active:t.cited,tone:"cited"}),e.jsx(Qs,{active:t.mentioned,tone:"mentioned"})]})}function Gm(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 Qs({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 Fm({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(Je,{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(Js,{provider:s.provider})}),e.jsx("td",{className:"text-neutral",children:s.citingCompetitors.join(", ")})]},`${s.queryId}::${s.provider}`))})]})})]})}const Sn="__cited__",Cn="__mentioned__",Qt="__mentionShare__";function no(t){const s=t,{dataStartDate:n,dataEndDate:a}=s;return typeof n!="string"||typeof a!="string"?null:{start:us(n),end:us(a),sweepCount:s.sweepCount??1}}function Xn(t){const s=no(t);if(!s)return"Sweep date unavailable";const n=Ss(s.start),a=Ss(s.end);return n===a?n:`${n} – ${a} · ${s.sweepCount} sweeps combined`}function _m(t){const s=no(t);return s?Or(s.start):""}function tn(t){return t.trim().toLowerCase()}function Ea(t){return Math.round(t*1e3)/10}function qa(t){return t.byProvider??{}}function Um(t,s,n){const a=t.buckets.length>0,i=t.buckets.length===1;if(n==="overall"){const c=s==="cited"?Sn:Cn,h=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(u=>({date:u.startDate,[c]:Ea(u[h])})),series:[c],hasData:a,singleBucket:i}}const r=s==="mentioned"?"mentionRate":"citationRate",o=[...new Set(t.buckets.flatMap(c=>Object.keys(qa(c))))].sort();return{rows:t.buckets.map(c=>{const h={date:c.startDate},p=qa(c);for(const u of o){const v=p[u];h[u]=v?Ea(v[r]):null}return h}),series:o,hasData:a,singleBucket:i}}function ao(t){const s=t;return Object.hasOwn(s,"modelEvidenceByProvider")?s.modelEvidenceByProvider??{}:null}function Bm(t){const s=t;return Object.hasOwn(s,"modelAttribution")?s.modelAttribution??{}:null}function Vm(t){return t.servedModelAttribution??{}}function Km(t){return t.modelServiceMismatch??{}}function zm(t){return t.modelPointerChanges??{}}function Qm(t){return t.length>0?t.join(", "):null}function Di(t,s){const n=tn(s);return Object.entries(t).find(([a])=>tn(a)===n)?.[1]}function ls(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 Hm(t,s){for(let n=t.length-1;n>=0;n-=1){const a=t[n];if(!Di(qa(a),s))continue;const i=ao(a);return i?Di(i,s)??null:null}return null}function Wm(t){const s=new Map;for(const[n,a]of Object.entries(t))for(const i of a.events){const r=s.get(i.bucketStartDate)??[];r.push({provider:n,event:i}),s.set(i.bucketStartDate,r)}return[...s.entries()].sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>({bucketStartDate:n,events:[...a].sort((i,r)=>i.provider.localeCompare(r.provider)||i.event.observedAt.localeCompare(r.event.observedAt))}))}function Ym(t){const s={},n=[];for(const[a,i]of Object.entries(t)){const r=i.events.filter(o=>!o.fromPreWindowAnchor);for(const o of i.events)o.fromPreWindowAnchor&&n.push({provider:a,event:o});r.length>0&&(s[a]={...i,events:r})}return{buckets:Wm(s),beforeWindow:n.sort((a,i)=>a.event.observedAt.localeCompare(i.event.observedAt)||a.provider.localeCompare(i.provider))}}function Xm(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 Jm(t){const s=[];for(const[n,a]of Object.entries(t)){const i=a.eventTotal??a.events.length;i>a.events.length&&s.push({provider:n,shown:a.events.length,total:i})}return s.sort((n,a)=>n.provider.localeCompare(a.provider))}function Zm(t){const s=t.buckets.map(a=>{const i=a.mentionShare;return{date:a.startDate,[Qt]:i?.rate==null?null:Ea(i.rate)}}),n=s.map(a=>a[Qt]).filter(a=>typeof a=="number"&&Number.isFinite(a));return{rows:s,series:[Qt],hasData:n.length>0,singleBucket:n.length===1}}function eh(t,s,n){return s==="mentionShare"?Zm(t):Um(t,s,n)}function Ei(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 qi(t){const[,s,n]=t.slice(0,10).split("-");return!s||!n?t:`${s}/${n}`}function Oi(t){return t>0?`+${t}`:`${t}`}function th(t){if(t.length===0)return null;if(t.length<=2)return`Query set changed: ${t.map(n=>`${Oi(n.delta)} on ${qi(n.date)}`).join(", ")}`;const s=[...t].sort((n,a)=>a.date.localeCompare(n.date))[0];return`Query set changed ${t.length} times (latest ${Oi(s.delta)} on ${qi(s.date)})`}const sh=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],nh=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],ah=[{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."}],za=rt[2],ih="var(--chart-tooltip-bg)",rh={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",local:"Local"};function ds(t){const s=tn(t);return rh[s]??t.charAt(0).toUpperCase()+t.slice(1)}function Ns(t){return Math.round(t*10)/10}function oh(t){return t===Sn||t===Cn||t===Qt}function io(t){return t===Sn?"Cited":t===Cn?"Mentioned":t===Qt?"Mention share":ds(t)}function dn(t,s){return t===Sn?qs.positive:t===Cn?rt[1]:t===Qt?za:Zd(tn(t),s)}function lh(t,s){for(const n of t){const a=n[s];if(typeof a=="number"&&Number.isFinite(a))return a}return null}function ch(t){return t.map(s=>s.trim().toLowerCase()).filter(Boolean).sort().join(`
|
|
2
|
+
`)}function ea(t){return t==="non-brand"?"non-brand queries":"pooled queries · classification unavailable"}function Vn(t,s){return t==="cited"?"Cited":t==="mentionShare"?s?`Mention share · ${ea(s)}`:"Mention share":"Mentioned"}function Nn(t){return t==="cited"?"citationRate":"mentionRate"}function ro(t,s){return s==="cited"?t.cited:t.mentionedCount}function oo(t,s,n){const a=t.byProvider[s];return a?{count:n==="cited"?a.cited:a.mentionedCount,total:a.total,rate:n==="cited"?a.citationRate:a.mentionRate}:null}function lo(t,s){if(s===void 0)return null;const n=String(s);return t.find(a=>a.startDate===n)??null}function Oa(t){const s=ao(t);if(s===null)return"Model attribution unavailable for this bucket.";const n=Object.entries(s).sort(([a],[i])=>tn(a).localeCompare(tn(i))).map(([a,i])=>`${ds(a)}: ${ls(i)}`);return n.length>0?`Model evidence: ${n.join("; ")}`:"No model evidence in this bucket."}function dh(t){return t.some(({event:s})=>s.to.status==="mixed")?qs.caution:t.some(({event:s})=>s.to.status==="unknown")?qs.negative:t.every(({event:s})=>s.from.status==="known"&&s.to.status==="known")?rt[4]:qs.positive}function uh(t,s,n){const a=lo(t,s);return a?Xn(a):Ss(us(n))}function mh({partition:t,available:s,counts:n,truncated:a,incompleteHistory:i,served:r,mismatch:o,buckets:m}){const c=l.useId(),h=Object.entries(r).sort(([u],[v])=>u.localeCompare(v)),p=t.buckets.length>0||t.beforeWindow.length>0;return!s||!p?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:u,events:v})=>v.map(({provider:j,event:b})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:uh(m,u,b.observedAt)}),e.jsxs("span",{children:[ds(j),": ",ls(b.from)," → ",ls(b.to)]})]},`${j}-${b.observedAt}-${b.bucketStartDate}`)))}),t.beforeWindow.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"trend-model-evidence-note",children:"Changed before this date range"}),e.jsx("ul",{className:"trend-model-evidence-list",children:t.beforeWindow.map(({provider:u,event:v})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsxs("span",{className:"trend-model-evidence-date",children:["on or before ",Ss(us(v.observedAt))]}),e.jsxs("span",{children:[ds(u),": ",ls(v.from)," → ",ls(v.to),v.anchorObservedAt?` (last seen ${ls(v.from)} on ${Ss(us(v.anchorObservedAt))})`:""]})]},`before-${u}-${v.observedAt}`))})]}),a.map(u=>e.jsxs("p",{className:"trend-model-evidence-note",children:[ds(u.provider),": showing the most recent ",u.shown," of ",u.total," changes."]},`truncated-${u.provider}`)),i.map(u=>e.jsxs("p",{className:"trend-model-evidence-note",children:["We did not look far enough back to be sure this is every ",ds(u)," change."]},`incomplete-${u}`)),h.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"trend-model-evidence-note",children:"What the engines answered with"}),e.jsx("ul",{className:"trend-model-evidence-list",children:h.map(([u,v])=>{const j=Qm(v.latestServedModelIds),b=o[u];return e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:Ss(us(v.latestObservation.observedAt))}),e.jsxs("span",{children:[ds(u),": ",j??ls(v.latestObservation.state),b?` — not the ${ls(b.configured)} you selected`:""]})]},`served-${u}`)})})]})]})}function Gi(t){return t===null?"no data":`${t}%`}function ga(t){return t==null?"undefined":`${Ns(t*100)}%`}function hh({active:t,label:s,payload:n,metric:a,mode:i,buckets:r}){if(!t)return null;const o=lo(r,s);if(!o)return null;if(a==="mentionShare"){const c=o.mentionShare.projectMentionSnapshots,h=o.mentionShare.competitorMentionSnapshots,p=c+h,u=o.mentionShare.rate==null?null:Ns(o.mentionShare.rate*100);return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:Xn(o)}),e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch trend-tooltip-swatch-ring",style:{borderColor:za},"aria-hidden":"true"}),e.jsxs("span",{className:"trend-tooltip-name",children:["Mention share · ",ea(o.mentionShare.scope)]}),e.jsx("span",{className:"trend-tooltip-value",children:Gi(u)})]}),p>0?e.jsxs("p",{className:"trend-tooltip-detail",children:["You ",c," / ",p," brand mentions. Competitors ",h,"."]}):e.jsx("p",{className:"trend-tooltip-detail",children:"No project or competitor brand mentions in this bucket."}),e.jsx("p",{className:"trend-tooltip-detail",children:Oa(o)})]})}const m=i==="byProvider"?(n??[]).filter(c=>c.dataKey!==void 0):[{dataKey:a==="cited"?Sn:Cn,value:Ns(o[Nn(a)]*100)}];return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:Xn(o)}),m.map((c,h)=>{const p=String(c.dataKey??c.name??""),u=i==="byProvider"?oo(o,p,a):null,v=u?.count??ro(o,a),j=u?.total??o.total,b=typeof c.value=="number"?c.value:Ns(u?u.rate*100:o[Nn(a)]*100),g=c.color??dn(p,h);return e.jsxs("div",{className:"trend-tooltip-block",children:[e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch",style:{backgroundColor:g},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:io(p)}),e.jsx("span",{className:"trend-tooltip-value",children:Gi(b)})]}),e.jsxs("p",{className:"trend-tooltip-detail",children:[v," / ",j," snapshots, ",a==="cited"?"source links":"answer text"]})]},`${p}-${h}`)}),e.jsx("p",{className:"trend-tooltip-detail",children:Oa(o)})]})}function xh({buckets:t,metric:s,mode:n,series:a}){const i=t[t.length-1]?.mentionShare.scope;return e.jsxs("table",{className:"sr-only",children:[e.jsxs("caption",{children:[Vn(s,i)," trend data"]}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Bucket"}),e.jsx("th",{scope:"col",children:"Values"})]})}),e.jsx("tbody",{children:t.map(r=>{let o;if(s==="mentionShare"){const m=r.mentionShare.projectMentionSnapshots,c=r.mentionShare.competitorMentionSnapshots,h=m+c,p=ea(r.mentionShare.scope);o=h>0?`${ga(r.mentionShare.rate)} mention share for ${p}, ${m} of ${h} brand mentions were you`:`mention share undefined for ${p}, no project or competitor brand mentions`}else n==="byProvider"?o=a.map(m=>{const c=oo(r,m,s);return c?`${ds(m)} ${ga(c.rate)} ${Vn(s).toLowerCase()}, ${c.count} of ${c.total} snapshots`:`${ds(m)} no data`}).join("; "):o=`${ga(r[Nn(s)])} ${Vn(s).toLowerCase()}, ${ro(r,s)} of ${r.total} snapshots`;return o+=`; ${Oa(r)}`,e.jsxs("tr",{children:[e.jsx("th",{scope:"row",children:Xn(r)}),e.jsx("td",{children:o})]},r.startDate)})})]})}function fa({options:t,value:s,onChange:n,ariaLabel:a,className:i}){const r=l.useId();return e.jsx("div",{role:"group","aria-label":a,className:`segmented ${i??""}`,children:t.map(o=>{const m=s===o.value,c=o.description?`${r}-${o.value}-description`:void 0;return e.jsxs(l.Fragment,{children:[e.jsx("button",{type:"button","aria-pressed":m,"aria-describedby":c,className:`segmented-option ${m?"segmented-option-active":""}`,onClick:()=>n(o.value),children:o.label}),o.description&&e.jsx("span",{id:c,className:"sr-only",children:o.description})]},o.value)})})}function ph({projectName:t,competitorDomains:s=[],analyticsRevision:n="none"}){const[a,i]=l.useState("all"),[r,o]=l.useState("mentioned"),[m,c]=l.useState("byProvider"),h=l.useMemo(()=>ch(s),[s]),p=Ie({queryKey:["analytics-metrics",t,a,h,n],queryFn:()=>El(t,a),staleTime:Pr}),u=p.data??null,v=p.error,j=r==="mentionShare"?"overall":m,b=l.useMemo(()=>u?eh(u,r,j):null,[u,r,j]),g=u?Bm(u):null,f=l.useMemo(()=>Ym(g??{}),[g]),k=l.useMemo(()=>Xm(g??{}),[g]),O=l.useMemo(()=>Jm(g??{}),[g]),q=l.useMemo(()=>Object.entries(g??{}).filter(([,B])=>B.anchorUnavailable).map(([B])=>B).sort(),[g]),A=l.useMemo(()=>u?Vm(u):{},[u]),d=l.useMemo(()=>u?Km(u):{},[u]),y=l.useMemo(()=>u?ql(zm(u)):null,[u]),S=r!=="mentionShare"&&j==="byProvider",V=u?.buckets??[],K=V[V.length-1]?.mentionShare.scope??u?.mentionShareScope??"pooled",w=Vn(r,K),T=r==="cited"?qs.positive:r==="mentionShare"?za:rt[1],F=S?Ht.textDim:T,$=l.useMemo(()=>{const B=new Map(V.map(R=>[R.startDate,_m(R)]));return R=>B.get(String(R))??""},[V]),H=r==="mentionShare"?b?Ei(b.rows,Qt):null:V.length>0?Ns(V[V.length-1][Nn(r)]*100):null,ye=r==="mentionShare"?b?lh(b.rows,Qt):null:V.length>0?Ns(V[0][Nn(r)]*100):null,ge=r==="mentionShare"?b?.rows.filter(B=>typeof B[Qt]=="number").length??0:V.length,z=H!==null&&ye!==null&&ge>1?Ns(H-ye):null,ee=s.length,ie=e.jsxs(e.Fragment,{children:[y?.kind==="change"&&e.jsx("p",{className:"mb-3 rounded-lg border border-caution-800/60 bg-caution-950/20 px-3 py-2 text-[11px] leading-snug text-secondary",children:y.text}),e.jsxs("div",{className:"visibility-trend-head",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsxs("h2",{className:"visibility-trend-title",children:["Answer-engine trend",e.jsx(Je,{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."})]})]}),H!==null&&e.jsxs("div",{className:"visibility-trend-current",children:[e.jsx("span",{className:"visibility-trend-current-dot",style:{backgroundColor:F},"aria-hidden":"true"}),e.jsx("span",{className:"visibility-trend-current-label",children:w}),S&&e.jsx("span",{className:"visibility-trend-current-qualifier",children:"avg"}),e.jsxs("span",{className:"visibility-trend-current-value",children:[H,"%"]}),z!==null&&e.jsxs("span",{className:`visibility-trend-current-delta ${z>0?"text-positive-400":z<0?"text-negative-400":"text-muted"}`,children:[z>0?"+":"",z.toFixed(1)," pts"]})]})]}),e.jsxs("div",{className:"visibility-trend-controls",children:[e.jsx(fa,{options:ah,value:r,onChange:o,ariaLabel:"Metric",className:"visibility-trend-metric-control"}),r!=="mentionShare"&&e.jsx(fa,{options:nh,value:m,onChange:c,ariaLabel:"Series"}),e.jsx(fa,{options:sh,value:a,onChange:i,ariaLabel:"Time window",className:"sm:ml-auto"})]})]});let W;if(v)W=e.jsx("p",{className:"text-sm text-negative-400",children:Va(v)});else if(p.isLoading&&!u)W=e.jsx("div",{className:"visibility-trend-chart animate-pulse rounded-lg bg-bg-elevated/40","aria-hidden":"true"});else if(r==="mentionShare"&&ee===0)W=e.jsx("p",{className:"text-sm text-secondary",children:"Add tracked competitors to measure mention share over time."});else if(!u||!b)W=null;else{const{rows:B,series:R,hasData:se}=b,le=th(u.queryChanges);if(!se)W=e.jsx("p",{className:"text-sm text-secondary",children:r==="mentionShare"?`No answer-text brand mentions for you or tracked competitors on ${ea(K)} in this window yet.`:"Run a sweep to start tracking citations and mentions over time."});else if(S&&R.length===0)W=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 de=`${w} rate across ${B.length} ${B.length===1?"sweep":"sweeps"}. Latest ${H}%${z!==null?`, ${z>=0?"up":"down"} ${Math.abs(z).toFixed(1)} points over the period`:""}.`;W=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"sr-only",children:de}),e.jsx(xh,{buckets:V,metric:r,mode:j,series:R}),S&&R.length>0&&e.jsx("ul",{className:"trend-legend","aria-label":"Engines",children:R.map((X,Ae)=>{const _=Ei(B,X),ae=Hm(V,X),Ne=g===null?"Attribution unavailable":ae?ls(ae):"No observed model evidence";return e.jsxs("li",{className:"trend-legend-item",children:[e.jsx("span",{className:"trend-legend-swatch",style:{backgroundColor:dn(X,Ae)},"aria-hidden":"true"}),e.jsxs("span",{className:"trend-legend-label",children:[e.jsx("span",{className:"trend-legend-name",children:io(X)}),e.jsxs("span",{className:"trend-legend-model",children:[e.jsx("span",{"aria-hidden":"true",children:"· "}),Ne]})]}),_!==null&&e.jsxs("span",{className:"trend-legend-value",children:[_,"%"]})]},X)})}),e.jsx("div",{className:"visibility-trend-chart",role:"img","aria-label":`${w} trend chart over ${B.length} ${B.length===1?"bucket":"buckets"}`,children:e.jsx(fn,{width:"100%",height:"100%",children:e.jsxs(bn,{data:B,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Fr,{stroke:qr,vertical:!1}),e.jsx(vn,{dataKey:"date",tick:ns,tickLine:!1,axisLine:{stroke:Gs},tickFormatter:$,minTickGap:24}),e.jsx(yn,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:X=>`${X}%`,tick:ns,tickLine:!1,axisLine:!1,width:40}),e.jsx(jn,{cursor:{stroke:Gs,strokeWidth:1},content:e.jsx(hh,{metric:r,mode:j,buckets:V})}),f.buckets.map(({bucketStartDate:X,events:Ae})=>e.jsx(au,{x:X,stroke:dh(Ae),strokeDasharray:"4 4",strokeWidth:1.5,ifOverflow:"extendDomain"},`model-evidence-${X}`)),R.map((X,Ae)=>e.jsx(_r,{type:"monotone",dataKey:X,name:X,stroke:dn(X,Ae),strokeDasharray:X===Qt?"5 4":void 0,strokeWidth:oh(X)?2.5:2,dot:X===Qt?{r:2.75,fill:"var(--chart-tooltip-bg)",stroke:dn(X,Ae),strokeWidth:1.5}:{r:2.5,fill:dn(X,Ae),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:ih},connectNulls:X!==Qt,isAnimationActive:!1},X))]})})}),e.jsx(mh,{partition:f,available:g!==null,counts:k,truncated:O,incompleteHistory:q,served:A,mismatch:d,buckets:V}),le&&e.jsx("p",{className:"visibility-trend-note",children:le})]})}}return e.jsxs("section",{className:"visibility-trend",children:[ie,W]})}const Fi=new Set([hn.queued,hn.running]);function gh({projectName:t}){const s=Cs(),[n,a]=l.useState(""),[i,r]=l.useState(""),[o,m]=l.useState(""),[c,h]=l.useState("__default__"),[p,u]=l.useState(null),v=Ie({...Ol({client:U,path:{name:t}}),staleTime:6e4}),j=Ie({...Gl({client:U}),staleTime:6e4}),b=Ie({...Fl({client:U,path:{name:t},query:{limit:20}}),refetchInterval:w=>w.state.data?.runs.some(T=>Fi.has(T.status))?3e3:!1}),g=b.data?.runs??[];l.useEffect(()=>{!p&&g[0]&&u(g[0].id)},[g,p]);const f=g.find(w=>w.id===p)??null,k=Ie({..._l({client:U,path:{name:t,runId:p??""}}),enabled:!!p,refetchInterval:f&&Fi.has(f.status)?3e3:!1}),O=k.data??null,q=l.useMemo(()=>vh(n),[n]),A=v.data?.locations??[],d=l.useMemo(()=>{const w=new Map((j.data?.providerCatalog??[]).map(T=>[T.name,T]));return(j.data?.providers??[]).filter(T=>T.configured&&w.get(T.name)?.mode==="api").map(T=>({...T,catalog:w.get(T.name)}))},[j.data]),y=!j.isLoading&&d.length===0,S=d.find(w=>w.name===i)??null;l.useEffect(()=>{i&&!S&&(r(""),m(""))},[i,S]);const V=Et({...Ul(),onSuccess:async w=>{u(w.id),a(""),m(""),await wh(s),Se({title:"Research batch saved",detail:`${w.totalQueries} quer${w.totalQueries===1?"y is":"ies are"} in research history. Nothing was added to tracked queries.`,tone:"positive",dedupeKey:`research:start:${w.id}`,dedupeMode:"replace"})},onError:w=>{Se({title:"Could not start research",detail:w instanceof Error?w.message:"Check the provider, model, and location, then try again.",tone:"negative"})}});function K(){if(q.length===0||q.length>50||y||V.isPending||J())return;const w=c==="__default__"?void 0:c==="__none__"?null:A.find(T=>T.label===c)??void 0;V.mutate({client:U,path:{name:t},body:{queries:q,...i?{provider:i}:{},...i&&o.trim()?{model:o.trim()}:{},...w!==void 0?{location:w}:{}}})}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(pe,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"New batch"}),e.jsx("h3",{children:"Research queries"}),e.jsx("p",{className:"mt-1 max-w-xl text-sm leading-6 text-muted",children:"Run specific queries against one API model and keep the answers as a separate research record."})]})}),e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("label",{className:"block",htmlFor:"research-queries",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Queries"}),e.jsx("textarea",{id:"research-queries",className:"mt-1 min-h-36 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:`one query per line
|
|
3
|
+
e.g. What is the best way to choose an AEO platform?`,value:n,onChange:w=>a(w.target.value),"aria-describedby":"research-query-count"}),e.jsxs("span",{id:"research-query-count",className:`mt-1 block text-[11px] ${q.length>50?"text-negative":"text-faint"}`,children:[q.length," ",q.length===1?"query":"queries",", duplicates and blank lines are removed. Maximum 50."]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"block",htmlFor:"research-provider",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"API provider"}),e.jsxs("select",{id:"research-provider",className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none",value:i,onChange:w=>{r(w.target.value),m("")},children:[e.jsx("option",{value:"",children:"Project default"}),d.map(w=>e.jsx("option",{value:w.name,children:w.displayName??w.name},w.name))]})]}),e.jsxs("label",{className:"block",htmlFor:"research-location",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Location"}),e.jsxs("select",{id:"research-location",className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none",value:c,onChange:w=>h(w.target.value),children:[e.jsx("option",{value:"__default__",children:"Project default"}),e.jsx("option",{value:"__none__",children:"No location"}),A.map(w=>e.jsx("option",{value:w.label,children:w.label},w.label))]})]})]}),e.jsxs("label",{className:"block",htmlFor:"research-model",children:[e.jsxs("span",{className:"text-xs font-medium text-secondary",children:["Exact model ",e.jsx("span",{className:"font-normal text-muted",children:"(optional)"})]}),e.jsx("input",{id:"research-model",list:"research-known-models",className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none disabled:cursor-not-allowed disabled:opacity-50",placeholder:S?`Default: ${S.model??S.defaultModel??S.catalog.defaultModel}`:"Choose a provider to select an exact model",value:o,disabled:!S,onChange:w=>m(w.target.value)}),e.jsx("datalist",{id:"research-known-models",children:(S?.catalog.knownModels??[]).map(w=>e.jsx("option",{value:w.id,children:w.displayName},w.id))})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 border-t border-default pt-4",children:[!J()&&e.jsxs(Ye,{type:"button",size:"sm",disabled:q.length===0||q.length>50||y||V.isPending,onClick:K,children:[e.jsx(Hn,{size:14}),V.isPending?"Starting research…":`Run ${q.length||""} research ${q.length===1?"query":"queries"}`]}),e.jsx("p",{className:"text-xs leading-5 text-muted",children:"Saved to research history. Nothing is added to tracked queries."})]}),y&&e.jsx("p",{className:"rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2 text-sm text-caution",children:"Configure an API provider in Settings before starting research. Browser engines are not available for this workflow."})]})]}),e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Saved research batches"})]}),b.isFetching&&e.jsx(oe,{tone:"neutral",children:"Loading"})]}),g.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:g.map(w=>e.jsxs("tr",{className:p===w.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:()=>u(w.id),children:yh(w.createdAt)})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:w.provider}),e.jsx("span",{className:"font-mono text-[11px] text-muted",children:w.requestedModel??w.resolvedModel})]}),e.jsx("td",{className:"text-secondary",children:w.location?.label??"No location"}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[w.completedQueries+w.failedQueries,"/",w.totalQueries]}),e.jsx("td",{children:e.jsx(oe,{tone:co(w.status),children:w.status})})]},w.id))})]})})]})]}),e.jsx(fh,{detail:O,isLoading:k.isFetching})]})}function fh({detail:t,isLoading:s}){const[n,a]=l.useState(null);l.useEffect(()=>{a(t?.queries[0]?.id??null)},[t?.id]);const i=t?.queries.find(r=>r.id===n)??t?.queries[0]??null;return e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Results"}),e.jsx("h3",{children:t?`Research run ${jh(t.id)}`:"Choose a research batch"})]}),t&&e.jsx(oe,{tone:co(t.status),children:t.status})]}),t?e.jsxs("div",{className:"mt-4 grid gap-4 xl:grid-cols-[minmax(0,1.15fr)_minmax(320px,0.85fr)]",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[680px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"})]})}),e.jsx("tbody",{children:t.queries.map(r=>e.jsxs("tr",{className:i?.id===r.id?"bg-bg-elevated/40":void 0,children:[e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-left font-medium text-heading hover:text-link focus:outline-none focus:underline",onClick:()=>a(r.id),children:r.query})}),e.jsx("td",{children:e.jsx(oe,{tone:Nh(r.status),children:r.status})}),e.jsx("td",{children:e.jsx(oe,{tone:r.answerMentioned===!0?"positive":r.answerMentioned===!1?"neutral":r.status===Ds.failed?"negative":"caution",children:r.answerMentioned===null?r.status===Ds.failed?"Unavailable":"Pending":r.answerMentioned?"Mentioned":"Not mentioned"})}),e.jsx("td",{children:e.jsx(oe,{tone:r.citationState==="cited"?"positive":r.citationState==="not-cited"?"neutral":r.status===Ds.failed?"negative":"caution",children:r.citationState===null?r.status===Ds.failed?"Unavailable":"Pending":r.citationState==="cited"?"Cited":"Not cited"})})]},r.id))})]})}),e.jsx(bh,{query:i,isLoading:s})]}):e.jsx("p",{className:"mt-4 text-sm text-muted",children:"Select a saved batch to inspect each answer and its source links."})]})}function bh({query:t,isLoading:s}){return t?e.jsxs("div",{className:"space-y-4 border-t border-default pt-4 xl:border-t-0 xl:border-l xl:pl-4 xl:pt-0",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Selected query"}),e.jsx("p",{className:"mt-1 text-sm font-medium leading-6 text-heading",children:t.query})]}),t.error?e.jsx("div",{className:"rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:t.error}):t.answerText?e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Answer"}),e.jsx("p",{className:"mt-1 whitespace-pre-wrap text-sm leading-6 text-secondary",children:t.answerText})]}):e.jsx("p",{className:"text-sm text-muted",children:t.status===Ds.failed?"This query did not return an answer.":"The answer will appear here when this query finishes."}),t.namedCompetitors.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Named in answer"}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:t.namedCompetitors.map(n=>e.jsx("span",{className:"mention-chip mention-chip--competitor",children:n},n))})]}),t.citedCompetitorDomains.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Cited competitor domains"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:"Cited as a source, not merely named in the answer."}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:t.citedCompetitorDomains.map(n=>e.jsx("span",{className:"mention-chip mention-chip--competitor",children:n.replace(/^www\./,"")},n))})]}),t.groundingSources.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Source links"}),e.jsx("ul",{className:"mt-2 space-y-1",children:t.groundingSources.map((n,a)=>{const i=Ts(n.uri),r=n.title||n.uri;return e.jsxs("li",{className:"flex min-w-0 items-start gap-1.5 text-sm",children:[i?e.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",className:"truncate text-secondary hover:text-link focus:outline-none focus:underline",children:r}):e.jsx("span",{className:"truncate text-secondary",children:r}),i&&e.jsx(Xd,{className:"mt-0.5 size-3 shrink-0 text-muted","aria-hidden":"true"})]},`${n.uri}-${a}`)})})]})]}):e.jsx("p",{className:"text-sm text-muted",children:s?"Loading saved answers…":"Select a query to inspect its answer."})}function vh(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 yh(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 jh(t){return t.length>8?t.slice(0,8):t}function co(t){return t===hn.completed?"positive":t===hn.partial?"caution":t===hn.failed?"negative":"neutral"}function Nh(t){return t===Ds.completed?"positive":t===Ds.failed?"negative":"neutral"}async function wh(t){await ft(t,"researchRuns")}const Ga=new Set(["queued","seeding","probing"]);function Sh({projectName:t}){const[s,n]=l.useState("find");return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Query discovery"}),e.jsx("h2",{children:"Discover or research queries"})]})}),e.jsxs("div",{className:"inline-flex rounded-md border border-default bg-surface p-1",role:"tablist","aria-label":"Query discovery workflow",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":s==="find",className:`rounded px-3 py-1.5 text-sm font-medium transition-colors ${s==="find"?"bg-bg-elevated text-heading shadow-sm":"text-muted hover:text-strong"}`,onClick:()=>n("find"),children:"Find queries"}),e.jsx("button",{type:"button",role:"tab","aria-selected":s==="research",className:`rounded px-3 py-1.5 text-sm font-medium transition-colors ${s==="research"?"bg-bg-elevated text-heading shadow-sm":"text-muted hover:text-strong"}`,onClick:()=>n("research"),children:"Research queries"})]}),e.jsx("div",{className:"mt-4",children:s==="find"?e.jsx(Ch,{projectName:t}):e.jsx(gh,{projectName:t})})]})}function Ch({projectName:t}){const s=Cs(),[n,a]=l.useState(null),[i,r]=l.useState(""),[o,m]=l.useState("100"),c=Ie({...Bl({client:U,path:{name:t},query:{limit:"10"}}),refetchInterval:d=>d.state.data?.some(S=>Ga.has(S.status))?3e3:!1}),h=c.data??[];l.useEffect(()=>{!n&&h[0]&&a(h[0].id)},[n,h]);const p=h.find(d=>d.id===n)??null,u=Ie({...Vl({client:U,path:{name:t,id:n??""}}),enabled:!!n,refetchInterval:p&&Ga.has(p.status)?3e3:!1}),v=u.data??null,j=Ie({...Kl({client:U,path:{name:t,id:n??""}}),enabled:!!(n&&p?.status==="completed")}),b=Et({mutationFn:()=>{const d={},y=i.trim();y&&(d.icpDescription=y);const S=Number.parseInt(o,10);return Number.isFinite(S)&&S>0&&(d.maxProbes=S),zl(t,d)},onSuccess:async d=>{a(d.sessionId),r(""),await Ui(s,t,d.sessionId),Se({title:"Discovery started",detail:`Run ${ba(d.sessionId)} is testing questions your customers might ask.`,tone:"neutral",dedupeKey:`discovery:start:${d.sessionId}`,dedupeMode:"replace"})},onError:d=>{Se({title:"Discovery failed to start",detail:d instanceof Error?d.message:"Could not start discovery.",tone:"negative"})}}),g=Et({mutationFn:d=>{if(!n)throw new Error("Select a completed discovery session first.");return Ql(t,n,d)},onSuccess:async d=>{await Ui(s,t,d.sessionId),s.invalidateQueries({queryKey:Rr({client:U})}),s.invalidateQueries({predicate:y=>Array.isArray(y.queryKey)&&y.queryKey[0]==="projects"&&y.queryKey.length>1}),Se({title:"Queries added",detail:Rh(d),tone:"positive",dedupeKey:`discovery:promote:${d.sessionId}`,dedupeMode:"replace"})},onError:d=>{Se({title:"Could not add queries",detail:d instanceof Error?d.message:"Could not add queries from this run.",tone:"negative"})}}),f=v??p,k=j.data??null,O=(k?.queriesByBucket.cited.length??0)+(k?.queriesByBucket.aspirational.length??0),q=l.useMemo(()=>(v?.probes??[]).slice(0,30),[v?.probes]);async function A(){try{const d=await c.refetch();if(d.error)throw d.error;const y=d.data?.length??0;Se({title:"Discovery sessions refreshed",detail:`${y} recent session${y===1?"":"s"} loaded.`,tone:"positive",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}catch(d){Se({title:"Discovery refresh failed",detail:d instanceof Error?d.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:J()?"Generate customer questions and check whether your site is already visible.":"Generate customer questions, check current visibility, then choose what to track."})]}),e.jsxs(P,{type:"button",variant:"outline",size:"sm",disabled:c.isFetching,onClick:()=>{A()},children:[e.jsx(Qn,{className:`size-3.5 ${c.isFetching?"animate-spin":""}`,"aria-hidden":"true"}),"Refresh"]})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[360px_minmax(0,1fr)]",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 1"}),e.jsx("h3",{children:"Describe your customer"})]}),e.jsx(oe,{tone:"neutral",children:"Runs on Gemini"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm text-secondary",children:"Who is your ideal customer?"}),e.jsx("textarea",{className:"mt-1 min-h-24 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",placeholder:"e.g. Small e-commerce stores that want AI-powered customer support. Leave blank to use the customer profile saved on this project.",value:i,onChange:d=>r(d.target.value)})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm text-secondary",children:"How many questions to test"}),e.jsx("input",{className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none",inputMode:"numeric",value:o,onChange:d=>m(d.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."})]}),!J()&&e.jsxs(Ye,{type:"button",size:"sm",disabled:b.isPending,onClick:()=>b.mutate(),children:[e.jsx(Hn,{size:14}),b.isPending?"Starting…":"Find queries"]})]})]}),e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Recent runs"})]}),c.isFetching&&e.jsx(oe,{tone:"neutral",children:"Loading"})]}),h.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No discovery runs yet. Describe your customer above to start your first one."}):e.jsx("div",{className:"space-y-2",children:h.map(d=>e.jsxs("button",{type:"button",className:`w-full rounded-md border px-3 py-2 text-left transition-colors ${n===d.id?"border-mono-600 bg-bg-elevated/70":"border-default bg-bg/40 hover:border-strong hover:bg-bg-elevated/40"}`,onClick:()=>a(d.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:ba(d.id)}),e.jsx(oe,{tone:_i(d.status),children:d.status})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-sm text-secondary",children:[e.jsxs("span",{children:["Cited queries ",d.citedCount??0]}),e.jsxs("span",{children:["Worth tracking ",d.aspirationalCount??0]}),e.jsxs("span",{children:["Skip ",d.wastedCount??0]})]})]},d.id))})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(pe,{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:f?ba(f.id):"No run selected"})]}),f&&e.jsx(oe,{tone:_i(f.status),children:f.status})]}),f?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(vs,{label:"Questions tested",value:f.probeCount??0}),e.jsx(vs,{label:"Cited queries",value:f.citedCount??0,tone:"positive"}),e.jsx(vs,{label:"Worth tracking",value:f.aspirationalCount??0,tone:"caution"}),e.jsx(vs,{label:"Skip",value:f.wastedCount??0,tone:"negative"})]}),f.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:f.error}),f.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:f.warning}),f.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:f.icpDescription})]}),f.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:f.competitorMap.slice(0,8).map(d=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[d.domain," ",e.jsx("span",{className:"text-muted",children:d.hits})]},d.domain))})]})]}):e.jsx("p",{className:"text-sm text-secondary",children:"Start a run above, or pick one from Recent runs to see its progress."})]}),f?.status==="completed"&&e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 2"}),e.jsx("h3",{children:"Choose queries to track"})]}),!J()&&e.jsxs(Ye,{type:"button",size:"sm",disabled:g.isPending||O===0,onClick:()=>g.mutate(void 0),children:[e.jsx(Lr,{size:14}),g.isPending?"Adding…":"Add recommended queries"]})]}),j.isLoading?e.jsx("p",{className:"text-sm text-muted",children:"Loading recommendations…"}):k?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(vs,{label:"Queries to add",value:O,tone:"positive"}),e.jsx(vs,{label:"Cited queries",value:k.queriesByBucket.cited.length,tone:"positive"}),e.jsx(vs,{label:"Worth tracking",value:k.queriesByBucket.aspirational.length,tone:"caution"}),e.jsx(vs,{label:"Skip",value:k.queriesByBucket["wasted-surface"].length,tone:"negative"})]}),e.jsx("p",{className:"text-sm leading-6 text-secondary",children:"Adds Cited queries and Worth tracking queries, plus recurring competitor sites. Skip items remain available for review only."}),k.suggestedCompetitors.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-secondary",children:"Competitor sites that will be added"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:k.suggestedCompetitors.map(d=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[d.domain," ",e.jsx("span",{className:"text-muted",children:d.hits})]},d.domain))})]})]}):e.jsx("p",{className:"text-sm text-muted",children:"No recommendations available for this run."})]}),e.jsxs(pe,{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"})]}),u.isFetching&&e.jsx(oe,{tone:"neutral",children:"Loading"})]}),q.length===0?e.jsx("p",{className:"text-sm text-muted",children:"Results show up here once the run starts testing questions."}):e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Question"}),e.jsx("th",{children:"Result"}),e.jsx("th",{children:"Sites cited"})]})}),e.jsx("tbody",{children:q.map(d=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:d.query}),e.jsx("td",{children:e.jsx(oe,{tone:kh(d.bucket),children:Ph(d.bucket)})}),e.jsx("td",{className:"text-secondary",children:d.citedDomains.length>0?d.citedDomains.slice(0,3).join(", "):"-"})]},d.id))})]})})]})]})]})]})}function vs({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 _i(t){return t==="completed"?"positive":t==="failed"?"negative":Ga.has(t)?"caution":"neutral"}function kh(t){return t==="cited"?"positive":t==="aspirational"?"caution":t==="wasted-surface"?"negative":"neutral"}const Ah={cited:"Cited queries",aspirational:"Worth tracking","wasted-surface":"Skip"};function Ph(t){return t?Ah[t]:"Not classified"}function ba(t){return t.length>8?t.slice(0,8):t}function Rh(t){const s=t.promoted.queries.length,n=t.promoted.competitors.length,a=t.skipped.queries.length+t.skipped.competitors.length;return`${s} quer${s===1?"y":"ies"} and ${n} competitor${n===1?"":"s"} added${a>0?`; ${a} already tracked`:""}.`}async function Ui(t,s,n){await Promise.all([ft(t,"discovery"),t.invalidateQueries({queryKey:Hl({client:U})})])}function Bi(t){return`${(t*100).toFixed(1)}%`}function Ih({projectName:t}){const[s,n]=l.useState("changes"),[a,i]=l.useState(null),[r,o]=l.useState(null),m=Ie({...Wl({client:U,path:{name:t},query:{limit:30}}),enabled:s==="health"}),c=Ie({...Yl({client:U,path:{name:t},query:{kind:"answer-visibility",limit:100}}),enabled:s==="compare"}),h=(c.data??[]).filter(f=>(f.status==="completed"||f.status==="partial")&&f.trigger!=="probe").reverse(),p=r??h[0]?.id??"",u=a??h.find(f=>f.id!==p)?.id??"",v=!!(u&&p&&u!==p),j=Ie({...Xl({client:U,path:{name:t},query:{run1:u,run2:p}}),enabled:s==="compare"&&v}),b=m.data??[],g=j.data?.diff.filter(f=>f.changed||f.visibilityChanged)??[];return e.jsxs("div",{className:"mt-6",children:[e.jsx("div",{className:"filter-row",role:"tablist","aria-label":"Project history views",children:[["changes","Changes"],["health","Coverage history"],["compare","Compare runs"]].map(([f,k])=>e.jsx("button",{type:"button",role:"tab","aria-selected":s===f,className:`filter-chip ${s===f?"filter-chip-active":""}`,onClick:()=>n(f),children:k},f))}),s==="changes"?e.jsx(iu,{projectName:t}):null,s==="health"?e.jsxs("section",{className:"mt-6","aria-labelledby":"coverage-history-heading",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Query evidence"}),e.jsx("h2",{id:"coverage-history-heading",children:"Mention and citation coverage"}),e.jsx("p",{className:"supporting-copy mt-1",children:"Independent answer-text mentions and source citations across completed sweeps."})]}),m.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Loading coverage history…"}):null,!m.isLoading&&b.length===0?e.jsxs(pe,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No coverage history yet"}),e.jsx("p",{children:"Complete an answer visibility sweep to create the first snapshot."})]}):null,b.length>0?e.jsx("div",{className:"evidence-table-wrap mt-4",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"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:b.map(f=>e.jsxs("tr",{children:[e.jsx("td",{className:"whitespace-nowrap tabular-nums text-secondary",children:new Date(f.createdAt).toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[f.mentionedPairs,"/",f.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:Bi(f.overallMentionRate)}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[f.citedPairs,"/",f.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:Bi(f.overallCitedRate)})]},f.id))})]})}):null]}):null,s==="compare"?e.jsxs("section",{className:"mt-6","aria-labelledby":"compare-runs-heading",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Evidence diff"}),e.jsx("h2",{id:"compare-runs-heading",children:"Compare answer visibility runs"}),e.jsx("p",{className:"supporting-copy mt-1",children:"See which tracked queries changed mention or citation state between two sweeps."})]}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"text-xs text-muted",children:["Earlier run",e.jsx("select",{value:u,onChange:f=>i(f.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:h.map(f=>e.jsx("option",{value:f.id,children:new Date(f.createdAt).toLocaleString()},f.id))})]}),e.jsxs("label",{className:"text-xs text-muted",children:["Later run",e.jsx("select",{value:p,onChange:f=>o(f.target.value),className:"mt-1 min-h-11 w-full rounded-md border border-base bg-bg px-3 text-sm text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-600",children:h.map(f=>e.jsx("option",{value:f.id,children:new Date(f.createdAt).toLocaleString()},f.id))})]})]}),c.isLoading||j.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Comparing runs…"}):null,!c.isLoading&&h.length<2?e.jsxs(pe,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"Two completed sweeps are required"}),e.jsx("p",{children:"Run another answer visibility sweep before comparing historical evidence."})]}):null,j.data&&g.length===0?e.jsxs(pe,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No mention or citation changes"}),e.jsx("p",{children:"The selected sweeps have the same states for every comparable tracked query."})]}):null,g.length>0?e.jsx("div",{className:"evidence-table-wrap mt-4",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Citation"}),e.jsx("th",{children:"Mention"})]})}),e.jsx("tbody",{children:g.map(f=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:f.query??"Archived query"}),e.jsx("td",{children:e.jsxs(oe,{tone:f.changed?"caution":"neutral",children:[f.run1State??"none"," → ",f.run2State??"none"]})}),e.jsx("td",{children:e.jsxs(oe,{tone:f.visibilityChanged?"caution":"neutral",children:[f.run1MentionState??"none"," → ",f.run2MentionState??"none"]})})]},f.queryId??f.query??"unknown"))})]})}):null]}):null]})}const Vi={state:"not-connected",selection:null,snapshotCount:0,evidence:"No stored evidence yet.",lastSnapshotAt:null},$h={contract:null,assessment:null,googleAds:Vi,gtm:Vi,snapshots:[]};function Th(t){return t.contractSelectionRequired?"contract-selection-required":t.assessmentState==="loading"?"assessment-loading":t.assessmentState==="unavailable"?"assessment-unavailable":Eh(t)?"static-mismatch":t.assessment?.status??(t.contract?"configured":"not-configured")}function Mh(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 Lh(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 Dh(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 uo(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"&&qh(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 Eh(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome==="fail")}function qh(t){return t.assessment?.status==="configured"&&t.assessment.findings.some(s=>s.outcome!=="pass")}function mo(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 Oh(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 Gh(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 Ps(t){return t.length<=12?t:`…${t.slice(-10)}`}function Fh(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 _h(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 va={"ads-connection-missing":"Google Ads connection is available","ads-conversion-action-missing":"Google Ads conversion action exists and is enabled","ads-goal-missing":"Google Ads goal includes the conversion action","ads-goal-not-biddable":"Google Ads goal is available for bidding","ads-action-not-primary":"Google Ads action is primary","gtm-connection-missing":"Tag Manager connection is available","gtm-live-graph-missing":"Tag Manager configuration is available","gtm-tag-missing":"Required Tag Manager tag exists","gtm-tag-unrecognized":"Tag Manager tag type is supported","gtm-tag-paused":"Tag Manager tag is active","gtm-trigger-missing":"Required Tag Manager trigger is linked","gtm-variable-missing":"Required Tag Manager variable is linked","gtm-event-mismatch":"Tag Manager event matches the declaration","gtm-hostname-mismatch":"Tag Manager host matches the production site","gtm-value-mapping-missing":"Conversion value mapping is present","gtm-transaction-id-mapping-missing":"Transaction ID mapping is present","gtm-currency-mapping-missing":"Currency mapping is present","gtm-conversion-id-mismatch":"Google conversion ID matches","gtm-conversion-label-mismatch":"Google conversion label matches","runtime-event-not-observed":"Website event was observed","runtime-gtm-not-observed":"Tag Manager firing was observed","runtime-ads-not-observed":"Google Ads conversion was observed"};function Ki(t){return t.outcome==="pass"?{label:va[t.code],tone:"positive",outcome:"Pass"}:t.outcome==="fail"?{label:va[t.code],tone:"negative",outcome:"Fail"}:{label:va[t.code],tone:"caution",outcome:"Unknown"}}function Uh(t){return t.runtime.productionHosts.length>0?t.runtime.productionHosts.join(", "):"the declared production site"}function Bh(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 Vh(t){return t.provider==="google-ads"?"Google Ads":"Tag Manager"}function zi({label:t,connection:s,changeSelectionLabel:n,onChangeSelection:a,actionPending:i}){const r=mo(s.state),o=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(oe,{tone:r.tone,children:r.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}),o?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:o}):e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:[s.snapshotCount," stored ",s.snapshotCount===1?"snapshot":"snapshots",s.lastSnapshotAt?`, latest ${qt(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(Ye,{type:"button",variant:"outline",size:"sm",disabled:i,onClick:a,children:n}):e.jsx("span",{className:"text-sm text-secondary",children:"Use the next step above"})})]})}const Kh="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.",zh="Available once Google Ads and Tag Manager are connected.",Qh="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 Hh({workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:n,onChangeGtmSelection:a,actionPending:i,actionError:r}){const o=t.googleAds.state==="connected",m=t.gtm.state==="connected",c=t.googleAds.state==="unavailable",h=t.gtm.state==="unavailable",p=c||h||t.gtm.state==="unavailable",u={id:"retry-connection-status",label:"Retry connection status",detail:"Retry the stored connection reads before starting another provider action."},v=!o&&!m,j=[{title:"Google Ads",state:t.googleAds.state,ready:o,summary:t.googleAds.selection,changeLabel:"Change Google Ads account",onChange:n,action:c?u:Lh(t)},{title:"Tag Manager",state:t.gtm.state,ready:m,summary:t.gtm.selection,changeLabel:"Change Tag Manager container",onChange:a,action:h?u:Dh(t)}],b=o&&m&&!p?uo(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(Je,{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."})]}),v?e.jsx("p",{className:"mt-2 max-w-2xl text-sm leading-6 text-secondary",children:Qh}):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(Je,{text:Kh})]}),b&&s?e.jsx(Ye,{type:"button",disabled:i,onClick:()=>s(b.id),children:i?"Working…":b.label}):e.jsx("p",{className:"text-sm text-secondary",children:zh})]}),e.jsx("ul",{className:"flex flex-wrap items-center gap-x-6 gap-y-2 border-b border-default py-3",children:j.map(g=>{const f=g.ready?{label:"Ready",tone:"positive"}:mo(g.state),k=g.action;return e.jsxs("li",{className:"flex min-w-0 flex-wrap items-center gap-2 text-sm",children:[e.jsx("span",{className:"font-medium text-heading",children:g.title}),e.jsx(oe,{tone:f.tone,children:f.label}),g.summary?e.jsx("span",{className:"min-w-0 truncate text-secondary",children:g.summary}):null,k&&s?k.id==="retry-connection-status"?e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:i,onClick:()=>s(k.id),children:i?"Working…":k.label}):e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:i,onClick:()=>s(k.id),children:i?"Working…":k.label}):null,g.summary&&g.onChange?e.jsx(Ye,{type:"button",variant:"ghost",size:"sm","aria-label":g.changeLabel,disabled:i,onClick:g.onChange,children:"Change"}):null]},g.title)})}),r?e.jsx("p",{role:"alert",className:"mt-3 text-sm text-negative",children:r}):null]})]})}function Wh({workspace:t=$h,onPrimaryAction:s,actionPending:n=!1,actionError:a=null,contracts:i=[],selectedContractId:r=null,onSelectContract:o,contractError:m=null,onRetryContracts:c,onRetryEvidence:h,onChangeGoogleAdsSelection:p,onChangeGtmSelection:u,onAddContract:v}){const j=Th(t),b=Mh(j),g=uo(t),f=t.assessment?.findings??[],k=f.filter(d=>d.outcome!=="pass"),O=f.filter(d=>d.outcome==="pass"),q=k.some(d=>d.outcome==="fail")?"negative":"caution";return i.length===0&&t.contract===null&&!t.contractSelectionRequired&&m===null?e.jsx(Hh,{workspace:t,onPrimaryAction:s,onChangeGoogleAdsSelection:p,onChangeGtmSelection:u,actionPending:n,actionError:a}):e.jsxs("section",{className:"page-section","aria-labelledby":"conversion-integrity-title",children:[e.jsx("div",{className:"section-head mb-5",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow",children:"Google marketing"}),e.jsx("h2",{id:"conversion-integrity-title",className:"mt-1 text-xl font-semibold tracking-[-0.02em] text-heading",children:"Conversion Integrity"}),e.jsx("p",{className:"lede mt-2",children:"Follow one declared website event through Tag Manager, Google Ads, and the evidence Canonry can verify."})]})}),e.jsxs("div",{className:"flex flex-col gap-4 border-y border-default py-5 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(oe,{tone:b.tone,children:b.label}),t.assessment?.evaluatedAt?e.jsxs("span",{className:"text-[11px] text-muted",children:["Assessed ",qt(t.assessment.evaluatedAt)]}):null]}),e.jsx("p",{className:"supporting-copy mt-2 max-w-2xl",children:b.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(d=>e.jsxs("li",{className:"break-words",children:[Vh(d)," ",d.kind,", captured ",qt(d.capturedAt),e.jsxs("span",{className:"ml-1 font-mono text-[11px] text-muted",children:["(",d.id,")"]})]},d.id))})]}):null]}),e.jsxs("div",{className:"shrink-0 lg:max-w-xs",children:[s?g.id==="review-findings"||g.id==="review-runtime-verification"||g.id==="retry-connection-status"||g.id==="select-contract"||g.id==="retry-integrity"||g.id==="waiting-for-integrity"?e.jsx(P,{type:"button",disabled:n||g.id==="waiting-for-integrity",onClick:()=>s(g.id),children:n?"Working…":g.label}):e.jsx(Ye,{type:"button",disabled:n,onClick:()=>s(g.id),children:n?"Working…":g.label}):g.id==="review-findings"?e.jsx(P,{asChild:!0,type:"button",children:e.jsx("a",{href:"#conversion-integrity-findings",children:"Review findings"})}):j==="runtime-unverified"?e.jsx(P,{asChild:!0,type:"button",children:e.jsx("a",{href:"#conversion-integrity-runtime-guidance",children:"Review runtime verification"})}):null,e.jsx("p",{className:"mt-2 text-sm leading-5 text-secondary",children:g.detail}),a?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:a}):null]})]}),e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-contract-title",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Declared conversion"}),e.jsx("h3",{id:"conversion-integrity-contract-title",className:"min-w-0 break-words text-base font-semibold text-heading",children:t.contract?.name??(t.contractSelectionRequired?"Choose a conversion":"No conversion declared")})]}),i.length>0&&v?e.jsx(Ye,{type:"button",variant:"outline",size:"sm",disabled:n,onClick:v,children:"Add conversion"}):null]}),i.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:r??"",onChange:d=>o?.(d.target.value),children:[e.jsx("option",{value:"",children:"Choose a declared conversion"}),i.map(d=>e.jsx("option",{value:d.id,children:d.name},d.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:Fh(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:_h(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:Ps(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:Ps(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:Ps(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:Ps(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."}),m?e.jsxs("div",{role:"alert",className:"mt-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:m}),c?e.jsx(P,{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]}),k.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(oe,{tone:q,children:[k.length," ",k.length===1?"check":"checks"]})]}),e.jsx("ul",{className:"divide-y divide-default border-y border-default",children:k.map(d=>{const y=Ki(d);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:y.label}),e.jsx(oe,{tone:y.tone,children:y.outcome})]}),e.jsxs("p",{className:"mt-1 break-words text-sm text-secondary",children:["Related item: ",d.subject]}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",d.code]}),d.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",d.evidenceIds.join(", ")]}):null]},`${d.code}:${d.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(Je,{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(d=>{const y=Oh(d.key,j);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 ${y==="positive"?"bg-positive-fill":y==="caution"?"bg-caution-fill":y==="negative"?"bg-negative-fill":"bg-neutral-fill"}`}),e.jsx("span",{className:"text-sm font-medium text-heading",children:d.title})]}),e.jsx("p",{className:"text-sm text-secondary",children:d.detail}),e.jsx(oe,{tone:y,children:Gh(d.key,j)})]},d.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:[zi({label:"Google Ads",connection:t.googleAds,...t.googleAds.state==="connected"||t.googleAds.state==="stale"?{changeSelectionLabel:"Change Google Ads account",onChangeSelection:p}:{},actionPending:n}),zi({label:"Google Tag Manager",connection:t.gtm,...t.gtm.state==="connected"||t.gtm.state==="stale"?{changeSelectionLabel:"Change Tag Manager container",onChangeSelection:u}:{},actionPending:n})]})]})}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-caution",children:"Static API evidence does not prove that a browser tag fired or that Google Ads recorded a conversion."}),(t.googleAds.snapshotError||t.gtm.snapshotError)&&h?e.jsx(P,{type:"button",variant:"outline",className:"mt-3",onClick:h,children:"Retry evidence"}):null]}),t.snapshots.length>0?e.jsxs("section",{className:"page-section-divider","aria-labelledby":"conversion-integrity-snapshots-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Recent observations"}),e.jsx("h3",{id:"conversion-integrity-snapshots-title",className:"text-base font-semibold text-heading",children:"Latest sanitized snapshots"})]})}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("caption",{className:"sr-only",children:"Latest stored Google marketing snapshots"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Source"}),e.jsx("th",{scope:"col",children:"Observation"}),e.jsx("th",{scope:"col",children:"Captured"}),e.jsx("th",{scope:"col",children:"Identifier"})]})}),e.jsx("tbody",{children:t.snapshots.slice(0,5).map(d=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:d.provider==="google-ads"?"Google Ads":"Google Tag Manager"}),e.jsx("td",{className:"text-secondary",children:d.kind}),e.jsx("td",{className:"text-secondary",children:qt(d.capturedAt)}),e.jsx("td",{className:"font-mono text-[11px] text-muted",children:Ps(d.id)})]},d.id))})]})})]}):null,O.length>0?e.jsxs("details",{className:"inline-disclosure mt-8",children:[e.jsxs("summary",{children:[O.length," ",O.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:O.map(d=>{const y=Ki(d);return e.jsxs("tr",{children:[e.jsxs("td",{className:"text-secondary",children:[e.jsx("p",{children:y.label}),e.jsxs("p",{className:"mt-1 font-mono text-[11px] text-muted",children:["Diagnostic: ",d.code]}),d.evidenceIds.length>0?e.jsxs("p",{className:"mt-1 break-words font-mono text-[11px] text-muted",children:["Evidence: ",d.evidenceIds.join(", ")]}):null]}),e.jsx("td",{children:e.jsx(oe,{tone:y.tone,children:y.outcome})}),e.jsx("td",{className:"break-words text-secondary",children:d.subject})]},`${d.code}:${d.subject}`)})})]})})]}):null,j==="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 ",Uh(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:Ps(t.contract.gtm.tagId)})," fires with ",Bh(t.contract),"."]}),e.jsxs("li",{children:["Confirm Google Ads records the matching conversion action ",e.jsx("span",{className:"font-mono text-heading",children:Ps(t.contract.googleAds.conversionActionId)}),". Do not change the account or publish a Tag Manager version just to verify it."]})]})]}):null]})}const Rs=3e4,Qi={name:"",eventName:"",conversionActionId:"",conversionId:"",conversionLabel:"",campaignIds:"",tagId:"",triggerIds:"",variableIds:"",productionHosts:"",requireBiddableGoal:!0,requirePrimaryAction:!0,verificationRequired:!0,requireTransactionId:!0,requireValue:!0,requireCurrency:!0},Ct="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",zt="text-sm font-medium text-secondary";function Hi(t,s,n,a){return n?{snapshotCount:t,snapshotState:"unavailable",snapshotError:ut(a)}:s?{snapshotCount:t,snapshotState:"loading"}:{snapshotCount:t}}function Ln(t){return[...new Set(t.split(/[\n,]/).map(s=>s.trim()).filter(Boolean))]}function Yh(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 i=t.connection.selection.customerId;return i?{state:"stale",selection:`Selected customer ${i}`,...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 Xh(t,s,n){const a=[`Container ${t}`,`account ${s}`];return n&&a.push(`workspace ${n}`),a.join(" · ")}function Jh(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:Xh(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 Zh(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:Ln(t.campaignIds),requireBiddableGoal:t.requireBiddableGoal,requirePrimaryAction:t.requirePrimaryAction},gtm:{accountId:n.accountId,containerId:n.containerId,tagId:t.tagId.trim(),triggerIds:Ln(t.triggerIds),variableIds:Ln(t.variableIds)},runtime:{verificationRequired:t.verificationRequired,requireTransactionId:t.requireTransactionId,requireValue:t.requireValue,requireCurrency:t.requireCurrency,productionHosts:Ln(t.productionHosts)}}}function Wi(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 Dn(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 En(t,s,n){return t?"no longer accessible":n?"access not verified":s?"not in the current result":"checking access"}function qn({id:t,label:s,value:n,onChange:a,children:i,disabled:r=!1}){return e.jsxs("label",{htmlFor:t,className:zt,children:[s,e.jsx("select",{id:t,className:Ct,value:n,onChange:o=>a(o.target.value),disabled:r,children:i})]})}function Bs({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:i=>n(i.target.checked),className:"mt-0.5 size-4 rounded border-base bg-bg accent-mono-100"}),e.jsx("span",{children:a})]})}function Yi({providerLabel:t,disabled:s,onDisconnect:n}){const[a,i]=l.useState(!1),[r,o]=l.useState(!1),[m,c]=l.useState(null),h=l.useRef(null),p=l.useRef(null),u=l.useRef(!1);l.useEffect(()=>{const g=u.current;u.current=a,a?p.current?.focus():g&&h.current?.querySelector("button")?.focus()},[a]);function v(){c(null),i(!0)}function j(){c(null),i(!1)}async function b(){o(!0),c(null);try{await n()}catch(g){c(ut(g)),o(!1)}}return e.jsx("div",{ref:h,className:"mt-5 border-t border-subtle pt-4",children:a?e.jsxs("div",{role:"group","aria-label":`Confirm disconnect ${t}`,className:"max-w-2xl",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:"Remove Canonry's stored access and selection?"}),e.jsx("p",{className:"mt-1 text-sm leading-6 text-secondary",children:"Saved evidence and conversion contracts remain. New checks stop until you reconnect."}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(P,{ref:p,type:"button",variant:"outline",size:"sm",className:"min-h-11",disabled:r,onClick:j,children:"Keep connected"}),e.jsx(Ye,{type:"button",variant:"destructive",size:"sm",className:"min-h-11",disabled:s||r,onClick:()=>{b()},children:r?"Disconnecting…":`Disconnect ${t}`})]}),m?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:m}):null]}):e.jsxs(Ye,{type:"button",variant:"ghost",size:"sm",className:"min-h-11 text-negative hover:text-negative",disabled:s,onClick:v,children:["Disconnect ",t]})})}function Xi({id:t,label:s,options:n,synced:a,loading:i,failed:r,onRetry:o,emptyHint:m,value:c,onChange:h}){const p=n.some(g=>g.id===c),[u,v]=l.useState(!1),j=u||c!==""&&!p&&n.length>0,b=e.jsx("label",{htmlFor:t,className:zt,children:s});return i?e.jsxs("div",{children:[b,e.jsx("select",{id:t,className:Ct,disabled:!0,children:e.jsx("option",{children:"Loading…"})})]}):r?e.jsxs("div",{children:[b,e.jsx("input",{id:t,required:!0,className:Ct,value:c,onChange:g=>h(g.target.value)}),e.jsxs("p",{className:"mt-1 text-xs text-negative",children:["Could not load the list."," ",e.jsx("button",{type:"button",className:"text-link underline",onClick:o,children:"Retry"})]})]}):!a||n.length===0?e.jsxs("div",{children:[b,e.jsx("input",{id:t,required:!0,className:Ct,value:c,onChange:g=>h(g.target.value)}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:a?"Synced, but nothing to choose from yet.":m})]}):e.jsxs("div",{children:[b,j?e.jsx("input",{id:t,required:!0,className:Ct,value:c,onChange:g=>h(g.target.value)}):e.jsxs("select",{id:t,required:!0,className:Ct,value:c,onChange:g=>h(g.target.value),children:[e.jsxs("option",{value:"",children:["Select ",s.toLowerCase()]}),n.map(g=>e.jsxs("option",{value:g.id,children:[g.name,g.detail?` (${g.detail})`:"",g.active?"":" — inactive"]},g.id))]}),e.jsx("button",{type:"button",className:"mt-1 text-xs text-link",onClick:()=>{v(!j),h("")},children:j?"Choose from synced list":"Enter an ID manually"})]})}function ex({projectId:t,projectName:s}){const n=Ir(),[a,i]=l.useState(null),[r,o]=l.useState(null),[m,c]=l.useState(!1),[h,p]=l.useState(""),[u,v]=l.useState(null),[j,b]=l.useState(!1),[g,f]=l.useState(!1),[k,O]=l.useState(""),[q,A]=l.useState(""),[d,y]=l.useState(""),[S,V]=l.useState(""),[K,w]=l.useState(""),[T,F]=l.useState(!1),[$,H]=l.useState(Qi),[ye,ge]=l.useState(null),z=l.useRef(null),ee=Ie({...Jl({client:U,path:{name:s}}),staleTime:Rs}),ie=Ie({...Zl({client:U,path:{name:s}}),staleTime:Rs}),W=Ie({...ec({client:U,path:{name:s}}),staleTime:Rs}),B=Ie({...tc({client:U,path:{name:s}}),staleTime:Rs}),R=B.data,se=Ie({...sc({client:U,path:{name:s},query:{limit:5}}),staleTime:Rs}),le=Ie({...nc({client:U,path:{name:s},query:{limit:5}}),staleTime:Rs}),de=W.data??[],Ae=(ye?de.find(N=>N.id===ye)??null:null)??(de.length===1?de[0]??null:null),_=de.length>1&&!Ae,ae=Ie({...ac({client:U,path:{name:s,contractId:Ae?.id??""}}),enabled:!!Ae,staleTime:Rs}),Ne=Ie({...ic({client:U,path:{name:s}}),enabled:u==="google-ads"&&ee.data?.connected===!0,staleTime:0}),Le=Ie({...rc({client:U,path:{name:s}}),enabled:u==="gtm"&&ie.data?.connected===!0,staleTime:0}),Fe=Ie({...oc({client:U,path:{name:s,accountId:d}}),enabled:u==="gtm"&&!!d,staleTime:0}),Pe=Ie({...lc({client:U,path:{name:s,accountId:d,containerId:S}}),enabled:u==="gtm"&&!!d&&!!S,staleTime:0}),Qe=Et(cc({client:U})),ue=Et(dc({client:U})),we=Et(uc({client:U})),Ze=Et(mc({client:U})),_e=Et(hc({client:U})),He=Et(xc({client:U})),$e=Et(pc({client:U})),Ce=Et(gc({client:U})),E=Et(fc({client:U}));l.useEffect(()=>{if(u!=="google-ads"||j||!ee.isSuccess)return;const N=ee.data.connection?.selection;O(N?.customerId??""),A(N?.loginCustomerId??""),b(!0)},[j,ee.data,ee.isSuccess,u]),l.useEffect(()=>{if(u!=="gtm"||g||!ie.isSuccess)return;const N=ie.data.selection;y(N?.accountId??""),V(N?.containerId??""),w(N?.workspaceId??""),f(!0)},[g,ie.data,ie.isSuccess,u]),l.useEffect(()=>{!ye||!W.data||W.data.some(N=>N.id===ye)||ge(null)},[W.data,ye]);const M=l.useMemo(()=>{const N=se.data?.snapshots??[],re=le.data?.snapshots??[],at=[...N.map(Vt=>({id:Vt.id,provider:"google-ads",kind:Vt.kind,capturedAt:Vt.capturedAt})),...re.map(Vt=>({id:Vt.id,provider:"gtm",kind:Vt.kind,capturedAt:Vt.capturedAt}))].sort((Vt,Xt)=>Xt.capturedAt.localeCompare(Vt.capturedAt)).slice(0,5),Re=[],gt=ae.data?.googleAdsSnapshot,rs=ae.data?.gtmSnapshot;return gt&&Re.push({id:gt.id,provider:"google-ads",kind:gt.kind,capturedAt:gt.capturedAt}),rs&&Re.push({id:rs.id,provider:"gtm",kind:rs.kind,capturedAt:rs.capturedAt}),{contract:ae.data?.assessment.contract??Ae,assessment:ae.data?.assessment??null,contractSelectionRequired:_,assessmentState:Ae?ae.isError?"unavailable":ae.isLoading?"loading":void 0:void 0,assessmentError:ae.isError?ut(ae.error):null,googleAds:Yh(ee.data,Hi(se.data?.total??0,se.isLoading,se.isError,se.error),ee.isError),gtm:Jh(ie.data,Hi(le.data?.total??0,le.isLoading,le.isError,le.error),ie.isError),snapshots:at,assessmentEvidenceSnapshots:Re}},[Ae,_,se.data,se.error,se.isError,se.isLoading,ee.data,ee.isError,le.data,le.error,le.isError,le.isLoading,ie.data,ie.isError,ae.data,ae.error,ae.isError,ae.isLoading]),L=l.useSyncExternalStore(kr,Kn,Kn),je=Object.values(L.runs).some(N=>N.projectId===t&&(N.kind===Os["google-ads-sync"]||N.kind===Os["gtm-sync"])),qe=Qe.isPending||ue.isPending||we.isPending||Ze.isPending||_e.isPending||He.isPending||$e.isPending||Ce.isPending||E.isPending||je;async function Y(){await Promise.all([ee.refetch(),ie.refetch(),W.refetch(),se.refetch(),le.refetch(),B.refetch(),Ae?ae.refetch():Promise.resolve()])}async function Be(N){await Y();for(let re=0;re<10&&!N();re+=1)await new Promise(at=>setTimeout(at,1500)),await Y()}function mt(){const N=document.activeElement;z.current=N instanceof HTMLElement?N:null}function ot(N){if(typeof window<"u"&&typeof window.requestAnimationFrame=="function"){window.requestAnimationFrame(N);return}globalThis.setTimeout(N,0)}function De(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Oe(N){if(!N)return;!N.matches('a[href], button, input, select, textarea, [contenteditable="true"]')&&!N.hasAttribute("tabindex")&&(N.tabIndex=-1),N.focus({preventScroll:!0})}function xt(N,re=N){const at=document.getElementById(N);at instanceof HTMLDetailsElement&&(at.open=!0);const Re=at?.scrollIntoView;typeof Re=="function"&&Re.call(at,{behavior:De()?"auto":"smooth",block:"start"}),Oe(document.getElementById(re)??at)}function We(N,re){mt(),ot(()=>xt(N,re))}function Ve(){const N=z.current;z.current=null,N&&ot(()=>{N.isConnected&&N.focus({preventScroll:!0})})}function Te(){i(null),c(!1),Ve()}function jt(){i(null),v(null),Ve()}function Tt(){i(null),F(!1),Ve()}function Ue(){i(null),v(null),c(!0),We("google-ads-connect-panel","google-ads-connect-title")}function Ge(){i(null),O(""),A(""),b(!1),v("google-ads"),c(!1),We("google-ads-selection-panel","google-ads-selection-title")}function bt(){i(null),y(""),V(""),w(""),f(!1),v("gtm"),c(!1),We("gtm-selection-panel","gtm-selection-title")}function Ke(){i(null),F(!0),We("conversion-integrity-contract-form","conversion-integrity-contract-form-title")}function Nt(N,re){Cr({id:N.id,projectId:N.projectId,kind:N.kind,projectLabel:s,sourceAction:re}),Se({title:re==="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:${N.id}`,dedupeMode:"replace"})}async function kt(){ts(n),i(null);try{const N=await Qe.mutateAsync({path:{name:s},body:{provider:"google-ads",...h.trim()?{developerToken:h.trim()}:{}}});p(""),c(!1),o("Finish the Google Ads consent flow in the new window. Canonry will refresh stored status after it closes."),Wi(N.authorizationUrl,()=>{Y(),o(null),Ve()})}catch(N){i(ut(N))}}async function vt(){ts(n),i(null);try{const N=await ue.mutateAsync({path:{name:s},body:{provider:"gtm"}});o("Finish the Tag Manager consent flow in the new window. Canonry will refresh stored status after it closes."),Wi(N.authorizationUrl,()=>{Y(),o(null),Ve()})}catch(N){i(ut(N))}}async function At(){if(ts(n),!k){i("Select a Google Ads customer before saving.");return}i(null);try{await we.mutateAsync({path:{name:s},body:{customerId:k,...q.trim()?{loginCustomerId:q.trim()}:{}}}),v(null),Ve(),await Be(()=>ee.data?.selectedCustomer!=null)}catch(N){i(ut(N))}}async function lt(){if(ts(n),!d||!S){i("Select a Tag Manager account and container before saving.");return}i(null);try{await Ze.mutateAsync({path:{name:s},body:{accountId:d,containerId:S,...K?{workspaceId:K}:{}}}),v(null),Ve(),await Be(()=>ie.data?.status==="connected")}catch(N){i(ut(N))}}async function G(){ts(n),i(null),await $e.mutateAsync({path:{name:s}}),v(null),c(!1),O(""),A(""),b(!1),o(null),await Y(),Se({title:"Google Ads disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`google-ads-disconnected:${t}`,dedupeMode:"replace"}),z.current=null,ot(()=>Oe(document.getElementById("conversion-integrity-title")))}async function ke(){ts(n),i(null),await Ce.mutateAsync({path:{name:s}}),v(null),y(""),V(""),w(""),f(!1),o(null),await Y(),Se({title:"Tag Manager disconnected",detail:"Stored evidence and conversion contracts were retained.",tone:"neutral",dedupeKey:`gtm-disconnected:${t}`,dedupeMode:"replace"}),z.current=null,ot(()=>Oe(document.getElementById("conversion-integrity-title")))}async function fe(){ts(n),i(null);try{const N=await _e.mutateAsync({path:{name:s}});Nt(N,"google-ads-sync")}catch(N){i(ut(N))}}async function he(){ts(n),i(null);try{const N=await He.mutateAsync({path:{name:s}});Nt(N,"gtm-sync")}catch(N){i(ut(N))}}async function Mt(){ts(n),i(null);try{const N=await Promise.allSettled([_e.mutateAsync({path:{name:s}}),He.mutateAsync({path:{name:s}})]),[re,at]=N;re.status==="fulfilled"&&Nt(re.value,"google-ads-sync"),at.status==="fulfilled"&&Nt(at.value,"gtm-sync");const Re=N.find(gt=>gt.status==="rejected");if(Re?.status==="rejected")throw Re.reason}catch(N){i(ut(N))}}async function ct(){ts(n);const N=ee.data?.connection?.selection.customerId,re=ie.data?.selection;if(!N||!re?.accountId||!re.containerId){i("Select Google Ads and Tag Manager resources before declaring a conversion.");return}i(null);try{const at=await E.mutateAsync({path:{name:s},body:Zh($,N,{accountId:re.accountId,containerId:re.containerId})});H(Qi),F(!1),Ve(),(await W.refetch()).data?.some(gt=>gt.id===at.id)&&ge(at.id)}catch(at){i(ut(at))}}function Pt(N){switch(N){case"connect-google-ads":Ue();return;case"connect-gtm":mt(),vt();return;case"select-google-ads":Ge();return;case"select-gtm":bt();return;case"sync-google-ads":fe();return;case"sync-gtm":he();return;case"sync-static-evidence":Mt();return;case"declare-contract":Ke();return;case"review-findings":We("conversion-integrity-findings","conversion-integrity-findings");return;case"review-runtime-verification":We("conversion-integrity-runtime-guidance","conversion-integrity-runtime-title");return;case"retry-connection-status":Y();return;case"select-contract":We("conversion-integrity-contract-select","conversion-integrity-contract-select");return;case"retry-integrity":ae.refetch();return;case"waiting-for-integrity":return}}const Lt=Ne.data?.customers??[],Wt=Le.data?.accounts??[],Dt=Fe.data?.containers??[],is=Pe.data?.workspaces??[],nt=!!k&&!Lt.some(N=>N.customerId===k),ms=!!d&&!Wt.some(N=>N.id===d),wt=!!S&&!Dt.some(N=>N.id===S),hs=!!K&&!is.some(N=>N.id===K),Ot=nt&&Ne.isSuccess&&Ne.data.truncated===!1,Yt=ms&&Le.isSuccess&&Le.data.truncated===!1,Bt=wt&&Fe.isSuccess&&Fe.data.truncated===!1,et=hs&&Pe.isSuccess&&Pe.data.truncated===!1,xs=Yt||Bt||et,Gt=Yt?"The saved Tag Manager account is no longer accessible. Choose an available account before saving.":Bt?"The saved Tag Manager container is no longer accessible. Choose an available container before saving.":et?"The saved draft workspace is no longer accessible. Choose an available workspace or No draft workspace before saving.":null,St=En(Ot,Ne.data,Ne.isError),ps=En(Yt,Le.data,Le.isError),dt=En(Bt,Fe.data,Fe.isError),Zt=En(et,Pe.data,Pe.isError),C=Ne.isError?ut(Ne.error):null,be=Le.isError?ut(Le.error):Fe.isError?ut(Fe.error):Pe.isError?ut(Pe.error):null,ve=u==="google-ads"?C:u==="gtm"?be:null,I=Dn("customer",Ne.data,Lt.length),Q=Dn("account",Le.data,Wt.length),me=Dn("container",Fe.data,Dt.length),te=Dn("draft workspace",Pe.data,is.length),ne=Le.isError||Fe.isError||Pe.isError&&!!K,Ee=m||u!==null||T;function es(){Ne.refetch()}function pt(){if(Le.isError){Le.refetch();return}if(Fe.isError){Fe.refetch();return}Pe.isError&&Pe.refetch()}return ee.isLoading||ie.isLoading||W.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(N=>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"})]},N))}),e.jsx("p",{role:"status",className:"sr-only",children:"Loading conversion setup…"})]}):W.isError&&!W.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: ",ut(W.error)]}),e.jsx(P,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{W.refetch()},children:"Retry contracts"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Wh,{workspace:M,onPrimaryAction:Pt,actionPending:qe,actionError:Ee?null:a,contracts:de,selectedContractId:Ae?.id??null,onSelectContract:N=>ge(N||null),contractError:W.isError?ut(W.error):null,onRetryContracts:()=>{W.refetch()},onRetryEvidence:()=>{Promise.all([se.refetch(),le.refetch()])},onChangeGoogleAdsSelection:Ge,onChangeGtmSelection:bt,onAddContract:()=>Pt("declare-contract")}),r?e.jsx("p",{role:"status",className:"page-section text-sm text-secondary",children:r}):null,m?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:Me(async N=>{N.preventDefault(),await kt()}),children:[e.jsxs("label",{htmlFor:"google-ads-developer-token",className:zt,children:["Developer token",e.jsx("input",{id:"google-ads-developer-token",type:"password",autoComplete:"off",value:h,onChange:N=>p(N.target.value),className:Ct,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(Ye,{type:"submit",disabled:Qe.isPending,children:Qe.isPending?"Starting…":"Continue to Google"}),e.jsx(P,{type:"button",variant:"outline",onClick:Te,children:"Cancel"})]})]})]}):null,u==="google-ads"?e.jsxs("section",{id:"google-ads-selection-panel",className:"page-section-divider","aria-labelledby":"google-ads-selection-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Google Ads"}),e.jsx("h3",{id:"google-ads-selection-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Select customer context"})]})}),ve?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:ve}),e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:es,children:"Retry customer list"})]}):null,a?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:a}):null,Ot?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(qn,{id:"google-ads-customer",label:"Customer account",value:k,onChange:N=>{b(!0),O(N);const re=Lt.find(at=>at.customerId===N);A(re?.parentCustomerId??"")},disabled:Ne.isLoading,children:[e.jsx("option",{value:"",children:Ne.isLoading?"Loading accessible customers…":"Select a customer"}),nt?e.jsxs("option",{value:k,disabled:Ot,children:["Saved customer ",k," (",St,")"]}):null,Lt.map(N=>e.jsx("option",{value:N.customerId,children:N.descriptiveName??`Customer ${N.customerId}`},N.customerId))]}),e.jsxs("label",{htmlFor:"google-ads-login-customer",className:zt,children:["Manager account ID (optional)",e.jsx("input",{id:"google-ads-login-customer",className:Ct,value:q,onChange:N=>{b(!0),A(N.target.value)},placeholder:"Use only when a manager context is required"})]})]}),I?e.jsx("p",{role:"status",className:`mt-3 text-sm ${Ne.data?.truncated?"text-caution":"text-secondary"}`,children:I}):null,e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Ye,{type:"button",disabled:we.isPending||Ne.isLoading||Ne.isError||Ot||!k,onClick:Me(At),children:we.isPending?"Saving…":"Save customer selection"}),e.jsx(P,{type:"button",variant:"outline",onClick:jt,children:"Cancel"})]}),ee.data?.connected?e.jsx(Yi,{providerLabel:"Google Ads",disabled:qe,onDisconnect:G}):null]}):null,u==="gtm"?e.jsxs("section",{id:"gtm-selection-panel",className:"page-section-divider","aria-labelledby":"gtm-selection-title",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Google Tag Manager"}),e.jsx("h3",{id:"gtm-selection-title",tabIndex:-1,className:"text-base font-semibold text-heading",children:"Select container context"})]})}),ve?e.jsxs("div",{role:"alert",className:"mb-4 flex flex-wrap items-center gap-3 text-sm text-negative",children:[e.jsx("span",{children:ve}),e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:pt,children:Le.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,Gt?e.jsx("p",{role:"alert",className:"mb-4 text-sm text-negative",children:Gt}):null,e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-3",children:[e.jsxs(qn,{id:"gtm-account",label:"Account",value:d,onChange:N=>{f(!0),N!==d&&(V(""),w("")),y(N)},disabled:Le.isLoading,children:[e.jsx("option",{value:"",children:Le.isLoading?"Loading accounts…":"Select an account"}),ms?e.jsxs("option",{value:d,disabled:Yt,children:["Saved account ",d," (",ps,")"]}):null,Wt.map(N=>e.jsx("option",{value:N.id,children:N.name},N.id))]}),e.jsxs(qn,{id:"gtm-container",label:"Container",value:S,onChange:N=>{f(!0),N!==S&&w(""),V(N)},disabled:!d||Fe.isLoading,children:[e.jsx("option",{value:"",children:Fe.isLoading?"Loading containers…":"Select a container"}),wt?e.jsxs("option",{value:S,disabled:Bt,children:["Saved container ",S," (",dt,")"]}):null,Dt.map(N=>e.jsx("option",{value:N.id,children:N.name},N.id))]}),e.jsxs(qn,{id:"gtm-workspace",label:"Draft workspace (optional)",value:K,onChange:N=>{f(!0),w(N)},disabled:!S||Pe.isLoading,children:[e.jsx("option",{value:"",children:Pe.isLoading?"Loading workspaces…":"No draft workspace"}),hs?e.jsxs("option",{value:K,disabled:et,children:["Saved draft workspace ",K," (",Zt,")"]}):null,is.map(N=>e.jsx("option",{value:N.id,children:N.name},N.id))]})]}),e.jsxs("div",{className:"mt-3 grid max-w-3xl gap-2 text-sm sm:grid-cols-3",children:[Q?e.jsx("p",{role:"status",className:Le.data?.truncated?"text-caution":"text-secondary",children:Q}):null,me?e.jsx("p",{role:"status",className:Fe.data?.truncated?"text-caution":"text-secondary",children:me}):null,te?e.jsx("p",{role:"status",className:Pe.data?.truncated?"text-caution":"text-secondary",children:te}):null]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[e.jsx(Ye,{type:"button",disabled:Ze.isPending||Le.isLoading||Fe.isLoading||Pe.isLoading&&!!K||ne||xs||!d||!S,onClick:Me(lt),children:Ze.isPending?"Saving…":"Save container selection"}),e.jsx(P,{type:"button",variant:"outline",onClick:jt,children:"Cancel"})]}),ie.data?.connected?e.jsx(Yi,{providerLabel:"Tag Manager",disabled:qe,onDisconnect:ke}):null]}):null,T?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:Me(async N=>{N.preventDefault(),await ct()}),children:[e.jsxs("div",{className:"grid max-w-3xl gap-4 sm:grid-cols-2",children:[e.jsxs("label",{htmlFor:"contract-name",className:zt,children:["Conversion name",e.jsx("input",{id:"contract-name",required:!0,maxLength:120,className:Ct,value:$.name,onChange:N=>H(re=>({...re,name:N.target.value})),placeholder:"Booking completed"})]}),e.jsxs("label",{htmlFor:"contract-event-name",className:zt,children:["Website event",e.jsx("input",{id:"contract-event-name",required:!0,className:Ct,value:$.eventName,onChange:N=>H(re=>({...re,eventName:N.target.value})),placeholder:"booking_complete"})]}),e.jsx(Xi,{id:"contract-conversion-action",label:"Google Ads conversion action",options:R?.googleAds.conversionActions??[],synced:R?.googleAds.syncedAt!=null,loading:B.isLoading,failed:B.isError,onRetry:()=>{B.refetch()},emptyHint:"Run a Google Ads sync to list conversion actions.",value:$.conversionActionId,onChange:N=>H(re=>({...re,conversionActionId:N}))}),e.jsx(Xi,{id:"contract-gtm-tag",label:"Tag Manager tag",options:R?.gtm.tags??[],synced:R?.gtm.syncedAt!=null,loading:B.isLoading,failed:B.isError,onRetry:()=>{B.refetch()},emptyHint:"Run a Tag Manager sync to list tags.",value:$.tagId,onChange:N=>H(re=>({...re,tagId:N}))})]}),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:zt,children:["Google conversion ID (optional)",e.jsx("input",{id:"contract-conversion-id",className:Ct,value:$.conversionId,onChange:N=>H(re=>({...re,conversionId:N.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-conversion-label",className:zt,children:["Google conversion label (optional)",e.jsx("input",{id:"contract-conversion-label",className:Ct,value:$.conversionLabel,onChange:N=>H(re=>({...re,conversionLabel:N.target.value}))})]}),e.jsxs("label",{htmlFor:"contract-trigger-ids",className:zt,children:["Trigger IDs",e.jsx("input",{id:"contract-trigger-ids",className:Ct,value:$.triggerIds,onChange:N=>H(re=>({...re,triggerIds:N.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-variable-ids",className:zt,children:["Variable IDs",e.jsx("input",{id:"contract-variable-ids",className:Ct,value:$.variableIds,onChange:N=>H(re=>({...re,variableIds:N.target.value})),placeholder:"Comma-separated, optional"})]}),e.jsxs("label",{htmlFor:"contract-campaign-ids",className:zt,children:["Campaign IDs",e.jsx("input",{id:"contract-campaign-ids",className:Ct,value:$.campaignIds,onChange:N=>H(re=>({...re,campaignIds:N.target.value})),placeholder:"Optional campaign-specific goal checks"})]}),e.jsxs("label",{htmlFor:"contract-production-hosts",className:zt,children:["Production hosts",e.jsx("input",{id:"contract-production-hosts",className:Ct,value:$.productionHosts,onChange:N=>H(re=>({...re,productionHosts:N.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(Bs,{id:"contract-primary-action",checked:$.requirePrimaryAction,onChange:N=>H(re=>({...re,requirePrimaryAction:N})),children:"Google Ads action is primary"}),e.jsx(Bs,{id:"contract-biddable-goal",checked:$.requireBiddableGoal,onChange:N=>H(re=>({...re,requireBiddableGoal:N})),children:"Google Ads goal is biddable"}),e.jsx(Bs,{id:"contract-runtime-verification",checked:$.verificationRequired,onChange:N=>H(re=>({...re,verificationRequired:N})),children:"Runtime proof is required"}),e.jsx(Bs,{id:"contract-transaction-id",checked:$.requireTransactionId,onChange:N=>H(re=>({...re,requireTransactionId:N})),children:"Transaction ID is required"}),e.jsx(Bs,{id:"contract-value",checked:$.requireValue,onChange:N=>H(re=>({...re,requireValue:N})),children:"Conversion value is required"}),e.jsx(Bs,{id:"contract-currency",checked:$.requireCurrency,onChange:N=>H(re=>({...re,requireCurrency:N})),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(Ye,{type:"submit",disabled:E.isPending,children:E.isPending?"Saving…":"Save conversion contract"}),e.jsx(P,{type:"button",variant:"outline",onClick:Tt,children:"Cancel"})]})]})]}):null]})}const tx=6e4,sx=["7d","14d","30d"],Qa="not available",nx='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%.',ax="No Google Ads snapshot stored yet",ix="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.",rx="No closed days yet",ox="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.",lx={"insufficient-history":"Period change is hidden: the stored snapshot does not cover a prior period of equal length yet."},ys=new Intl.NumberFormat(void 0,{maximumFractionDigits:0}),ya=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}),ho=new Intl.NumberFormat(void 0,{maximumFractionDigits:1}),cx=new Intl.NumberFormat(void 0,{minimumFractionDigits:2,maximumFractionDigits:2});function Vs(t,s){return t===null||!Number.isFinite(t)?Qa:s===null?cx.format(t/1e6):vu(t,s)}function ja(t){if(t===null||!Number.isFinite(t))return Qa;const s=t*100;return s>0&&s<.1?"<0.1%":`${ho.format(s)}%`}function dx(t,s){if(t===null||!Number.isFinite(t))return`${Qa} 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%":`${ho.format(n)}%`;return`${t>0?"↑":"↓"} ${a} vs prior ${s}d`}function ux(t){return t==="enabled"?"positive":t==="paused"?"caution":"neutral"}function mx(t){return t==="enabled"?"Enabled":t==="paused"?"Paused":t==="removed"?"Removed":"Unknown"}function hx(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 xx({projectName:t}){const[s,n]=l.useState("14d"),[a,i]=l.useState(()=>new Set(["costMicros","conversions"])),r=Ie({...bc({client:U,path:{name:t},query:{window:s}}),staleTime:tx}),o=r.data,m=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(Je,{text:nx})]}),o?.source?e.jsxs("p",{className:"text-xs text-muted",children:[Ut(o.startDate)," to ",Ut(o.endDate)," · ",o.days," closed ",o.days===1?"day":"days"]}):null]}),e.jsx(to,{windows:sx,value:s,onChange:n,label:"Google Ads time period"})]});if(r.isLoading)return e.jsxs("section",{className:"page-section","aria-busy":"true","aria-labelledby":"google-ads-performance-title",children:[m,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(d=>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"})]},d))}),e.jsx("p",{role:"status",className:"sr-only",children:"Loading Google Ads performance…"})]});if(r.isError||!o)return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[m,e.jsxs("p",{role:"alert",className:"mt-4 text-sm text-negative",children:["Could not load Google Ads performance: ",ut(r.error)]}),e.jsx(P,{type:"button",variant:"outline",className:"mt-3",onClick:()=>{r.refetch()},children:"Retry performance"})]});const{totals:c,daily:h,campaigns:p,comparison:u,comparisonUnavailableReason:v,source:j}=o;if(!j){const d=v==="insufficient-history";return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[m,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:d?rx:ax}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-secondary",children:d?ox:ix})]})]})}const b=j.currencyCode,g=j.campaignsInInventory>0&&j.campaignsQueried<j.campaignsInInventory?{queried:j.campaignsQueried,inInventory:j.campaignsInInventory}:null,f=c.costMicros>0&&c.conversions===0,k=[{key:"spend",comparable:!0,label:"Spend",value:Vs(c.costMicros,b),change:u?.change.costMicros??null,direction:"none",seriesKey:"costMicros"},{key:"conversions",comparable:!0,label:"Conversions",value:ya.format(c.conversions),change:u?.change.conversions??null,direction:"up-good",seriesKey:"conversions"},{key:"cost-per-conversion",label:"Cost / conv.",value:f?"no conversions":Vs(c.costPerConversionMicros,b),change:null,comparable:!1,direction:"down-good",seriesKey:null},{key:"conversion-rate",comparable:!0,label:"Conv. rate",value:ja(c.conversionRate),change:u?.change.conversionRate??null,direction:"up-good",seriesKey:null}],O=[{key:"clicks",label:"Clicks",value:ys.format(c.clicks),seriesKey:"clicks"},{key:"impressions",label:"Impressions",value:ys.format(c.impressions),seriesKey:"impressions"},{key:"ctr",label:"CTR",value:ja(c.ctr),seriesKey:null},{key:"cpc",label:"CPC",value:Vs(c.cpcMicros,b),seriesKey:null}],q={costMicros:{label:"Spend",color:rt[1],axisId:"spend",formatValue:d=>Vs(d,b)},conversions:{label:"Conversions",color:rt[0],axisId:"conversions",formatValue:d=>ya.format(d)},clicks:{label:"Clicks",color:rt[2],axisId:"clicks",formatValue:d=>ys.format(d)},impressions:{label:"Impressions",color:rt[3],axisId:"impressions",formatValue:d=>ys.format(d)}},A=[...a].map(d=>({dataKey:d,...q[d]}));return e.jsxs("section",{className:"page-section","aria-labelledby":"google-ads-performance-title",children:[m,g!==null?e.jsxs("p",{role:"status",className:"mt-3 text-sm text-caution",children:["Totals cover ",ys.format(g.queried)," of"," ",ys.format(g.inInventory)," campaigns, so they are a subset of the account."]}):null,j.truncated?e.jsx("p",{role:"status",className:"mt-3 text-sm text-caution",children:"The provider returned a bounded result, so some rows are missing from the figures below."}):null,!u&&v==="insufficient-history"?e.jsx("p",{className:"mt-3 text-sm text-secondary",children:lx["insufficient-history"]}):null,e.jsx("div",{className:"mt-4 grid grid-cols-2 gap-2 lg:grid-cols-4",children:k.map(d=>{const y=d.seriesKey!==null&&a.has(d.seriesKey),S=y&&a.size===1,V=e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[d.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:y?q[d.seriesKey].color:"var(--color-mono-600)"}}):null,d.label]}),e.jsx("span",{className:"mt-0.5 block text-lg tabular-nums text-strong",children:d.value}),u&&d.comparable?e.jsx("span",{className:`block text-[11px] tabular-nums ${hx(d.change,d.direction)}`,children:dx(d.change,u.days)}):e.jsx("span",{className:"block text-[11px] text-muted",children:d.comparable?`no prior ${s} period stored`:" "})]});return d.seriesKey===null?e.jsx("div",{className:"rounded-md border border-subtle bg-surface-subtle px-3 py-2",children:V},d.key):e.jsx("button",{type:"button","aria-pressed":y,disabled:S,onClick:()=>i(K=>{const w=new Set(K);return w.has(d.seriesKey)?w.delete(d.seriesKey):w.add(d.seriesKey),w.size===0?K:w}),className:`rounded-md border px-3 py-2 text-left transition-colors ${y?"border-strong bg-surface-active":"border-subtle bg-surface-subtle hover:bg-surface-hover"} ${S?"cursor-default":""}`,children:V},d.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:O.map(d=>{const y=d.seriesKey!==null&&a.has(d.seriesKey),S=y&&a.size===1,V=e.jsxs(e.Fragment,{children:[e.jsxs("dt",{className:"flex items-center gap-1.5 text-xs text-secondary",children:[d.seriesKey?e.jsx("span",{"aria-hidden":"true",className:"size-1.5 shrink-0 rounded-full",style:{backgroundColor:y?q[d.seriesKey].color:"var(--color-mono-600)"}}):null,d.label]}),e.jsx("dd",{className:"text-sm tabular-nums text-strong",children:d.value})]});return d.seriesKey===null?e.jsx("div",{className:"flex items-baseline gap-1.5",children:V},d.key):e.jsx("button",{type:"button","aria-pressed":y,disabled:S,onClick:()=>i(K=>{const w=new Set(K);return w.has(d.seriesKey)?w.delete(d.seriesKey):w.add(d.seriesKey),w.size===0?K:w}),className:`flex items-baseline gap-1.5 rounded px-1 -mx-1 ${S?"cursor-default":"hover:bg-surface-hover"}`,children:V},d.key)})}),e.jsxs("div",{className:"mt-4",children:[e.jsx(Er,{data:h,xKey:"date",series:A,xTickFormatter:gn,labelFormatter:Ut}),e.jsx("ul",{className:"sr-only",children:h.map(d=>e.jsxs("li",{children:[Ut(d.date),":"," ",A.map(y=>`${y.label} ${q[y.dataKey].formatValue(d[y.dataKey])}`).join(", "),d.origin==="filled"?", no delivery reported":""]},d.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:p.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"text-secondary",children:"No campaign delivered in this window."})}):p.map(d=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-xs truncate text-strong",title:d.name??d.campaignId,children:d.name??e.jsx("span",{className:"font-mono text-secondary",children:d.campaignId})}),e.jsx("td",{children:e.jsx(oe,{tone:ux(d.status),children:mx(d.status)})}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:ys.format(d.totals.impressions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:ys.format(d.totals.clicks)}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:Vs(d.totals.costMicros,b)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:ya.format(d.totals.conversions)}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:ja(d.totals.ctr)}),e.jsx("td",{className:"text-right tabular-nums",children:d.totals.costMicros>0&&d.totals.conversions===0?e.jsx(oe,{tone:"caution",children:"no conversions"}):e.jsx("span",{className:"text-secondary",children:Vs(d.totals.costPerConversionMicros,b)})})]},d.campaignId))})]})}),e.jsxs("p",{className:"mt-3 text-[11px] text-muted",children:["Snapshot ",Ss(us(j.capturedAt))," · ","customer ",j.customerId," · ","latest closed day ",Ut(j.asOfDate),j.openDate?e.jsxs(e.Fragment,{children:[" · ",Ut(j.openDate)," still open, excluded"]}):null,j.timeZone?e.jsxs(e.Fragment,{children:[" · ","days close in ",j.timeZone]}):null]})]})]})}const Na=20,cs=50,px=50,gx=50;function Ha(t){return t==="viewer"}function Wa(t){return t?.status==="unavailable"}function xo(t,s,n){return n?t.includes(s)?[...t]:[...t,s]:t.filter(a=>a!==s)}function po(t,s){const n=new Map(s.map(i=>[i.id,i.label])),a=t.map(i=>n.get(i)).filter(i=>!!i);return a.length===0?"Not applied":a.length>3?`${a.length} Properties`:a.join(", ")}function On(t,s,n){if(t.kind==="all")return s.map(r=>r.id);if(t.kind==="specific")return s.filter(r=>t.propertyIds.includes(r.id)).map(r=>r.id);const a=new Set(t.groupIds),i=new Set(n.filter(r=>a.has(r.id)).flatMap(r=>r.propertyIds));return s.filter(r=>i.has(r.id)).map(r=>r.id)}function fx(t,s,n){if(t.kind==="all")return`all ${n} ${n===1?"Property":"Properties"}`;if(t.kind==="specific")return n===1?"1 Property":`${n} Properties`;const a=t.groupIds.map(i=>s.find(r=>r.id===i)?.name).filter(i=>!!i);return a.length===0?"selected groups":a.join(" + ")}function wa(t,s){const n=new Set(s.map(i=>i.id)),a=t.propertyIds.filter(i=>n.has(i)).length;return`${t.name} · ${a===1?"1 Property":`${a} Properties`}`}function Ji(t){return t==="matched"?"positive":t==="duplicate"?"neutral":t==="ambiguous"||t==="proposed"||t==="excluded"?"caution":"negative"}function Zi(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 Gn(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 Fa(t){return t.state==="missing"||t.source==="unavailable-tracked-query"||!t.source}function Sa(t){return Fa(t)?"Unavailable tracked query":t.text?.trim()||"Unavailable tracked query"}function _a({properties:t,selectedPropertyIds:s,onSelectedPropertyIdsChange:n,legend:a,showBulkActions:i=!0}){const[r,o]=l.useState(""),[m,c]=l.useState(!1),h=r.trim().toLocaleLowerCase(),p=h?t.filter(b=>b.label.toLocaleLowerCase().includes(h)):t,u=m?p:p.slice(0,px),v=u.length<p.length;function j(){const b=new Set([...s,...u.map(g=>g.id)]);n(t.filter(g=>b.has(g.id)).map(g=>g.id))}return e.jsxs("fieldset",{children:[e.jsx("legend",{className:"text-sm font-medium text-heading",children:a}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-end justify-between gap-3",children:[e.jsxs("label",{className:"block min-w-48 flex-1",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:"Search Properties"}),e.jsx("input",{type:"search",value:r,onChange:b=>o(b.currentTarget.value),className:"mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400"})]}),i?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:u.length===0,onClick:j,children:"Select all shown"}),e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:s.length===0,onClick:()=>n([]),children:"Clear selection"})]}):null]}),p.length===0?e.jsx("p",{className:"mt-3 text-sm text-secondary",children:"No Properties match this search."}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"mt-3 text-sm text-secondary",children:["Showing ",u.length," of ",p.length," Properties"]}),e.jsx("div",{className:"mt-2 max-h-96 divide-y divide-default overflow-y-auto border-y border-default",children:u.map(b=>{const g=s.includes(b.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 ${b.label}`,checked:g,type:"checkbox",onChange:f=>n(xo(s,b.id,f.currentTarget.checked))}),e.jsx("span",{children:b.label})]}),b.urlCount===void 0?null:e.jsxs("span",{className:"tabular-nums text-secondary",children:[b.urlCount," URLs"]})]},b.id)})}),v?e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",onClick:()=>c(!0),children:"Show all Properties"}):null]})]})}function Ya(){return e.jsxs("div",{className:"flex items-center gap-2 text-sm text-secondary",children:[e.jsx(oe,{tone:"neutral",children:"Viewer access"}),e.jsx("span",{children:"You can inspect this setup."})]})}function Xa({message:t}){return e.jsxs("div",{role:"status",className:"border-y border-caution-800/40 bg-caution-950/20 py-4 text-sm text-caution",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oe,{tone:"caution",children:"Unavailable"}),e.jsx("h4",{className:"font-medium",children:"Measurement setup unavailable"})]}),e.jsx("p",{className:"mt-2 max-w-2xl text-secondary",children:t})]})}function bx({value:t}){const[s,n]=l.useState(0),[a,i]=l.useState(0),[r,o]=l.useState(null),m=t.preview,c=m?.counts.needsAttention??0,h=m?.rows.filter(S=>S.status==="matched")??[],p=m?.rows??[],u=p.filter(S=>S.status!=="matched"),v=Math.max(1,Math.ceil(p.length/cs)),j=Math.min(s,v-1),b=p.slice(j*cs,(j+1)*cs),g=Math.max(1,Math.ceil(u.length/cs)),f=Math.min(a,g-1),k=u.slice(f*cs,(f+1)*cs),O=t.csv.trim().length>0&&!t.isReviewing&&!t.isApplying,q=h.length>0&&!t.isApplying,A=m!==null&&r===m.previewChecksum,d=u.length>0&&f===g-1;l.useEffect(()=>{n(0),i(0),o(null)},[m?.previewChecksum]);async function y(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=>{y(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(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!O,onClick:()=>{t.onReview()},children:t.isReviewing?"Reviewing CSV…":"Review CSV"}),e.jsx("span",{className:"text-sm text-secondary",children:"Use columns named property and group. URL is optional."})]}),t.error?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:t.error}):null,t.notice?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:t.notice}):null]}),m?e.jsxs("div",{className:"mt-4 border-t border-default pt-4","aria-live":"polite",children:[e.jsx("h5",{className:"text-sm font-medium text-heading",children:"Review group membership"}),e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:[m.counts.matchedRows," matched · ",m.counts.groupsReady," group",m.counts.groupsReady===1?"":"s"," ready",c>0?` · ${c} need${c===1?"s":""} attention`:""]}),m.groupChanges.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"Groups and memberships ready to apply"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Change"}),e.jsx("th",{children:"Properties"}),e.jsx("th",{children:"New memberships"})]})}),e.jsx("tbody",{children:m.groupChanges.map(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,m.rows.length>0?e.jsxs("details",{className:"mt-3 border-y border-default py-3",children:[e.jsxs("summary",{className:"flex min-h-11 cursor-pointer items-center text-sm font-medium text-heading",children:["Review CSV rows (",m.counts.dataRows,")"]}),e.jsx("div",{className:"mt-3 overflow-x-auto border-y border-default",children:e.jsxs("table",{className:"evidence-table min-w-[620px]",children:[e.jsx("caption",{className:"sr-only",children:"CSV group membership review"}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Row"}),e.jsx("th",{children:"Property"}),e.jsx("th",{children:"Group"}),e.jsx("th",{children:"Status"})]})}),e.jsx("tbody",{children:b.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(oe,{tone:Ji(S.status),children:Zi(S.status)}),Gn(S)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:Gn(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 ",j+1," of ",v," · ",m.rows.length," rows"]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:j===0,onClick:()=>n(S=>Math.max(0,S-1)),children:"Previous 50 rows"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:j===v-1,onClick:()=>n(S=>Math.min(v-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:k.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(oe,{tone:Ji(S.status),children:Zi(S.status)}),Gn(S)?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:Gn(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 ",f+1," of ",g]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:f===0,onClick:()=>i(S=>Math.max(0,S-1)),children:"Previous 50 exceptions"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:f===g-1,onClick:()=>i(S=>Math.min(g-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:A,disabled:t.isApplying||!d,onChange:S=>o(S.currentTarget.checked?m.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(P,{type:"button",size:"sm",variant:"outline",className:"mt-3 min-h-11",disabled:!q||!A,onClick:()=>{t.onApply(h.map(S=>S.dataRow))},children:t.isApplying?"Applying groups…":`Apply ${h.length} matched row${h.length===1?"":"s"}`})]}):e.jsx(P,{type:"button",className:"mt-3 min-h-11",disabled:!q,onClick:()=>{t.onApply(h.map(S=>S.dataRow))},children:t.isApplying?"Creating groups…":`Create ${m.counts.groupsReady} group${m.counts.groupsReady===1?"":"s"} with ${h.length} membership${h.length===1?"":"s"}`})]}):null]})}const vx="—";function yx({access:t,availability:s,properties:n,queries:a,selectedQueryIds:i,isApplying:r=!1,isBusy:o=!1,canContinue:m=!0,onSelectedQueryIdsChange:c,onApplySelectedQueries:h,onClearQueryAssignments:p,onRemoveQuery:u,onCreateQueries:v,onCreateAndPairQuestions:j,isCreatingQueries:b=!1,createQueriesError:g=null,onManageProjectQueries:f,groups:k,audience:O,onAudienceChange:q,assignmentImpact:A=null,isPreviewingAssignmentImpact:d=!1,assignmentImpactError:y=null,onRetryAssignmentImpact:S,assignmentNotice:V=null,onReplaceAssignments:K,isReplacingAssignments:w=!1,onBack:T,onContinue:F}){const[$,H]=l.useState(""),[ye,ge]=l.useState(!1),[z,ee]=l.useState(!1),[ie,W]=l.useState(""),[B,R]=l.useState(""),[se,le]=l.useState(null);if(Wa(s))return e.jsx("section",{"aria-label":"Queries",children:e.jsx(Xa,{message:s.message})});const de=Ha(t),X=O,Ae=q,_=On(X,n,k),ae=_.length,Ne=ae>0&&i.length>0&&!r&&!o&&!d&&A!==null&&y===null,Le=p??u,Fe=$.trim().toLocaleLowerCase(),Pe=Fe?a.filter(L=>Sa(L).toLocaleLowerCase().includes(Fe)):a,Qe=Pe.filter(L=>(L.propertyIds?.length??0)===0),ue=z?Qe:Pe,we=ye?ue:ue.slice(0,gx),Ze=we.filter(L=>!Fa(L)),_e=[...new Set(ie.split(`
|
|
5
|
+
`).map(L=>L.trim()).filter(Boolean))],He=[...B.matchAll(/\{([a-z][\w-]*)\}/gi)].map(L=>L[1]),$e=n.filter(L=>_.includes(L.id)),Ce=He.length===0||B.trim()===""?[]:$e.map(L=>({propertyId:L.id,text:He.reduce((je,qe)=>je.replaceAll(`{${qe}}`,L.label),B.trim())})),E=[...new Set(Ce.map(L=>L.text))];function M(){const L=new Set([...i,...Ze.map(je=>je.id)]);c(a.filter(je=>L.has(je.id)).map(je=>je.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."})]})}),de?e.jsx(Ya,{}):null,de?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:L=>{const je=L.currentTarget.value;je==="all"?Ae({kind:"all"}):je==="specific"?Ae({kind:"specific",propertyIds:[]}):je.startsWith("group:")&&Ae({kind:"groups",groupIds:[je.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]}),k.length>0?e.jsx("optgroup",{label:"Groups",children:k.map(L=>{const je=On({kind:"groups",groupIds:[L.id]},n,k).length;return e.jsx("option",{value:`group:${L.id}`,disabled:je===0,children:wa(L,n)},L.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(L=>{const je=k.find(qe=>qe.id===L);return je?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:[wa(je,n),e.jsx("button",{type:"button","aria-label":`Remove ${je.name}`,className:"-my-px -mr-2 ml-1 inline-flex min-h-11 min-w-11 items-center justify-center rounded text-secondary outline-none hover:text-heading focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>{const qe=X.groupIds.filter(Y=>Y!==je.id);Ae(qe.length>0?{kind:"groups",groupIds:qe}:{kind:"all"})},children:"×"})]},je.id):null})}),k.some(L=>!X.groupIds.includes(L.id)&&On({kind:"groups",groupIds:[L.id]},n,k).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:L=>{L.currentTarget.value&&Ae({kind:"groups",groupIds:[...X.groupIds,L.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"}),k.filter(L=>!X.groupIds.includes(L.id)).map(L=>{const je=On({kind:"groups",groupIds:[L.id]},n,k).length;return e.jsx("option",{value:L.id,disabled:je===0,children:wa(L,n)},L.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(_a,{legend:"Specific Properties",properties:n,selectedPropertyIds:X.propertyIds,showBulkActions:!1,onSelectedPropertyIdsChange:L=>{Ae({kind:"specific",propertyIds:L})}})}):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."})]}),de||!v?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:ie,onChange:L=>W(L.currentTarget.value),placeholder:`best apartments in dallas
|
|
6
|
+
luxury apartments atlanta
|
|
7
|
+
pet friendly apartments austin`}),g?e.jsx("p",{role:"alert",className:"mt-2 text-sm text-negative",children:g}):null,e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:_e.length===0||b||o,onClick:()=>{Promise.resolve(v(_e)).then(()=>W(""),()=>{})},children:b?"Adding…":`Add ${_e.length||""} ${_e.length===1?"query":"queries"}`.replace(" "," ")}),f?e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:o,onClick:f,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:B,onChange:L=>R(L.target.value),placeholder:"apartments near {property}"}),B.trim()===""?null:He.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."]}):$e.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:[E.length," ",E.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:E.slice(0,3).map(L=>e.jsx("li",{className:"text-sm text-strong",children:L},L))}),E.length>3?e.jsxs("p",{className:"mt-1 mb-0 text-sm text-secondary",children:["and ",E.length-3," more"]}):null]}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"mt-2 min-h-11",disabled:Ce.length===0||b||o||!j,onClick:()=>{j&&Promise.resolve(j(Ce)).then(()=>R(""),()=>{})},children:b?"Adding…":`Add ${Ce.length||""} ${Ce.length===1?"query":"queries"}`.replace(" "," ")}),Ce.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"," ",Ce.length," assignment",Ce.length===1?"":"s","."]}):null]})]})]}),de?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(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:Ze.length===0,onClick:M,children:"Select all shown queries"}),e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:i.length===0,onClick:()=>c([]),children:"Clear query selection"}),e.jsx(P,{type:"button",size:"sm",className:"min-h-11",disabled:!Ne,onClick:()=>{h({queryIds:i,propertyIds:_,...X.kind==="groups"?{groupIds:X.groupIds}:{}})},children:r?"Assigning queries…":`Assign ${i.length||""} ${i.length===1?"query":"queries"} to ${fx(X,k,ae)}`.replace(" "," ")}),e.jsxs("div",{className:"min-h-[2.75rem]",children:[d?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Calculating assignment impact…"}):null,A?e.jsxs("p",{className:"text-sm text-secondary",children:[i.length," ",i.length===1?"query":"queries"," → ",A.assignmentCount," Property assignment",A.assignmentCount===1?"":"s"," · ",A.addedAssignments," new, ",A.alreadyPresentAssignments," already assigned"," · ",A.fullRunProviderCalls," provider request",A.fullRunProviderCalls===1?"":"s"," per full run"," · ",A.addedProviderCalls," new",X.kind==="groups"?` · ${A.resolvedPropertyCount} unique ${A.resolvedPropertyCount===1?"Property":"Properties"}${A.overlapCount>0?`, ${A.overlapCount} in overlapping groups`:""}`:"",". Existing assignments stay in place."]}):y?e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("p",{role:"alert",className:"text-sm text-negative",children:y}),S?e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:S,children:"Retry impact"}):null,T?e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:T,children:"Back to Groups"}):null]}):e.jsxs("p",{className:"text-sm text-secondary",children:[i.length," ",i.length===1?"query":"queries"," × ",ae," Properties = ",i.length*ae," assignments"]})]}),V?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:V}):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:$,onChange:L=>{H(L.currentTarget.value),ge(!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 ",we.length," of ",ue.length," queries,"," ",Pe.length-Qe.length," of ",Pe.length," applied"]}),de||Qe.length===0?null:e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>{ee(L=>!L),ge(!1)},children:z?"Show all queries":`Show the ${Qe.length} not applied`})]})]}):null,we.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:[de?null:e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Select query"})}),e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Properties"}),de?null:e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Clear query assignments"})})]})}),e.jsx("tbody",{children:we.map(L=>{const je=Fa(L),qe=Sa(L),Y=i.includes(L.id),Be=(L.propertyIds?.length??0)>0;return e.jsxs("tr",{children:[de?null:je?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 ${qe}`,checked:Y,type:"checkbox",onChange:mt=>c(xo(i,L.id,mt.currentTarget.checked)),className:"size-6 accent-accent"})})}),e.jsx("td",{children:e.jsx("p",{className:"font-medium text-heading",children:qe})}),e.jsx("td",{className:"text-secondary",children:po(L.propertyIds??[],n)}),de?null:e.jsx("td",{className:"text-right",children:Be?e.jsxs("div",{className:"flex flex-wrap justify-end gap-1",children:[K?e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:o||w,onClick:()=>le({queryId:L.id,propertyIds:[...L.propertyIds??[]]}),"aria-label":`Replace query assignments for ${qe}`,children:"Replace assignments"}):null,e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:o,onClick:()=>{Le(L.id)},"aria-label":`Clear query assignments for ${qe}`,children:"Clear assignments"})]}):null})]},L.id)})})]})}):a.length>0?e.jsx("p",{className:"text-sm text-secondary",children:"No queries match this search."}):null,de||!se?null:(()=>{const L=a.find(Y=>Y.id===se.queryId),je=L?Sa(L):"this query",qe=se.propertyIds.filter(Y=>n.some(Be=>Be.id===Y));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 “",je,"”."]}),e.jsx("div",{className:"mt-3",children:e.jsx(_a,{legend:"Properties for this query",properties:n,selectedPropertyIds:qe,onSelectedPropertyIdsChange:Y=>le(Be=>Be&&{...Be,propertyIds:[...Y]})})}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-3",children:[e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:w||o,onClick:()=>le(null),children:"Keep current assignments"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:qe.length===0||w||o||!K,onClick:()=>{K&&Promise.resolve(K({queryId:se.queryId,propertyIds:qe}))},children:w?"Replacing assignments…":`Replace with ${qe.length} ${qe.length===1?"Property":"Properties"}`})]})]})})(),we.length<ue.length?e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:()=>ge(!0),children:"Show all queries"}):null,de?null:e.jsxs(e.Fragment,{children:[m?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 ${T?"justify-between":"justify-end"}`,children:[T?e.jsx(P,{type:"button",variant:"outline",className:"min-h-11",disabled:o,onClick:T,children:"Back"}):null,e.jsx(P,{type:"button",variant:Ne?"outline":"default",className:"min-h-11",disabled:!m||o,onClick:F,children:"Continue"})]})]})]})}function jx({access:t,availability:s,properties:n,groups:a,groupDraft:i,isSaving:r=!1,onGroupDraftChange:o,onSaveGroup:m,onEditGroup:c,onRemoveGroup:h,onClearGroupDraft:p,membershipImport:u,onBack:v,onContinue:j}){if(Wa(s))return e.jsx("section",{"aria-label":"Groups",children:e.jsx(Xa,{message:s.message})});const b=Ha(t),g=i.name.trim().length>0&&i.propertyIds.length>0&&!r,f=n.filter(A=>i.propertyIds.includes(A.id)).length,k=i.name.trim().length>0||i.propertyIds.length>0||i.competitorDomains.trim().length>0,O=!b&&(c!==void 0||h!==void 0);function q(){if(p){p();return}o({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."})]})}),b?e.jsx(Ya,{}):null,b||!u?null:e.jsx(bx,{value:u}),b?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:i.name,onChange:A=>o({...i,name:A.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:[f," of ",n.length," Properties selected"]}),e.jsx("div",{className:"pt-3",children:e.jsx(_a,{legend:"Properties in this group",properties:n,selectedPropertyIds:i.propertyIds,onSelectedPropertyIdsChange:A=>o({...i,propertyIds:A})})})]}),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:i.competitorDomains,onChange:A=>o({...i,competitorDomains:A.currentTarget.value}),placeholder:"one.example, two.example"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",disabled:!g,onClick:()=>{m(i)},children:r?"Saving group…":"Save group"}),e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11",disabled:!k,onClick:q,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."})]}),k?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"}),O?e.jsx("th",{children:"Actions"}):null]})}),e.jsx("tbody",{children:a.map(A=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:A.name}),e.jsx("td",{className:"text-secondary",children:po(A.propertyIds,n)}),e.jsx("td",{className:"text-secondary",children:A.competitors.length>0?A.competitors.join(", "):"None"}),O?e.jsx("td",{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[c?e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11","aria-label":`Edit ${A.name}`,onClick:()=>c(A),children:"Edit"}):null,h?e.jsx(P,{type:"button",size:"sm",variant:"ghost",className:"min-h-11","aria-label":`Remove ${A.name}`,onClick:()=>{h(A.id)},children:"Remove"}):null]})}):null]},A.id))})]})}),a.length===0?e.jsx("p",{className:"text-sm text-secondary",children:"No groups have been added."}):null,b?null:e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${v?"justify-between":"justify-end"}`,children:[v?e.jsx(P,{type:"button",variant:"outline",className:"min-h-11",onClick:v,children:"Back"}):null,e.jsx(P,{type:"button",className:"min-h-11",disabled:k,onClick:j,children:a.length===0&&!k?"Continue without groups":"Continue"})]})]})}function Nx({access:t,availability:s,counts:n,flaggedExceptions:a,sitemapReview:i,onBack:r,onReviewChanges:o,isReviewing:m=!1,canReviewChanges:c=!0,reviewedChanges:h,reviewChangesError:p,canPublish:u,isPublishing:v=!1,onPublish:j}){const[b,g]=l.useState(Na),[f,k]=l.useState(Na),[O,q]=l.useState(Na);if(Wa(s))return e.jsx("section",{"aria-label":"Review and publish",children:e.jsx(Xa,{message:s.message})});const A=Ha(t),d=i?.items??[],y=i?.coverageItems??[],S=d.slice(0,b),V=y.slice(0,f),K=a.slice(0,O),w=o!==void 0,T=h!=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."})]})}),A?e.jsx(Ya,{}):null,i?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"}),i.exceptionCount>0?e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:[i.exceptionCount," sitemap ",i.exceptionCount===1?"entry needs":"entries need"," review."]}):null,i.coverageReviewCount>0?e.jsxs("p",{className:"mt-1 text-sm text-secondary",children:[i.coverageReviewCount," ",i.coverageReviewCount===1?"Property has":"Properties have"," URL coverage changes."]}):null]}),i.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 (",i.exceptionCount,")"]}),d.length>0?e.jsx("ul",{className:"mt-3 space-y-3 text-sm",children:S.map(F=>e.jsxs("li",{children:[e.jsx("p",{className:"font-medium text-primary",children:F.url}),e.jsx("p",{className:"mt-1 text-secondary",children:F.reason})]},`${F.url}-${F.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 ",d.length]}),S.length<d.length?e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>g(F=>F+cs),children:"Show next 50 URLs"}):null]})]}):null,A?e.jsx("p",{className:"text-sm text-secondary",children:"An editor must finish this review before publishing."}):e.jsxs(e.Fragment,{children:[i.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 ",i.coverageReviewCount," changed ",i.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 (",i.coverageReviewCount,")"]}),V.length>0?e.jsxs("div",{className:"mt-3 space-y-4",children:[V.map(F=>e.jsxs("section",{"aria-label":`${F.property} URL changes`,children:[e.jsx("h5",{className:"text-sm font-medium text-primary",children:F.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:F.savedUrls.map($=>e.jsx("li",{className:"break-all text-secondary",children:$},$))})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-secondary",children:"Current sitemap URLs"}),F.currentSitemapUrls.length>0?e.jsx("ul",{className:"mt-1 space-y-1",children:F.currentSitemapUrls.map($=>e.jsx("li",{className:"break-all text-secondary",children:$},$))}):e.jsx("p",{className:"mt-1 text-secondary",children:"No matching URL was found."})]})]})]},F.property)),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",V.length," of ",y.length]}),V.length<y.length?e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>k(F=>F+cs),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:i.coverageResolution==="keep-existing",onChange:()=>i.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:i.coverageResolution==="replace-with-imported",onChange:()=>i.onCoverageResolutionChange("replace-with-imported")}),"Use current sitemap URLs"]})]}):null,e.jsx(P,{type:"button",className:"min-h-11",onClick:()=>{i.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??vx})]})})]})}),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,h?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:h.title}),h.items.length>0?e.jsx("ul",{className:"mt-3 list-disc space-y-2 pl-5 text-sm text-secondary",children:h.items.map((F,$)=>e.jsx("li",{children:F},`${F}-${$}`))}):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:K.map(F=>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:F.title}),F.detail?e.jsx("p",{className:"mt-1 text-sm text-secondary",children:F.detail}):null]}),e.jsx(oe,{tone:F.tone??"caution",children:"Needs attention"})]},F.id))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-secondary",children:[e.jsxs("span",{children:["Showing ",K.length," of ",a.length]}),K.length<a.length?e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"min-h-11",onClick:()=>q(F=>F+cs),children:"Show next 50 exceptions"}):null]})]})]}),A?null:e.jsxs(e.Fragment,{children:[w&&p?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:p}):null,e.jsxs("div",{className:`flex flex-wrap items-center gap-3 ${r?"justify-between":"justify-end"}`,children:[r?e.jsx(P,{type:"button",variant:"outline",className:"min-h-11",onClick:r,children:"Back"}):null,o!==void 0&&!T?e.jsx(P,{type:"button",className:"min-h-11",disabled:m||!c,onClick:()=>{o()},children:m?"Reviewing changes…":"Review changes"}):e.jsx(P,{type:"button",className:"min-h-11",disabled:!u||v,onClick:()=>{j()},children:v?"Publishing setup…":"Publish setup"})]})]})]})}const wx={proposed:{label:"New",tone:"caution"},confirmed:{label:"Included",tone:"positive"},excluded:{label:"Excluded",tone:"neutral"}};function Sx(t){return t.trim().toLocaleLowerCase()}function Cx(t,s){return s?`${t.name} ${(t.urls??[t.url]).join(" ")}`.toLocaleLowerCase().includes(s):!0}function kx({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 Ax({canEdit:t,draft:s,onDraftChange:n,onReviewSitemap:a,reviewState:i}){const r=!t||i==="reviewing",o=r||!s.sitemapUrl.trim()||!s.examplePropertyUrl.trim()&&!s.propertyPathPattern.trim();function m(c,h){n({...s,[c]:h})}return e.jsxs("section",{"aria-labelledby":"advanced-measurement-import-heading","aria-busy":i==="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(oe,{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(),!o&&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:r,onChange:c=>m("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:r,onChange:c=>m("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:r,onChange:c=>m("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:r,onChange:c=>m("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:r,onChange:c=>m("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:r,onChange:c=>m("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:r,onChange:c=>m("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(P,{type:"submit",disabled:o,children:i==="reviewing"?"Reviewing sitemap…":"Review sitemap"})]})]})}function Px({canEdit:t,properties:s,propertiesState:n,propertiesSearch:a,onPropertiesSearchChange:i,selectedPropertyIds:r,onSelectedPropertyIdsChange:o,onContinue:m,isContinuing:c=!1,onRetryProperties:h,onReturnToImport:p,maxVisibleProperties:u,onShowAllProperties:v}){const j=Sx(a),b=s.filter(K=>Cx(K,j)),g=Math.max(1,u??b.length),f=b.slice(0,g),k=new Set(r),O=s.filter(K=>k.has(K.id)).map(K=>K.id),q=f.length<b.length;function A(K){const w=new Set(K);o(s.filter(T=>w.has(T.id)).map(T=>T.id))}function d(K,w){if(!t||c)return;const T=new Set(O);w?T.add(K):T.delete(K),A(T)}function y(){!t||c||A([...O,...f.map(K=>K.id)])}function S(){!t||c||o([])}function V(){!t||c||O.length===0||m(O)}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(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:h,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(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:h,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(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:!t,onClick:p,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:K=>i(K.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(P,{type:"button",variant:"outline",size:"sm",disabled:c,onClick:y,children:"Select all shown"}),e.jsx(P,{type:"button",variant:"ghost",size:"sm",disabled:c||O.length===0,onClick:S,children:"Clear selection"})]}):null]}),b.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(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:!t,onClick:p,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 ",f.length," of ",b.length," Properties"]}),e.jsxs("p",{children:[O.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:f.map(K=>{const w=wx[K.state];return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"px-3 py-3 font-medium text-heading",children:K.name}),e.jsx("td",{className:"max-w-96 px-3 py-3 font-mono text-xs text-secondary",children:e.jsx(kx,{property:K})}),e.jsx("td",{className:"px-3 py-3",children:e.jsx(oe,{tone:w.tone,children:w.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 ${K.name}`,checked:O.includes(K.id),disabled:c,onChange:T=>d(K.id,T.target.checked),className:"size-6 accent-accent"})})}):null]},K.id)})})]})}),q&&v?e.jsx(P,{type:"button",variant:"outline",size:"sm",className:"mt-3",disabled:c,onClick:v,children:"Show all Properties"}):null]}),t?e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-3",children:[e.jsx(P,{type:"button",variant:"ghost",disabled:c,onClick:p,children:"Back"}),e.jsx(P,{type:"button",disabled:c||O.length===0,onClick:V,children:c?"Saving Properties…":"Continue"})]}):null]}):null]})}function Rx(t){return t.activeStep==="import"?e.jsx(Ax,{canEdit:t.canEdit,draft:t.importDraft,onDraftChange:t.onImportDraftChange,onReviewSitemap:t.onReviewSitemap,reviewState:t.reviewState}):e.jsx(Px,{...t})}const Ix=[{id:"import",label:"Import"},{id:"properties",label:"Properties"},{id:"groups",label:"Groups"},{id:"queries",label:"Queries"},{id:"review",label:"Review and publish"}];function $x({currentStep:t,hasDraft:s,canEdit:n,onDiscard:a,onStepChange:i,children:r}){const o=l.useRef(null),m=l.useRef(null),c=l.useRef(null),h=l.useRef(null),p=l.useRef(!1),[u,v]=l.useState(!1);return l.useEffect(()=>{s||v(!1)},[s]),l.useEffect(()=>{const j=p.current;p.current=u,u?c.current?.focus():j&&h.current?.focus()},[u]),l.useEffect(()=>{const j=o.current;if(o.current=t,j===null||j===t)return;const b=m.current?.querySelector('h1, h2, h3, [role="heading"]');b&&(b.tabIndex=-1,b.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(oe,{tone:"caution",children:"Unpublished changes"}),n&&a?u?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(P,{ref:c,type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>v(!1),children:"Keep editing"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:a,children:"Discard unpublished changes"})]}):e.jsx(P,{ref:h,type:"button",size:"sm",variant:"ghost",className:"min-h-11",onClick:()=>v(!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:Ix.map(j=>e.jsx("li",{children:i?e.jsx("button",{type:"button","aria-current":t===j.id?"step":void 0,onClick:()=>i(j.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===j.id?"border-strong text-heading":"border-transparent text-secondary hover:text-heading"}`,children:j.label}):e.jsx("span",{"aria-current":t===j.id?"step":void 0,className:`block min-h-11 border-b-2 px-1 py-3 text-sm font-medium ${t===j.id?"border-strong text-heading":"border-transparent text-secondary"}`,children:j.label})},j.id))})}),e.jsx("div",{ref:m,children:r})]})}function Tx(t){const s=t.canEdit?"editor":"viewer";return t.currentStep==="import"||t.currentStep==="properties"?e.jsx(Rx,{...t.importProperties,activeStep:t.currentStep,canEdit:t.canEdit}):t.currentStep==="queries"?e.jsx(yx,{...t.queries,access:s,onManageProjectQueries:t.onManageProjectQueries}):t.currentStep==="groups"?e.jsx(jx,{...t.groups,access:s}):"review"in t?e.jsx(Nx,{...t.review,access:s}):null}function Fn(t){return e.jsx($x,{currentStep:t.currentStep,hasDraft:t.hasDraft,canEdit:t.canEdit,onDiscard:t.onDiscard,onStepChange:t.onStepChange,children:Tx(t)})}function go(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`web-${Date.now()}-${Math.random().toString(36).slice(2)}`}function It(t){return{"If-Match":t,"Idempotency-Key":go()}}function Is(t){return t instanceof Zs&&(t.statusCode===404||t.statusCode===409||t.statusCode===412)}function Kt(t,s){return t instanceof Zs?s:(t instanceof Error?t.message.trim():"")||s}function Mx(t){const s="Could not calculate assignment impact.";if(!(t instanceof Zs)||t.code!=="VALIDATION_ERROR")return s;const n=t.message.trim();return t.details?.displayToOperator===!0&&n?n:s}const Lx={loadSetup:t=>it(()=>Fc({client:U,path:{name:t}})),loadDraft:t=>it(()=>Gc({client:U,path:{name:t}})),createDraft:(t,s)=>it(()=>Oc({client:U,path:{name:t},headers:{"Idempotency-Key":go()},body:{expectedActiveRevision:s}})),importSitemap:(t,s,n)=>it(()=>qc({client:U,path:{name:t},headers:It(s),body:n})),applySitemapSelection:(t,s,n,a)=>it(()=>Ec({client:U,path:{name:t},headers:It(s),body:{selections:n,selectedTargetKeys:a}})),previewAssignments:(t,s)=>it(()=>Dc({client:U,path:{name:t},body:s})),applyAssignments:(t,s,n)=>it(()=>Lc({client:U,path:{name:t},headers:It(s),body:n})),replaceAssignments:(t,s,n)=>it(()=>Mc({client:U,path:{name:t},headers:It(s),body:n})),applyPairedAssignments:(t,s,n)=>it(()=>Tc({client:U,path:{name:t},headers:It(s),body:{pairs:n}})),removeAssignment:(t,s,n,a)=>it(()=>$c({client:U,path:{name:t},headers:It(s),body:{targetKeys:n,queryId:a}})),excludeTarget:(t,s,n)=>it(()=>Ic({client:U,path:{name:t},headers:It(s),body:{targetKey:n,cleanup:"assignments-and-group-memberships"}})),upsertTarget:(t,s,n)=>it(()=>Rc({client:U,path:{name:t},headers:It(s),body:{target:n}})),upsertGroup:(t,s,n)=>it(()=>Pc({client:U,path:{name:t},headers:It(s),body:{group:n}})),removeGroup:(t,s,n)=>it(()=>Ac({client:U,path:{name:t},headers:It(s),body:{groupKey:n}})),upsertCompetitor:(t,s,n)=>it(()=>kc({client:U,path:{name:t},headers:It(s),body:n})),removeCompetitor:(t,s,n,a)=>it(()=>Cc({client:U,path:{name:t},headers:It(s),body:{groupKey:n,competitorKey:a}})),previewGroupMembership:(t,s)=>it(()=>Sc({client:U,path:{name:t},body:s})),applyGroupMembership:(t,s,n)=>it(()=>wc({client:U,path:{name:t},headers:It(s),body:n})),compilePreview:t=>it(()=>Nc({client:U,path:{name:t}})),diffPreview:t=>it(()=>jc({client:U,path:{name:t}})),publish:(t,s,n)=>it(()=>yc({client:U,path:{name:t},headers:It(s),body:n})),discard:(t,s)=>it(()=>vc({client:U,path:{name:t},headers:It(s)}))},er={sitemapUrl:"",examplePropertyUrl:"",preferredHost:"",propertyPathPattern:"",additionalHost:"",additionalPathPattern:"",excludedPaths:""},ln={name:"",propertyIds:[],competitorDomains:""},tr=50;function un(t){const s=t.trim();if(!s)return null;try{return new URL(s.includes("://")?s:`https://${s}`).hostname.toLocaleLowerCase()}catch{return null}}function Dx(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 sr(t){const s=t.propertyPathPattern.trim();if(s){const i=(s.startsWith("/")?s:`/${s}`).split("/").slice(1);if(i.filter(o=>o==="*"||o==="{slug}").length!==1||i.some(o=>o.includes("*")&&o!=="*"))throw new Error("Property URL pattern must contain exactly one * or {slug} segment.");return`/${i.map(o=>o==="*"?"{slug}":o).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 Ex(t){const s=[],n=new Set;for(const a of t.split(/[\n,]+/)){const i=a.trim().replace(/\/+$/,"");if(!i)continue;const o=i.split("/").filter(Boolean).at(-1)??i,m=o.startsWith("*"),c=o.endsWith("*"),h=o.slice(m?1:0,c?-1:void 0).trim();if(!h)throw new Error("Ignored URL patterns must include text besides *.");const p=m&&c?"contains":m?"suffix":c?"prefix":"exact",u=`${p}:${h}`;n.has(u)||(n.add(u),s.push({kind:p,value:h}))}return s}function qx(t){const s=Dx(t.sitemapUrl),n=t.examplePropertyUrl.trim()?un(t.examplePropertyUrl):null,a=un(t.preferredHost)??n??un(s);if(!a)throw new Error("Add a valid sitemap or Property page URL.");const i=un(t.additionalHost),r=t.additionalHost.trim().length>0,o=t.additionalPathPattern.trim().length>0;if(r!==o||r&&!i)throw new Error("Add both an additional domain and its Property URL pattern.");const m=Ex(t.excludedPaths);return{sitemapUrl:s,rule:{primary:{host:a,pathTemplate:sr(t)},...i?{aliases:[{host:i,pathTemplate:sr({...t,examplePropertyUrl:"",propertyPathPattern:t.additionalPathPattern})}]}:{},...m.length>0?{excludedSlugPatterns:m}:{}}}}function Ox(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 Gx(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 nr(t){return[...new Set([...t.discoveredUrl?[t.discoveredUrl]:[],...t.urlMatchers])]}function Fx(t){return t==="included"?"confirmed":t==="excluded"?"excluded":"proposed"}function Ca(t){return t?.authoring.targets.filter(s=>s.status!=="excluded").map(s=>s.stableKey)??[]}function Ua(t,s){const n=t.trim().toLocaleLowerCase().replace(/[^a-z0-9._~-]+/g,"-").replace(/^-+|-+$/g,"");return`${s}-${n||"item"}`.slice(0,128)}function ar(t){return un(t)}function fo(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 bo(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 vo(t,s){return s[0]==="assignments"&&typeof s[1]=="number"?t?.assignments[s[1]]:void 0}function yo(t,s){return t?.targets.find(n=>n.stableKey===s)?.label??"a Property"}function _x(t,s){const n=fo(t.authoring,s.path);if(!n)return;const a=s.path[2],i=s.path[3];if(a==="urlMatchers"&&typeof i=="number"){const r=n.urlMatchers[i];return r?`${n.label} — ${r}`:n.label}if(a==="aliases"&&typeof i=="number"){const r=n.aliases[i];return r?`${n.label} — ${r}`:n.label}return n.label}function Ux(t,s){const n=bo(t.authoring,s.path);if(!n)return;const a=s.path[2],i=s.path[3];if(a==="competitors"&&typeof i=="number"){const r=n.competitors.at(i)?.domain;return r?`${n.label} — ${r}`:n.label}if(a==="targetKeys"&&typeof i=="number"){const r=yo(t.authoring,n.targetKeys[i]);return`${n.label} — ${r}`}return n.label}function Bx(t,s){const n=vo(t.authoring,s.path);if(!n)return;const a=t.queries.find(i=>i.id===n.queryId)?.query??"an unavailable query";return`${yo(t.authoring,n.targetKey)} — ${a}`}function Vx(t,s){return s.path[0]==="identities"?"Project domain":_x(t,s)??Ux(t,s)??Bx(t,s)}function ir(t,s,n){const a=vo(t.authoring,s.path);if(!a)return;const i={...t.authoring?.defaultContext,...a.contextOverride},r=s.path.at(-1);if(n==="models"&&typeof r=="string")return i.models?.[r];if(n==="locations"&&typeof r=="number")return i.locations?.[r]}function Kx(t,s){const n=Vx(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,ir(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,ir(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 _n(t,s,n=`${s}s`){return`${t} ${t===1?s:n}`}function jo(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 zx(t,s,n,a){return`${(()=>{switch(t){case"execution-context-no-provider":return`${s} ${_n(n,"query assignment")} need${n===1?"s":""} a provider.`;case"target-without-aliases":return`${s} ${_n(n,"Property","Properties")} need${n===1?"s":""} aliases.`;case"target-without-assignments":return`${s} ${_n(n,"Property","Properties")} need${n===1?"s":""} queries.`;default:return n>1?`${s} ${_n(n,"item")} need review.`:s}})()}${jo(a)}`}function Qx(t,s){const n=new Map;for(const a of t){const i=Kx(a,s),r=[a.ruleId,a.severity,i.title,i.detail].join("\0"),o=n.get(r)??{ruleId:a.ruleId,severity:a.severity,meaning:i,paths:new Set,affected:new Set};o.paths.add(JSON.stringify(a.path)),i.affected&&o.affected.add(i.affected),n.set(r,o)}return[...n.values()].map((a,i)=>({id:`${a.ruleId}-${a.severity}-${i}`,title:a.meaning.title,detail:zx(a.ruleId,a.meaning.detail,a.paths.size,a.affected),tone:a.meaning.tone}))}function ka(t){if(!t)return;const s=t.discoveredUrl??t.urlMatchers[0];return s?`${t.label} — ${s}`:t.label}function Aa(t,s,n){const a=fo(n,t.path),i=bo(n,t.path),r=t.path[2]==="rebind"&&typeof t.path[3]=="string"?t.path[3]:void 0,o=r?n?.targets.find(p=>p.stableKey===r):void 0,m=a?.label??i?.label,c=jo(m?[m]:[]),h={id:`${t.code}-${s}`,tone:"caution"};switch(t.code){case"merge-targets-noop":return{...h,title:"Choose another Property to merge",detail:`Select at least one other Property before merging.${c}`};case"excluded-target-has-assignments":return{...h,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{...h,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 p=ka(a)??"the proposed Property";return{...h,title:"Review a new Property",detail:`Review ${p}. It did not match an existing Property.`}}case"measurement.discovery.proposed_rebind":{const p=ka(a)??"the proposed Property",u=o?.label??"an existing Property";return{...h,title:"Review a moved Property",detail:`Review ${p}. It may be the same Property as ${u}.`}}case"measurement.discovery.rebind_ambiguous":{const p=ka(a)??"the proposed Property",u=o?.label??"an existing Property";return{...h,title:"Choose an existing Property",detail:`Review ${p}. It may match ${u}; choose the correct Property.`}}default:return{...h,title:"Unexpected setup warning",detail:"Review the latest setup change before publishing. If this warning remains, contact support."}}}function Hx(t,s=!1){const n=[],a=t.targets.added.length+t.targets.removed.length+t.targets.changed.length,i=t.groups.added.length+t.groups.removed.length+t.groups.changed.length,r=t.assignments.added+t.assignments.removed+t.assignments.reclassified;return a>0&&n.push(`${a} Property ${a===1?"change":"changes"}`),r>0&&n.push(`${r} query assignment ${r===1?"change":"changes"}`),i>0&&n.push(`${i} group ${i===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 ss(t){return[...new Set(t)]}function ws(t){return ss(t).sort()}function Wx(t,s,n){return t.kind==="groups"?{groupKeys:ws(t.groupIds),queryIds:ws(n)}:{targetKeys:ws(t.kind==="all"?s:t.propertyIds),queryIds:ws(n)}}function Yx(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 rr(t){return t.kind==="exact"?t.url??"":t.kind==="prefix"?`https://${t.host??""}${t.pathPrefix==="/"?"":t.pathPrefix??""}/*`:t.host??""}function Xx(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(rr).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(i=>({...i,aliases:[...i.aliases]}))}))};const n=s.targetQuerySelections.flatMap(a=>a.queryIds.map(i=>({targetKey:a.targetKey,queryId:i,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(rr).filter(Boolean),source:"manual"})),assignments:n,groups:s.groups.map(a=>({stableKey:a.stableKey,label:a.label,targetKeys:[...a.targetKeys],competitors:(a.competitors??[]).map(i=>({stableKey:Ua(i,"competitor"),label:i,domain:i,aliases:[]}))}))}}function Jx({projectName:t,queries:s,isQueryLoading:n,isQueryError:a,onRetryQueries:i,publishedPlan:r,canEdit:o=!0,onCreateQueries:m,onManageProjectQueries:c,onPublished:h,service:p=Lx}){const[u,v]=l.useState(null),[j,b]=l.useState(null),[g,f]=l.useState("import"),[k,O]=l.useState(!0),[q,A]=l.useState(null),[d,y]=l.useState(null),[S,V]=l.useState([]),[K,w]=l.useState({...er}),[T,F]=l.useState("idle"),[$,H]=l.useState(""),[ye,ge]=l.useState(tr),[z,ee]=l.useState([]),[ie,W]=l.useState([]),[B,R]=l.useState({kind:"all"}),[se,le]=l.useState(null),[de,X]=l.useState(null),[Ae,_]=l.useState(!1),[ae,Ne]=l.useState(null),[Le,Fe]=l.useState(0),[Pe,Qe]=l.useState(null),[ue,we]=l.useState({...ln}),[Ze,_e]=l.useState(null),[He,$e]=l.useState(""),[Ce,E]=l.useState(null),[M,L]=l.useState(!1),[je,qe]=l.useState(!1),[Y,Be]=l.useState(null),[mt,ot]=l.useState(null),[De,Oe]=l.useState(null),[xt,We]=l.useState(null),[Ve,Te]=l.useState(null),jt=l.useRef(0),Tt=l.useRef(0),Ue=j?.draft??null,Ge=j?.etag??null,bt=l.useMemo(()=>!o&&r?{baseActiveRevision:r.revision,authoring:Xx(r)}:null,[o,r]),Ke=Ue??bt;async function Nt(I){const Q=++jt.current;O(!0),A(null);try{let[me,te]=await Promise.all([p.loadSetup(t),p.loadDraft(t)]);if(!te.draft&&I&&o&&(await p.createDraft(t,me.activeRevision),[me,te]=await Promise.all([p.loadSetup(t),p.loadDraft(t)])),Q!==jt.current)return;v(me),b(te),f(Ox(te.draft));const ne=Ca(te.draft);ee(ne)}catch(me){if(Q!==jt.current)return;A(Kt(me,"Could not load advanced measurement setup."))}finally{Q===jt.current&&O(!1)}}l.useEffect(()=>(Nt(!0),()=>{jt.current+=1}),[t,o,p]),l.useEffect(()=>{!k&&!Ue&&bt&&f("properties")},[Ue,k,bt]);async function kt(){const I=await p.loadDraft(t);return b(I),I}async function vt(I){Te(null);try{const[Q,me]=await Promise.all([p.loadSetup(t),p.loadDraft(t)]);v(Q),b(me);const te=Ca(me.draft);ee(te),f(ne=>Gx(me.draft,ne)),y(I)}catch(Q){y(Kt(Q,I))}}async function At(I,Q,me,te={}){const{preserveBusyAction:ne=!1}=te;if(!o||!Ge||De&&!ne)return null;ne||Oe(I),y(null),Te(null);try{const Ee=await Q(Ge),es=await kt();return V((Ee.warnings??[]).map((pt,Fs)=>Aa(pt,Fs,es.draft?.authoring))),es}catch(Ee){return Is(Ee)?await vt("This setup changed in another session. The latest draft is loaded; review your changes again."):y(Kt(Ee,me)),null}finally{ne||Oe(null)}}const lt=l.useMemo(()=>(Ke?.authoring.targets??[]).map(I=>{const Q=nr(I);return{id:I.stableKey,name:I.label,url:Q[0]??"No URL",urls:Q,state:Fx(I.status)}}),[Ke]),G=l.useMemo(()=>Ke?.authoring.targets.filter(I=>I.status==="included")??[],[Ke]),ke=l.useMemo(()=>G.map(I=>({id:I.stableKey,label:I.label,urlCount:nr(I).length})),[G]),fe=Ke?.authoring.assignments.length??0,he=l.useMemo(()=>{if(!Ke)return[];const I=new Set(s.map(te=>te.id)),Q=s.map(te=>({id:te.id,text:te.query,source:"saved-project-queries",propertyIds:ss(Ke.authoring.assignments.filter(ne=>ne.queryId===te.id).map(ne=>ne.targetKey))})),me=ss(Ke.authoring.assignments.map(te=>te.queryId).filter(te=>!I.has(te))).map(te=>({id:te,source:"unavailable-tracked-query",state:"missing",propertyIds:ss(Ke.authoring.assignments.filter(ne=>ne.queryId===te).map(ne=>ne.targetKey))}));return[...Q,...me]},[s,Ke]),Mt=l.useMemo(()=>(Ke?.authoring.groups??[]).map(I=>({id:I.stableKey,name:I.label,propertyIds:I.targetKeys,competitors:I.competitors.map(Q=>Q.domain)})),[Ke]),ct=l.useMemo(()=>{if(ie.length===0)return null;const I=Wx(B,ke.map(me=>me.id),ie);return(I.groupKeys?.length??I.targetKeys?.length??0)>0?I:null},[B,ke,ie]),Pt=ct?JSON.stringify(ct):"";l.useEffect(()=>{const I=ct,Q=++Tt.current;if(!o||!Ue||!Ge||!I){le(null),X(null),Ne(null),_(!1);return}le(null),X(null),Ne(null),_(!0);const me=window.setTimeout(()=>{p.previewAssignments(t,I).then(te=>{if(Q===Tt.current){if(te.draftEtag!==Ge){le(null),X(null),Ne("The setup changed while calculating assignment impact. Refresh the draft and try again.");return}le(te),X(Pt)}}).catch(te=>{Q===Tt.current&&(le(null),X(null),Ne(Mx(te)))}).finally(()=>{Q===Tt.current&&_(!1)})},250);return()=>{window.clearTimeout(me),Tt.current+=1}},[ct,Pt,Le,o,Ue,Ge,t,p]);const Lt=l.useMemo(()=>[...fe===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"}]:[],...Ke?.authoring.assignments.some(I=>I.queryClass==="unclassified")&&!(bt&&r?.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],[fe,bt,r,S,Ke]),Wt=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 Dt(I){let Q;try{Q=qx(I)}catch(te){y(Kt(te,"Check the sitemap details and try again."));return}w(I),F("reviewing");const me=await At("import",te=>p.importSitemap(t,te,Q),"Could not review this sitemap.");if(me?.draft){const te=me.draft.authoring.targets.filter(Ee=>Ee.status==="proposed").map(Ee=>Ee.stableKey),ne=me.draft.authoring.targets.filter(Ee=>Ee.status==="included").map(Ee=>Ee.stableKey);ee([...ne,...te]),H(""),ge(tr),f("properties"),F("idle")}else F("error")}async function is(I){if(!m||I.length===0||De)return[];Oe("create-queries"),We(null);try{return await m(I)}catch(Q){throw We(ut(Q)),Q}finally{Oe(null)}}async function nt(I){if(!Ue||!Ge||De)return;const Q=new Set(I),te=Ue.authoring.targets.filter(Ee=>Ee.status==="proposed"&&Ee.discoveryIdentity).map(Ee=>({discoveryIdentity:Ee.discoveryIdentity,action:Q.has(Ee.stableKey)?"create":"ignore"})),ne=te.length>0||Ue.authoring.targets.some(Ee=>Ee.status!=="proposed"&&Ee.status==="included"!==Q.has(Ee.stableKey));Oe("properties"),y(null),Te(null);try{if(!ne){ee([...Q]),R({kind:"all"}),f("groups");return}await p.applySitemapSelection(t,Ge,te,[...Q]);const Ee=await kt(),es=Ca(Ee.draft);ee(es),R({kind:"all"}),f("groups")}catch(Ee){Is(Ee)?await vt("This setup changed in another session. The latest Properties are loaded."):y(Kt(Ee,"Could not save the selected Properties."))}finally{Oe(null)}}async function ms(I){const Q=I.groupIds&&I.groupIds.length>0?{groupKeys:ws(I.groupIds),queryIds:ws(I.queryIds)}:{targetKeys:ws(I.propertyIds),queryIds:ws(I.queryIds)};if(!se||de!==JSON.stringify(Q)||!Ge||se.draftEtag!==Ge){y("Review the latest assignment impact before assigning queries.");return}await At("assignments",te=>p.applyAssignments(t,te,Q),"Could not apply these queries.")&&(W([]),Qe(`${se.assignments.added} new assignment${se.assignments.added===1?"":"s"} added. Existing assignments were kept.`))}async function wt(I){if(I.propertyIds.length===0)return;await At("replace-assignments",me=>p.replaceAssignments(t,me,{targetKeys:ss(I.propertyIds),queryIds:[I.queryId]}),"Could not replace this query assignment.")&&(W(me=>me.filter(te=>te!==I.queryId)),Qe("Query assignments replaced."))}async function hs(I,Q=!1){if(I.length===0)return;if(!await At("paired-assignments",te=>p.applyPairedAssignments(t,te,[...I]),"Could not assign these queries.",{preserveBusyAction:Q}))throw new Error("Could not assign these queries.")}async function Ot(I){if(!(!o||!m||I.length===0||De)){Oe("create-and-pair-questions"),We(null);try{let Q;try{Q=await m(ss(I.map(ne=>ne.text)))}catch(ne){throw We(ut(ne)),ne}const me=new Map(Q.map(ne=>[ne.query,ne.id])),te=I.map(ne=>({targetKey:ne.propertyId,queryId:me.get(ne.text)})).filter(ne=>ne.queryId!==void 0);if(te.length!==I.length){const ne=new Error("The created queries could not be matched to their Properties.");throw We("The queries were added, but could not be paired with every Property. Try again to pair them."),ne}try{await hs(te,!0)}catch(ne){throw We("The queries were added, but could not be assigned to their Properties. Try again to pair them."),ne}}finally{Oe(null)}}}async function Yt(I){if(!Ue)return;const Q=ss(Ue.authoring.assignments.filter(te=>te.queryId===I).map(te=>te.targetKey));if(Q.length===0)return;await At(`remove-${I}`,te=>p.removeAssignment(t,te,Q,I),"Could not clear this query assignment.")&&W(te=>te.filter(ne=>ne!==I))}async function Bt(I){if(!Ue||!Ge||De)return;const Q=I.name.trim();if(!Q)return;const me=Ze??Ua(Q,"group"),te=Ue.authoring.groups.find(pt=>pt.stableKey===me);if(te&&Ze===null){y(`A group named "${te.label}" already exists. Edit it or choose a different name.`);return}const ne=I.competitorDomains.split(/[\s,]+/).map(pt=>pt.trim()).filter(Boolean),Ee=ne.find(pt=>ar(pt)===null);if(Ee){y(`"${Ee}" is not a valid competitor domain.`);return}const es=ss(ne.map(pt=>ar(pt)));Oe("group"),y(null),Te(null);try{const pt=await p.upsertGroup(t,Ge,{stableKey:me,label:Q,targetKeys:ss(I.propertyIds),competitors:es.map(N=>te?.competitors.find(re=>re.domain===N)??{stableKey:Ua(N,"competitor"),label:N,domain:N,aliases:[]})}),Fs=await kt();V(pt.warnings.map((N,re)=>Aa(N,re,Fs.draft?.authoring))),we({...ln}),_e(null)}catch(pt){Is(pt)?await vt("This setup changed in another session. The latest groups are loaded."):y(Kt(pt,"Could not save this group."))}finally{Oe(null)}}function et(I){const Q=Ue?.authoring.groups.find(me=>me.stableKey===I);Q&&(_e(I),we({name:Q.label,propertyIds:[...Q.targetKeys],competitorDomains:Q.competitors.map(me=>me.domain).join(", ")}))}async function xs(I){await At("remove-group",me=>p.removeGroup(t,me,I),"Could not remove this group.")&&(R(me=>me.kind==="groups"&&me.groupIds.includes(I)?{kind:"all"}:me),Ze===I&&(_e(null),we({...ln})))}function Gt(I){$e(I),E(null),Be(null),ot(null)}async function St(){if(!(!o||!He.trim()||M||je)){L(!0),Be(null),ot(null);try{E(await p.previewGroupMembership(t,{csv:He}))}catch(I){E(null),Be(Kt(I,"Could not review this CSV."))}finally{L(!1)}}}async function ps(I){if(!(!o||!Ge||!Ce||I.length===0||De)){if(Ce.draftEtag!==Ge){Be("The setup changed while this CSV was open. Review the latest CSV before applying it.");return}qe(!0),Oe("group-import"),Be(null),ot(null),Te(null);try{const Q=await p.applyGroupMembership(t,Ge,{csv:He,sourceChecksum:Ce.sourceChecksum,previewChecksum:Ce.previewChecksum,acceptedRows:ss(I.map(String)).map(Number)}),me=await kt();V(Q.warnings.map((te,ne)=>Aa(te,ne,me.draft?.authoring))),$e(""),E(null),ot(`${Q.addedMemberships} membership${Q.addedMemberships===1?"":"s"} added${Q.unchangedMemberships>0?`; ${Q.unchangedMemberships} already present`:""}.`)}catch(Q){Is(Q)?(await vt("This setup changed in another session. The latest draft is loaded; review the CSV again."),Be("The setup changed while this CSV was open. Review the latest CSV before applying it.")):Be(Kt(Q,"Could not apply this CSV."))}finally{Oe(null),qe(!1)}}}async function dt(){if(!(!Ue||!Ge||De||fe===0)){Oe("review"),y(null),Te(null);try{const[I,Q]=await Promise.all([p.compilePreview(t),p.diffPreview(t)]),me=[...I.checks,...Q.checks],te=me.some(ne=>ne.ruleId==="active-revision-schema-v1");if(V(Qx(me.filter(ne=>ne.ruleId!=="active-revision-schema-v1"),{authoring:Ke?.authoring,queries:s})),!I.ok||!Q.ok)return;if(Q.diff.activeRevision!==Ue.baseActiveRevision){await vt("The published setup changed while you were reviewing. The latest draft is loaded; review it again.");return}if(I.compiledChecksum!==Q.compiledChecksum){y("The setup changed while it was being reviewed. Review the latest changes again.");return}Te({etag:Ge,baseActiveRevision:Ue.baseActiveRevision,compiledChecksum:I.compiledChecksum,changes:Hx(Q.diff,te),providerCalls:I.plan.executionNodes.reduce((ne,Ee)=>ne+Ee.expectedSnapshots,0)})}catch(I){y(Kt(I,"Could not review this setup."))}finally{Oe(null)}}}async function Zt(){if(!(!Ue||!Ge||!Ve||De)){if(Ge!==Ve.etag||Ue.baseActiveRevision!==Ve.baseActiveRevision){Te(null),y("The setup changed after review. Review the latest changes before publishing.");return}Oe("publish"),y(null);try{await p.publish(t,Ge,{expectedActiveRevision:Ve.baseActiveRevision,expectedCompiledChecksum:Ve.compiledChecksum}),b({draft:null,etag:null}),Te(null),h?.()}catch(I){Is(I)?await vt("The setup changed before it could be published. Review the latest draft and publish again."):y(Kt(I,"Could not publish this setup."))}finally{Oe(null)}}}async function C(){if(!(!Ge||De)){Oe("discard"),y(null);try{await p.discard(t,Ge),b({draft:null,etag:null}),Te(null),h?.()}catch(I){Is(I)?await vt("This setup changed in another session. The latest draft is loaded."):y(Kt(I,"Could not discard these changes."))}finally{Oe(null)}}}async function be(){if(!(!Ue||!Ge||!u||De)){Oe("restart"),y(null),Te(null);try{await p.discard(t,Ge),await p.createDraft(t,u.activeRevision),w({...er}),H(""),ee([]),W([]),R({kind:"all"}),le(null),Ne(null),Qe(null),we({...ln}),_e(null),$e(""),E(null),Be(null),ot(null),await Nt(!1)}catch(I){Is(I)?await vt("The setup changed again. Reloaded the latest draft and published setup."):y(Kt(I,"Could not restart this setup."))}finally{Oe(null)}}}if(k)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(q)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:q}),e.jsx(P,{className:"mt-3 min-h-11",type:"button",size:"sm",variant:"outline",onClick:()=>{Nt(!0)},children:"Try again"})]})]});if(!Ke||o&&!Ge)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:o?"Start setup from the project Overview.":"No advanced setup is available to review."})]});if(o&&Ue&&u&&Ue.baseActiveRevision!==u.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(P,{className:"mt-3 min-h-11",type:"button",size:"sm",variant:"outline",disabled:De==="restart",onClick:()=>{be()},children:De==="restart"?"Restarting…":"Discard draft and restart"})]}),d?e.jsx("p",{role:"alert",className:"text-sm text-negative",children:d}):null]});const ve=a&&i?e.jsx("div",{className:"flex justify-end",children:e.jsx(P,{type:"button",size:"sm",variant:"outline",className:"min-h-11",onClick:i,children:"Retry queries"})}):null;return e.jsxs("div",{className:"space-y-4",children:[u?.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,d?e.jsx("p",{role:"alert",className:"border-y border-negative-800/40 bg-negative-950/20 py-3 text-sm text-negative",children:d}):null,ve,g==="import"||g==="properties"?e.jsx(Fn,{currentStep:g,hasDraft:Ue!==null,canEdit:o,onStepChange:o?void 0:f,onDiscard:()=>{C()},importProperties:{importDraft:K,onImportDraftChange:I=>{w(I),F("idle"),y(null)},onReviewSitemap:I=>{Dt(I)},reviewState:T,properties:lt,propertiesState:"ready",propertiesSearch:$,onPropertiesSearchChange:H,maxVisibleProperties:ye,onShowAllProperties:()=>ge(lt.length),selectedPropertyIds:z,onSelectedPropertyIdsChange:I=>ee([...I]),onContinue:I=>{nt(I)},isContinuing:De==="properties",onRetryProperties:()=>{kt()},onReturnToImport:()=>f("import")}}):g==="queries"?e.jsx(Fn,{currentStep:"queries",hasDraft:Ue!==null,canEdit:o,onStepChange:o?void 0:f,onDiscard:()=>{C()},onManageProjectQueries:c,queries:{onCreateQueries:m?I=>is(I):void 0,isCreatingQueries:De==="create-queries"||De==="create-and-pair-questions",isBusy:De!==null,createQueriesError:xt,availability:Wt,properties:ke,queries:he,selectedQueryIds:ie,isApplying:De==="assignments"||De==="paired-assignments",onSelectedQueryIdsChange:I=>W([...I]),onApplySelectedQueries:I=>ms(I),groups:Mt,audience:B,onAudienceChange:I=>{R(I),Qe(null)},assignmentImpact:se&&de===Pt?Yx(se):null,isPreviewingAssignmentImpact:Ae,assignmentImpactError:ae,onRetryAssignmentImpact:()=>Fe(I=>I+1),assignmentNotice:Pe,onReplaceAssignments:wt,isReplacingAssignments:De==="replace-assignments",onCreateAndPairQuestions:o&&m?Ot:void 0,onClearQueryAssignments:Yt,onRemoveQuery:Yt,canContinue:fe>0,onBack:()=>f("groups"),onContinue:()=>f("review")}}):g==="groups"?e.jsx(Fn,{currentStep:"groups",hasDraft:Ue!==null,canEdit:o,onStepChange:o?void 0:f,onDiscard:()=>{C()},groups:{properties:ke,groups:Mt,groupDraft:ue,isSaving:De==="group",onGroupDraftChange:we,onSaveGroup:Bt,onEditGroup:I=>et(I.id),onRemoveGroup:xs,onClearGroupDraft:()=>{_e(null),we({...ln})},membershipImport:{csv:He,preview:Ce,isReviewing:M,isApplying:je,error:Y,notice:mt,onCsvChange:Gt,onReview:St,onApply:ps},onBack:()=>{f("properties")},onContinue:()=>f("queries")}}):e.jsx(Fn,{currentStep:"review",hasDraft:Ue!==null,canEdit:o,onStepChange:o?void 0:f,onDiscard:()=>{C()},review:{counts:{properties:G.length,queries:new Set(Ke.authoring.assignments.map(I=>I.queryId)).size,groups:Ke.authoring.groups.length,assignments:Ke.authoring.assignments.length,providerCalls:Ve?.providerCalls},flaggedExceptions:Lt,reviewedChanges:Ve?.changes,isReviewing:De==="review",canReviewChanges:fe>0&&!De,onReviewChanges:dt,onBack:()=>f("queries"),canPublish:Ve!==null&&!De,isPublishing:De==="publish",onPublish:Zt}})]})}const Zx=[{key:"label",label:"Property",numeric:!1},{key:"mentionCoverage",label:"Mention",numeric:!0},{key:"citationCoverage",label:"Citation",numeric:!0}];function or(t){return t.label!=="Complete"}const $s="__all_properties__",ep=50,No=50,tp=20,sp=50,np=250,ap=5,ip=[{value:"all",label:"All queries"},{value:"non-brand",label:"Non-brand"},{value:"branded",label:"Branded"}],rp={"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"},wo={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."},op={numerator:null,denominator:null,reason:"plan_v1"};function xn(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 lp(t){return xn(t)?`${t.numerator} of ${t.denominator} (${Math.round(t.numerator/t.denominator*100)}%)`:"N/A"}function So(t){if(xn(t))return"";const s=t.reason??"unavailable";return wo[s]??s}function lr(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 cp(t,s){return!Number.isFinite(t)||!Number.isFinite(s)||t<0||s<=0||t>s?null:`${t} of ${s}`}function dp(t){const s=t.trim();return s&&!s.toLocaleLowerCase().includes("unavailable")?s:null}function up(t){return t?.closest?.('button, a, input, select, textarea, [role="button"]')!=null}function mn({metric:t,compact:s=!1}){const n=s?xn(t)?"text-sm font-medium text-primary":"text-sm font-medium text-secondary":xn(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",...xn(t)?{}:{title:So(t)},children:e.jsx("span",{className:n,children:lp(t)})})}function Ja({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(P,{size:"sm",variant:"outline",onClick:n,children:["Show all ",s," ",a]})]})}function cr({title:t,values:s,emptyLabel:n,valueClassName:a="text-secondary"}){const[i,r]=l.useState(No),o=s.slice(0,i);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:o.map((m,c)=>e.jsx("li",{className:a,children:m},`${m}:${c}`))}),e.jsx(Ja,{shown:o.length,total:s.length,itemLabel:t.toLocaleLowerCase(),onShowAll:()=>r(Number.MAX_SAFE_INTEGER)})]})]})}function mp({evidence:t,state:s="ready",onRetry:n}){const[a,i]=l.useState(No),r=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(P,{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:r.map(o=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("span",{className:"flex flex-wrap items-center gap-1",children:[e.jsx(oe,{tone:o.tone,children:rp[o.kind]}),o.historical?e.jsx(oe,{tone:"caution",children:"Historical"}):null]})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:o.query}),o.provider||o.location?e.jsx("span",{className:"mt-1 block text-xs text-muted",children:[o.provider,o.location].filter(Boolean).join(" · ")}):null]}),e.jsx("td",{className:"break-all text-secondary",children:o.url})]},o.id))})]})}),e.jsx(Ja,{shown:r.length,total:t.length,itemLabel:"evidence items",onShowAll:()=>i(Number.MAX_SAFE_INTEGER)})]})]})}function hp({property:t,onRetryEvidence:s}){return e.jsxs("div",{className:"space-y-5 py-2",children:[e.jsx(cr,{title:"Assigned queries",values:t.assignedQueries,emptyLabel:"No queries are assigned."}),e.jsx(cr,{title:"URLs",values:t.urls,emptyLabel:"No URLs are assigned.",valueClassName:"break-all text-secondary"}),e.jsx(mp,{evidence:t.evidence,state:t.evidenceState,onRetry:s})]})}function xp({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(mn,{metric:s.coverage,compact:!0})})]},s.name))})]})})]})}function dr({ariaLabelledBy:t,value:s,options:n,onChange:a,disabled:i=!1}){function r(o){if(i)return;const m=n.findIndex(p=>p.value===s);let c=null;if(o.key==="ArrowRight"||o.key==="ArrowDown"?c=(m+1)%n.length:o.key==="ArrowLeft"||o.key==="ArrowUp"?c=(m-1+n.length)%n.length:o.key==="Home"?c=0:o.key==="End"&&(c=n.length-1),c===null)return;o.preventDefault();const h=n[c];a(h.value),o.currentTarget.querySelectorAll('[role="radio"]')[c].focus()}return e.jsx("div",{role:"radiogroup","aria-labelledby":t,"aria-disabled":i,className:"segmented flex-wrap",onKeyDown:r,children:n.map(o=>{const m=o.value===s;return e.jsx("button",{type:"button",role:"radio","aria-checked":m,tabIndex:m?0:-1,disabled:i,onClick:()=>a(o.value),className:`segmented-option disabled:cursor-not-allowed disabled:opacity-50 ${m?"segmented-option-active":""}`,children:o.label},o.value)})})}function pp({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(Je,{text:"One or both signals missing. Not the same as neither."}):null]})]},n.key))})}function gp({report:t,canEdit:s,onRunMeasurement:n,onRepublishSetup:a,isRunningMeasurement:i=!1,isRepublishingSetup:r=!1,isViewLoading:o=!1,isLoadingMore:m=!1,isLoadMoreError:c=!1,viewSearch:h,onViewChange:p,onLoadMore:u,onPropertyExpand:v,onRetryEvidence:j,renderPropertyLink:b}){const g=t.currentView!=null,f=t.classReporting==="available"&&(g||t.classScopes!=null),[k,O]=l.useState(t.currentView?.queryClass??"all"),[q,A]=l.useState(t.currentView?.scope.key??$s),[d,y]=l.useState(h??""),[S,V]=l.useState(ep),[K,w]=l.useState(tp),[T,F]=l.useState(t.currentView?.sort??"label-asc"),[$,H]=l.useState(null),ye=l.useRef(h??""),ge=f&&!g&&k!=="all"?k==="non-brand"?t.classScopes.nonBrand:t.classScopes.branded:t.overall,z=g?{aggregate:t.currentView.aggregate,groups:[]}:ge,ee=l.useCallback(E=>{if(!g||!p)return;const M=E.scope??(q===$s?"all":"group"),L=E.search??d;ye.current=L,p({scope:M,...M==="group"?{groupKey:E.groupKey??q}:{},queryClass:E.queryClass??k,...L?{search:L}:{},...E.sort?{sort:E.sort}:{}})},[p,d,k,q,g]);l.useEffect(()=>{!t.currentView||o||(O(t.currentView.queryClass),A(t.currentView.scope.key??$s),t.currentView.sort&&F(t.currentView.sort))},[o,t.currentView]),l.useEffect(()=>{h!==void 0&&(ye.current=h,y(E=>E.trim()===h.trim()?E:h))},[h]),l.useEffect(()=>{if(!g||!p||d===ye.current)return;const E=window.setTimeout(()=>ee({search:d}),np);return()=>window.clearTimeout(E)},[p,ee,d,g]);const ie=t.availableGroups??z.groups;l.useEffect(()=>{q===$s||ie.some(E=>E.id===q)||A($s)},[ie,q]);const W=g?void 0:z.groups.find(E=>E.id===q),B=W?.aggregate??z.aggregate,R=E=>f?E:op,se=T,le=d.trim().toLocaleLowerCase(),de=l.useMemo(()=>!g&&le?B.properties.filter(E=>E.name.toLocaleLowerCase().includes(le)):B.properties,[B.properties,le,g]),X=g?de:de.slice(0,S),Ae=(g?t.currentView?.scope.kind==="group":W!=null)&&k==="non-brand"&&f&&(g||W.confirmedCompetitorCount>0)&&(B.shareOfVoice?.length??0)>0,_=f?B.unavailablePropertyCount??0:0,ae=t.flaggedResults.reduce((E,M)=>E+(M.count??1),0),Ne=t.flaggedResultsTotal??ae,Le=[R(B.metrics.propertiesMentioned),R(B.metrics.mentionCoverage),R(B.metrics.citationCoverage)].map(So).find(Boolean),Fe=f?t.nextActionText??Le??(_>0?`${_} ${_===1?"property is":"properties are"} unavailable.`:Ne>0?`${Ne} flagged ${Ne===1?"result needs":"results need"} review.`:null):wo.plan_v1,ue=!(t.latestMeasurement.status.tone==="negative")&&t.latestMeasurement.completedSlots<t.latestMeasurement.totalSlots?cp(t.latestMeasurement.completedSlots,t.latestMeasurement.totalSlots):null,we=dp(t.latestMeasurement.date),Ze=[{value:$s,label:"All properties"},...ie.map(E=>({value:E.id,label:E.label}))],_e=ie.length>ap;function He(E){A(E),ee(E===$s?{scope:"all"}:{scope:"group",groupKey:E})}function $e(E){O(E),ee({queryClass:E})}function Ce(E){const M=$!==E;H(M?E:null),M&&v?.(E)}return e.jsxs("section",{"aria-label":"Advanced measurement overview","aria-busy":o,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:o?e.jsx("span",{className:"text-sm text-secondary",children:"Updating results…"}):e.jsxs(e.Fragment,{children:[e.jsx(oe,{tone:t.latestMeasurement.status.tone,children:t.latestMeasurement.status.label}),t.latestMeasurement.includesBridgedHistory?e.jsx(oe,{tone:"caution",children:"Includes historical data"}):null,ue?e.jsx("span",{className:"text-sm text-secondary tabular-nums",children:ue}):null,we?e.jsx("span",{className:"text-sm text-secondary",children:we}):null,Fe?e.jsx("span",{className:"text-sm text-secondary",children:Fe}):null,s&&f&&n?e.jsx(P,{className:"ml-auto",size:"sm",onClick:()=>{n()},disabled:i,children:i?"Starting measurement…":"Run measurement"}):s&&!f?e.jsx(P,{className:"ml-auto",size:"sm",onClick:()=>{a?.()},disabled:!a||r,children:r?"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:q,onChange:E=>He(E.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:Ze.map(E=>e.jsx("option",{value:E.value,children:E.label},E.value))}):e.jsx(dr,{ariaLabelledBy:"advanced-measurement-group-label",value:q,options:Ze,onChange:He})]}),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(dr,{ariaLabelledBy:"advanced-measurement-class-label",value:k,options:ip,onChange:$e,disabled:!f})]}),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:d,onChange:E=>y(E.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"})]})]}),!o&&Ae?e.jsx(xp,{values:B.shareOfVoice??[]}):null,o?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(Je,{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??de.length," ",(t.currentView?.propertyTotal??de.length)===1?"property":"properties"]})]}),t.currentView?.outcomes?e.jsx(pp,{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:[Zx.map(E=>{const M=se.startsWith(`${E.key}-`),L=M&&se.endsWith("-desc")?"descending":M?"ascending":"none";return e.jsx("th",{"aria-sort":L,className:(E.numeric,void 0),children:p?e.jsxs("button",{type:"button",className:"inline-flex items-center gap-1 text-inherit hover:text-heading",onClick:()=>{const je=`${E.key}-${M&&se.endsWith("-asc")?"desc":"asc"}`;F(je),ee({sort:je})},"aria-label":`Sort by ${E.label.toLowerCase()}`,children:[E.label,e.jsx(Wn,{className:`h-3 w-3 transition-transform ${M?"opacity-100":"opacity-0"} ${L==="ascending"?"rotate-180":""}`,"aria-hidden":"true"})]}):E.label},E.key)}),e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Details"})})]})}),e.jsxs("tbody",{children:[X.map(E=>{const M=$===E.id;return e.jsxs(l.Fragment,{children:[e.jsxs("tr",{className:"cursor-pointer transition-colors hover:bg-surface-subtle",onClick:L=>{up(L.target)||Ce(E.id)},children:[e.jsxs("td",{className:"font-medium text-heading",children:[b?b({id:E.id,name:E.name}):E.name,or(E.status)||E.historical?e.jsxs("span",{className:"ml-2 inline-flex flex-wrap items-center gap-1 align-middle",children:[or(E.status)?e.jsx(oe,{tone:E.status.tone,children:E.status.label}):null,E.historical?e.jsx(oe,{tone:"caution",children:"Historical"}):null]}):null,lr(E)?e.jsx("div",{className:"mt-0.5 text-xs font-normal text-faint",children:lr(E)}):null]}),e.jsx("td",{className:"text-secondary",children:e.jsx(mn,{metric:E.mentionCoverage,compact:!0})}),e.jsx("td",{className:"text-secondary",children:e.jsx(mn,{metric:E.citationCoverage,compact:!0})}),e.jsx("td",{className:"text-right",children:e.jsx(P,{size:"icon",variant:"ghost","aria-expanded":M,"aria-label":M?`Hide details for ${E.name}`:`Show details for ${E.name}`,onClick:()=>Ce(E.id),children:e.jsx(Wn,{className:`h-4 w-4 transition-transform duration-200 motion-reduce:transition-none ${M?"rotate-180":""}`,"aria-hidden":"true"})})})]},E.id),M?(E.providers??[]).map(L=>e.jsxs("tr",{className:"measurement-subrow",children:[e.jsx("td",{className:"measurement-subrow-name",children:L.provider}),e.jsx("td",{className:"text-secondary",children:e.jsx(mn,{metric:L.mentionCoverage,compact:!0})}),e.jsx("td",{className:"text-secondary",children:e.jsx(mn,{metric:L.citationCoverage,compact:!0})}),e.jsx("td",{})]},`${E.id}:${L.provider}`)):null,M?e.jsx("tr",{children:e.jsx("td",{colSpan:4,className:"bg-surface-subtle px-4",children:e.jsx(hp,{property:E,onRetryEvidence:j})})},`${E.id}:details`):null]},E.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]})]})}),g&&t.currentView.nextCursor&&u?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(P,{size:"sm",variant:"outline",disabled:m,onClick:()=>u(t.currentView.nextCursor),children:m?"Loading…":c?"Retry loading more properties":"Show 50 more"})]}):g?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(Ja,{shown:X.length,total:de.length,itemLabel:"properties",onShowAll:()=>V(Number.MAX_SAFE_INTEGER)})]}),!o&&!le&&Ne>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 (",Ne,")"]}),e.jsx("ul",{className:"mt-3 space-y-3",children:t.flaggedResults.slice(0,K).map(E=>e.jsxs("li",{className:"flex flex-wrap items-start gap-2 text-sm",children:[e.jsx(oe,{tone:E.tone,children:"Flagged"}),e.jsx("span",{className:"font-medium text-heading",children:E.property}),e.jsx("span",{className:"text-secondary",children:E.summary})]},E.id))}),K<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,K).reduce((E,M)=>E+(M.count??1),0)," of ",Ne," flagged results"]}),e.jsx(P,{size:"sm",variant:"outline",onClick:()=>w(E=>Math.min(t.flaggedResults.length,E+sp)),children:"Show 50 more"})]}):ae<Ne?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 ",Ne," flagged results"]}),g&&t.currentView.nextCursor&&u?e.jsx(P,{size:"sm",variant:"outline",disabled:m,onClick:()=>u(t.currentView.nextCursor),children:m?"Loading…":c?"Retry loading more Properties":"Load more Properties"}):null]}):null]})}):null]})}function Co(t){return t==="continue"?"Continue setup":t==="edit"?"Edit setup":t==="republish"?"Republish setup":"Set up advanced measurement"}function fp(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 bp({mode:t,canEdit:s,simpleOverview:n,report:a,reportState:i="ready",onOpenSetup:r,onRunMeasurement:o,onRetryReport:m,onViewChange:c,onLoadMore:h,onPropertyExpand:p,onRetryEvidence:u,renderPropertyLink:v,isRunningMeasurement:j,isOpeningSetup:b,isViewLoading:g,isLoadingMore:f,isLoadMoreError:k,viewSearch:O}){return t.surface==="simple-overview"?n:e.jsxs("div",{className:"space-y-4",children:[t.setupAction==="republish"&&!a&&s&&r?e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(P,{type:"button",size:"sm",disabled:b,onClick:r,children:b?"Opening setup…":Co(t.setupAction)}),e.jsx("p",{className:"supporting-copy m-0",children:"Unpublished changes are waiting to go live."})]}):null,i==="loading"?e.jsx("div",{className:"h-32 animate-pulse rounded-md bg-surface-subtle","aria-label":"Loading advanced measurement report"}):i==="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."}),m?e.jsx(P,{className:"mt-3",type:"button",size:"sm",variant:"outline",onClick:m,children:"Retry report"}):null]}):a?e.jsx(gp,{report:a,canEdit:s,onRunMeasurement:o,onRepublishSetup:r,onViewChange:c,onLoadMore:h,onPropertyExpand:p,onRetryEvidence:u,renderPropertyLink:v,isRunningMeasurement:j,isRepublishingSetup:b,isViewLoading:g,isLoadingMore:f,isLoadMoreError:k,viewSearch:O}):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 Ks={numerator:null,denominator:null,reason:"plan_v1"};function vp(t){return t.kind==="exact"?t.url:t.kind==="prefix"?`https://${t.host}${t.pathPrefix}`:`https://${t.host}`}function ur(t){return t.numerator===null?{numerator:null,denominator:null,reason:t.reason}:{numerator:t.numerator,denominator:t.denominator}}function yp(t){return t==="assigned"?"this-property":t==="sibling"?"another-property":t==="ownedUnmapped"?"owned-unassigned":t==="external"?"external":t==="ambiguous"?"multiple-properties":"invalid-url"}function jp(t){return t==="assigned"?"positive":t==="external"?"neutral":t==="invalid"?"negative":"caution"}function Np(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 wp(t){return t.usageEdgeType!=="target"||!t.usageEdgeId.startsWith("target:")?null:t.usageEdgeId.slice(7).split(":",1)[0]??null}function Sp(t){const s=new Map;for(const n of t){const a=wp(n);if(!a)continue;const i=s.get(a)??[];i.push(n),s.set(a,i)}return s}function Cp(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(b=>[b.stableKey,b])),i=new Map(n.querySnapshots.map(b=>[b.queryId,b.queryText])),r=new Map;for(const b of n.targetQuerySelections){const g=r.get(b.targetKey)??[];g.push(...b.queryIds.map(f=>i.get(f)).filter(f=>!!f)),r.set(b.targetKey,[...new Set(g)])}const o=Sp(s.evidence),m=n.executionNodes.reduce((b,g)=>b+g.expectedSnapshots,0),c=s.run?.status==="completed"&&m>0,h=c?m:0,p=c?m:0,u=s.targets.map(b=>{const g=a.get(b.id),f=o.get(b.id)??[],k=f.map(A=>({id:`${A.observationId}:${A.usageEdgeId}:${A.sourceUrl}`,kind:yp(A.classification),query:A.queryText,url:A.sourceUrl,tone:jp(A.classification),historical:A.historical||A.bridged})),O=f.some(A=>A.historical||A.bridged),q=s.run?b.completeness.complete?g?.mentionNotApplicable?{label:"No aliases",tone:"caution"}:{label:"Complete",tone:"positive"}:{label:`Incomplete · ${b.completeness.executed} of ${b.completeness.expected}`,tone:"caution"}:{label:"Not measured",tone:"neutral"};return{id:b.id,name:b.label,mentionCoverage:ur(b.mentionCoverage),citationCoverage:ur(b.citationCoverage),status:q,assignedQueries:r.get(b.id)??[],urls:g?.urls.map(vp)??[],evidence:k,historical:O}}),v=new Map(u.map(b=>[b.id,b])),j=new Map(n.groups.map(b=>[b.stableKey,b]));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:h,totalSlots:p,date:Np(s.run?.finishedAt??s.run?.createdAt??null),includesBridgedHistory:s.diagnostics.bridgedObservationIds.length>0||s.diagnostics.historicalObservationIds.length>0},overall:{aggregate:{metrics:{propertiesMentioned:Ks,mentionCoverage:Ks,citationCoverage:Ks},properties:u},groups:s.groups.map(b=>({id:b.id,label:b.label,confirmedCompetitorCount:j.get(b.id)?.competitors?.length??0,aggregate:{metrics:{propertiesMentioned:Ks,mentionCoverage:Ks,citationCoverage:Ks},properties:b.targetIds.map(g=>v.get(g)).filter(g=>!!g)}}))},flaggedResults:[]}}const kp={critical:"negative",high:"negative",medium:"caution",low:"neutral"};function ht(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 Ap(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 Pp(t){const s=[t.city,t.region,t.country].filter(Boolean).join(", ");return s?`${t.label} (${s})`:t.label}function Rp({projectName:t}){const[s,n]=l.useState(!1),[a,i]=l.useState(null),[r,o]=l.useState(_c),m=Ie({...Uc({client:U,path:{name:t},query:{period:r}}),placeholderData:yr});async function c(){n(!0),i(null);try{await Vc(t,"client",r)}catch(p){const u=p instanceof Zs||p instanceof Error?p.message:"Download failed";i(u)}finally{n(!1)}}if(m.isLoading)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading report…"});if(m.error){const p=m.error instanceof Error?m.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:p})})}const h=m.data;return h?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:h.meta.project.displayName}),e.jsxs("p",{className:"page-subtitle",children:[h.meta.project.canonicalDomain," · ",h.meta.project.country," / ",h.meta.project.language.toUpperCase(),h.meta.location?` · Location: ${Pp(h.meta.location)}`:" · No location set"," · ","Last ",h.meta.periodDays," days"," · ","Generated ",Ap(h.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(Ip,{period:r,onChange:o}),e.jsxs(P,{variant:"secondary",size:"sm",onClick:Me(c),disabled:s,children:[e.jsx(Dr,{className:"size-4"}),s?"Preparing…":"Download report HTML"]})]})]}),e.jsx(qp,{report:h}),e.jsx(Bp,{report:h,audience:"client"}),e.jsx(Mp,{report:h}),e.jsx(Fp,{report:h,audience:"client",projectName:t}),e.jsx(_p,{report:h})]}):null}function Ip({period:t,onChange:s}){return e.jsx("div",{className:"segmented",role:"group","aria-label":"Report time period",children:Bc.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 mr="AI Visibility — Server-Side",hr="AI engine attention",$p=t=>`What AI engines actually do in your server logs over the last ${t} days — the other half of citations.`,Tp="Live telemetry from your server logs.";function Mp({report:t}){const s=t.serverActivity;if(!s)return null;if(!s.hasData)return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(wn,{eyebrow:hr,title:mr,subtitle:Tp}),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:uu(s.verifiedCrawlerHits.current+s.unverifiedCrawlerHits.current,s.verifiedCrawlerHits.prior+s.unverifiedCrawlerHits.prior)},a=t.meta.periodDays,i=`vs prior ${a} days`,r=da(n,"requests",i),o=`${ht(s.verifiedCrawlerHits.current)} verified · ${ht(s.unverifiedCrawlerHits.current)} unverified${r?` · ${r}`:""}`,m=da(s.aiUserFetchHits,"requests",i),c=da(s.referralArrivals,"sessions",i),h=s.referralRedirects>0?`${ht(s.referralRedirects)} blocked by redirects`:"",p=[c,s.referralArrivalsClassSummary,h].filter(Boolean).join(" · "),u=s.byOperator.filter(v=>v.verifiedHits>0||v.unverifiedHits>0||v.userFetchHits>0||v.referralArrivals>0).slice(0,5);return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(wn,{eyebrow:hr,title:mr,subtitle:$p(a)}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(Ia,{label:"AI bot requests observed",value:ht(n.current),subtitle:o}),e.jsx(Ia,{label:"AI user-fetch requests",value:ht(s.aiUserFetchHits.current),subtitle:m||"ChatGPT-User, Perplexity-User, MistralAI-User"}),e.jsx(Ia,{label:"AI referral sessions",value:ht(s.referralArrivals.current),subtitle:p})]}),u.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:u.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:v.operator}),e.jsx("td",{children:ht(v.verifiedHits+v.unverifiedHits)}),e.jsx("td",{children:ht(v.userFetchHits)}),e.jsx("td",{children:ht(v.referralArrivals)})]},v.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 Lp(t,s){return t.audience==="both"||t.audience===s}const Dp={gemini:"Gemini",openai:"ChatGPT",claude:"Claude",perplexity:"Perplexity",local:"Local model","cdp:chatgpt":"ChatGPT (browser)"};function Jn(t){return Dp[t]??t.charAt(0).toUpperCase()+t.slice(1)}function Ep(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 qp({report:t}){const s=t.executiveSummary,n=t.citationScorecard,a=s.totalQueryCount,i=a>0?`${s.mentionRate}%`:"—",r=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.",o=Ep(t.whatsChanged.mentionRate),m=n.providers.length>0?n.providers.map(Jn).join(", "):`${ht(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:i}),e.jsx("p",{className:"mt-3 max-w-2xl text-base text-neutral sm:text-lg",children:r}),o&&e.jsxs("p",{className:`mt-3 text-sm font-medium ${o.tone==="positive"?"text-positive-400":o.tone==="negative"?"text-negative-400":"text-secondary"}`,children:[e.jsx("span",{className:"mr-1",children:o.arrow}),o.text]})]}),e.jsxs("div",{className:"mt-5 grid gap-4 sm:grid-cols-3",children:[e.jsx(Pa,{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(Pa,{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(Pa,{label:"AI tools tested",value:ht(s.providerCount),subtitle:m})]}),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,h)=>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(h+1).padStart(2,"0")}),e.jsxs("span",{children:['"',c,'"']})]},h))})]}),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:Jn(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,h)=>e.jsx("div",{className:"rounded-lg border border-default bg-surface px-3 py-2 text-xs text-secondary",children:c},h))})]})}function Pa({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 Op(t){switch(t){case"immediate":return"Do now";case"short-term":return"This month";case"medium-term":return"Next quarter"}}function Gp(t){switch(t){case"high":return"Strong evidence";case"medium":return"Some evidence";case"low":return"Worth trying"}}function Fp({report:t,audience:s,projectName:n}){const a=s==="client"?t.clientSummary.actionItems:t.agencyDiagnostics.priorities.length>0?t.agencyDiagnostics.priorities:t.actionPlan.filter(u=>Lp(u,s)),i=gu(t,a),r=s==="client",o=Kc(),[m,c]=l.useState(new Set),h=m.size>0?i.filter(u=>!u.targetRef||!m.has(u.targetRef)):i,p=u=>{if(!u.targetRef)return;const v=u.targetRef;c(j=>new Set(j).add(v)),o.mutate({projectName:n,body:{targetRef:v}},{onSuccess:()=>{Se({tone:"positive",title:`Dismissed "${u.title}"`,detail:"Will not appear in future reports until un-dismissed."})},onError:j=>{Se({tone:"negative",title:`Couldn't dismiss "${u.title}"`,detail:String(j)}),c(b=>{const g=new Set(b);return g.delete(v),g})}})};return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(wn,{eyebrow:r?"Action plan":"Agency actions",title:r?"What to do next":"Agency Action Plan",subtitle:r?"Approve these in order. They are sorted by what will move the needle fastest.":"The highest-leverage work, sorted by urgency and evidence strength."}),h.length===0?e.jsx(ti,{message:"No recommendations yet — run an AI check to populate this."}):e.jsx("div",{className:"grid gap-3 lg:grid-cols-2",children:h.map((u,v)=>{const j=u.evidence.length>0?u.evidence:u.why,b=u.why.length>0||u.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:v+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(oe,{tone:Qc(u),children:r?Op(u.horizon):zc(u.horizon)}),!r&&e.jsx(oe,{tone:"neutral",children:Hc(u.category)}),e.jsx(oe,{tone:"neutral",children:r?Gp(u.confidence):`${Wc(u.confidence)} confidence`})]}),e.jsx("p",{className:"text-sm font-medium text-heading",children:u.title})]})]}),e.jsx("p",{className:"mt-3 text-sm text-secondary",children:u.action}),e.jsx(Vp,{items:j,limit:3,className:"mt-3"}),b&&e.jsxs("details",{className:"mt-3 text-xs text-secondary",children:[e.jsx("summary",{className:"cursor-pointer text-muted hover:text-neutral",children:r?"See the data behind this":"Evidence details"}),u.why.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"eyebrow-soft mb-1",children:r?"Why this matters":"Why"}),e.jsx("ul",{className:"list-disc space-y-1 pl-4",children:u.why.map((g,f)=>e.jsx("li",{children:g},f))})]}),u.evidence.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"eyebrow-soft mb-1",children:r?"What we saw":"Evidence"}),e.jsx("ul",{className:"list-disc space-y-1 pl-4",children:u.evidence.map((g,f)=>e.jsx("li",{children:g},f))})]})]}),e.jsxs("p",{className:"mt-3 border-t border-default pt-3 text-xs text-neutral",children:[e.jsx("span",{className:"font-medium",children:r?"What success looks like:":"Win condition:"})," ",u.successMetric]}),u.targetRef&&!J()&&e.jsx("div",{className:"mt-3 flex justify-end",children:e.jsx("button",{type:"button",onClick:()=>p(u),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"})})]},`${u.priority}-${u.title}`)})})]})}function xr({label:t,value:s,displayValue:n,max:a,barClass:i}){const r=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 ${i}`,style:{width:`${r}%`}})})]}),e.jsx("span",{className:"whitespace-nowrap text-sm font-semibold text-heading",children:n})]})}function _p({report:t}){const s=t.aiSourceOrigin.topDomains.slice(0,5),n=t.gsc,a=t.indexingHealth,i=fu(t).slice(0,5),r=s.length>0?Math.max(...s.map(c=>c.count)):0,o=n?Math.max(...n.topQueries.slice(0,5).map(c=>c.impressions),1):0,m=s.length>0||n!==null||a!==null||i.length>0;return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(wn,{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."}),m?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(xr,{label:c.domain+(c.isCompetitor?" (competitor)":""),value:c.count,displayValue:`${ht(c.count)}×`,max:r,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:[ht(a.indexed)," of ",ht(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:ht(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:ht(n.totalImpressions)})," Google searches and got ",e.jsx("span",{className:"font-semibold text-strong",children:ht(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(xr,{label:c.query,value:c.impressions,displayValue:`${ht(c.impressions)} ${c.impressions===1?"search":"searches"}`,max:o,barClass:"bg-info-500/70"},c.query))})]}),i.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:i.map((c,h)=>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:[Yc(c.action),c.winnabilityClass==="ceded"&&e.jsx(oe,{tone:"caution",children:"Ceded surface"})]})]},h))})]})]}):e.jsx(ti,{message:"No supporting evidence yet — this fills in after the first AI check."})]})}function Za(t){return t==="up"?"positive":t==="down"?"negative":"neutral"}function ei(t){return t==="up"?"↑":t==="down"?"↓":"→"}function Ra({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==="%"?"%":"",i=Za(s.direction),r=i==="positive"?"text-positive-400":i==="negative"?"text-negative-400":"text-heading",o=n==="%"?`${s.deltaAbs>0?"+":""}${s.deltaAbs.toFixed(1)}% vs ${s.prior}%`:mu(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 ${r}`,children:[s.current,a," ",e.jsx("span",{className:"text-sm font-medium",children:ei(s.direction)})]}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:o})]})}function pr({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 i=Za(s.direction),r=i==="positive"?"text-positive-400":i==="negative"?"text-negative-400":"text-heading",o=hu(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 ${r}`,children:[ht(s.current)," ",e.jsx("span",{className:"text-sm font-medium",children:ei(s.direction)})]}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:o})]})}function Up({movements:t,audience:s}){const n=t.filter(i=>i.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(i=>{const r=i.deltaAbs>0?"+":"",o=Za(i.direction),m=o==="positive"?"text-positive-400":o==="negative"?"text-negative-400":"text-neutral";return e.jsxs("tr",{children:[e.jsx("td",{children:a?Jn(i.provider):i.provider}),e.jsxs("td",{children:[i.prior,"%"]}),e.jsxs("td",{children:[i.current,"%"]}),e.jsxs("td",{className:m,children:[r,i.deltaAbs.toFixed(1),"% ",ei(i.direction)]})]},i.provider)})})]})})]})}function gr({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 i=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:[!i&&e.jsx("th",{children:"Severity"}),e.jsx("th",{children:i?"What changed":"Title"}),e.jsx("th",{children:i?"Customer query":"Query"}),e.jsx("th",{children:i?"AI tool":"Provider"})]})}),e.jsx("tbody",{children:t.map(r=>e.jsxs("tr",{children:[!i&&e.jsxs("td",{children:[e.jsx(oe,{tone:kp[r.severity],children:Xc(r.severity)}),r.instanceCount>1&&e.jsxs("span",{className:"ml-2 text-[11px] text-muted",children:["×",r.instanceCount]})]}),e.jsxs("td",{className:"evidence-query-cell",children:[r.title,i&&r.instanceCount>1&&e.jsxs("span",{className:"ml-2 text-[11px] text-muted",children:["×",r.instanceCount]})]}),e.jsx("td",{className:"text-xs text-secondary",children:r.query}),e.jsx("td",{className:"text-xs text-secondary",children:i?Jn(r.provider):r.provider})]},r.id))})]})})]})}function Bp({report:t,audience:s}){const n=t.whatsChanged,a=s==="client",i=!n.enoughHistory&&!n.gscClicksDelta&&!n.aiReferralsDelta&&n.wins.length===0&&n.regressions.length===0,r=e.jsx(wn,{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 i?e.jsxs("section",{className:"page-section-divider",children:[r,e.jsx(ti,{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:[r,e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(Ra,{label:a?"AI mentions your name":"Citation rate",delta:a?n.mentionRate:n.citationRate,unit:"%"}),e.jsx(Ra,{label:a?"AI links to your website":"Mention rate",delta:a?n.citationRate:n.mentionRate,unit:"%"}),e.jsx(Ra,{label:a?"Queries AI mentioned you in":"Cited queries",delta:a?n.mentionedQueryCount:n.citedQueryCount,unit:"count"}),e.jsx(pr,{label:a?"Visitors from Google":"GSC clicks",delta:n.gscClicksDelta,countLabel:a?"visits":"clicks",comparisonWindowDays:n.comparisonWindowDays}),e.jsx(pr,{label:a?"Visitors from AI tools":"AI referral sessions",delta:n.aiReferralsDelta,countLabel:a?"visits":"sessions",comparisonWindowDays:n.comparisonWindowDays})]}),e.jsx(Up,{movements:n.providerMovements,audience:s}),e.jsx(gr,{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(gr,{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 Ia({label:t,value:s,tone:n,subtitle:a}){const i=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 ${i}`,children:s}),a&&e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:a})]})}function wn({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 Vp({items:t,limit:s=3,className:n}){if(t.length===0)return null;const a=t.slice(0,s),i=t.length-a.length;return e.jsxs("div",{className:`flex flex-wrap gap-1.5 ${n??""}`,children:[a.map((r,o)=>e.jsx("span",{className:"rounded-md border border-default bg-bg-elevated/40 px-2 py-0.5 text-[11px] text-neutral",children:r},o)),i>0&&e.jsxs("span",{className:"rounded-md border border-default bg-bg-elevated/40 px-2 py-0.5 text-[11px] text-secondary",children:["+",i," more"]})]})}function ti({message:t}){return e.jsx("p",{className:"text-sm text-muted py-4 text-center",children:t})}function Kp({project:t,onUpdateProject:s,onRefresh:n}){const[a,i]=l.useState(!1),[r,o]=l.useState(!1),[m,c]=l.useState(null),[h,p]=l.useState(t.displayName),[u,v]=l.useState(t.canonicalDomain),[j,b]=l.useState(t.country),[g,f]=l.useState(t.language),[k,O]=l.useState(t.ownedDomains??[]),[q,A]=l.useState(""),[d,y]=l.useState(t.aliases??[]),[S,V]=l.useState(""),[K,w]=l.useState(null),[T,F]=l.useState(!1),[$,H]=l.useState(!1),[ye,ge]=l.useState(""),[z,ee]=l.useState(""),[ie,W]=l.useState(""),[B,R]=l.useState(""),[se,le]=l.useState(""),[de,X]=l.useState(null),[Ae,_]=l.useState(null);l.useEffect(()=>{a||(p(t.displayName),v(t.canonicalDomain),b(t.country),f(t.language),O(t.ownedDomains??[]),y(t.aliases??[]))},[t,a]);function ae(){i(!1),c(null),p(t.displayName),v(t.canonicalDomain),b(t.country),f(t.language),O(t.ownedDomains??[]),y(t.aliases??[]),A(""),V("")}function Ne(){const M=q.trim();M&&(k.includes(M)||O([...k,M]),A(""))}function Le(M){O(k.filter(L=>L!==M))}function Fe(){const M=S.trim();if(!M)return;const L=M.toLowerCase();d.some(je=>je.toLowerCase()===L)||y([...d,M]),V("")}function Pe(M){y(d.filter(L=>L!==M))}async function Qe(){if(!(!h.trim()||!u.trim()||!j.trim()||!g.trim())){o(!0),c(null);try{await s(t.name,{displayName:h.trim(),canonicalDomain:u.trim(),ownedDomains:k,aliases:d,country:j.trim(),language:g.trim()}),i(!1),Se({title:"Project settings saved",detail:`${h.trim()} was updated.`,tone:"positive",dedupeKey:`project:update:${t.name}`,dedupeMode:"replace"})}catch(M){c(M instanceof Error?M.message:"Failed to save")}finally{o(!1)}}}async function ue(){const M=ye.trim(),L=z.trim(),je=ie.trim(),qe=B.trim();if(!(!M||!L||!je||!qe)){F(!0),w(null);try{const Y={label:M,city:L,region:je,country:qe};se.trim()&&(Y.timezone=se.trim()),await ed(t.name,Y),n(),ge(""),ee(""),W(""),R(""),le(""),H(!1),Se({title:"Location added",detail:`${M} is now available for ${t.name}.`,tone:"positive",dedupeKey:`project:location:add:${t.name}:${M}`,dedupeMode:"drop"})}catch(Y){w(Y instanceof Error?Y.message:"Failed to add location")}finally{F(!1)}}}async function we(M){F(!0),w(null);try{await Zc(t.name,M),n(),Se({title:"Location removed",detail:`${M} was removed from ${t.name}.`,tone:"positive",dedupeKey:`project:location:remove:${t.name}:${M}`,dedupeMode:"drop"})}catch(L){w(L instanceof Error?L.message:"Failed to remove location")}finally{F(!1)}}async function Ze(M){F(!0),w(null);try{await Jc(t.name,M),n(),Se({title:"Default location updated",detail:`${M} is now the default for ${t.name}.`,tone:"positive",dedupeKey:`project:location:default:${t.name}`,dedupeMode:"replace"})}catch(L){w(L instanceof Error?L.message:"Failed to set default location")}finally{F(!1)}}async function _e(M){X(M),_(null);try{await td(t.name,M),Se({title:`${M.toUpperCase()} download started`,detail:`Historical citation and mention results for ${t.displayName}.`,tone:"positive",dedupeKey:`project:results-export:${t.name}`,dedupeMode:"replace"})}catch(L){_(L instanceof Error?L.message:"Could not download tracking results.")}finally{X(null)}}const He=h!==t.displayName||u!==t.canonicalDomain||j!==t.country||g!==t.language||JSON.stringify(k)!==JSON.stringify(t.ownedDomains??[])||JSON.stringify(d)!==JSON.stringify(t.aliases??[]),$e="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",Ce="mb-1 block text-sm font-medium text-secondary",E=ye.trim()&&z.trim()&&ie.trim()&&B.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"})]}),!J()&&!a&&e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>i(!0),children:"Edit settings"})]}),m&&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:[m,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>c(null),children:"×"})]}),!J()&&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:Ce,children:"Display name"}),e.jsx("input",{className:$e,type:"text",value:h,onChange:M=>p(M.target.value),placeholder:"My Project"})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ce,children:"Canonical domain"}),e.jsx("input",{className:$e,type:"text",value:u,onChange:M=>v(M.target.value),placeholder:"example.com"})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ce,children:"Country"}),e.jsx("input",{className:$e,type:"text",value:j,onChange:M=>b(M.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ce,children:"Language"}),e.jsx("input",{className:$e,type:"text",value:g,onChange:M=>f(M.target.value),placeholder:"en"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ce,children:"Owned domains"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:k.map(M=>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:[M,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>Le(M),"aria-label":`Remove ${M}`,children:"×"})]},M))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${$e} flex-1`,type:"text",placeholder:"docs.example.com",value:q,onChange:M=>A(M.target.value),onKeyDown:M=>M.key==="Enter"&&(M.preventDefault(),Ne())}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:!q.trim(),onClick:Ne,children:"Add"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ce,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:d.map(M=>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:[M,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>Pe(M),"aria-label":`Remove ${M}`,children:"×"})]},M))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${$e} flex-1`,type:"text",placeholder:"Facebook",value:S,onChange:M=>V(M.target.value),onKeyDown:M=>M.key==="Enter"&&(M.preventDefault(),Fe())}),e.jsx(P,{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(P,{type:"button",disabled:r||!He||!h.trim()||!u.trim(),onClick:Me(Qe),children:r?"Saving...":"Save changes"}),e.jsx(P,{type:"button",variant:"outline",disabled:r,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(M=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:M},M))}):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(M=>e.jsx("span",{className:"rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-xs text-neutral",children:M},M))}):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:[K&&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:[K,e.jsx("button",{type:"button",className:"ml-1 text-negative-400 hover:text-negative-200",onClick:()=>w(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(M=>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 ${M.label===t.defaultLocation?"border-positive-700/60 bg-positive-950/30 text-positive":"border-mono-700/60 bg-mono-800/40 text-neutral"}`,children:[M.label,M.label===t.defaultLocation?" ★":""]})}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:M.city}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:M.region}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:M.country}),e.jsx("td",{className:"py-1.5 pr-3 text-muted",children:M.timezone??"—"}),e.jsx("td",{className:"py-1.5",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[!J()&&M.label!==t.defaultLocation&&e.jsx("button",{type:"button",disabled:T,onClick:()=>{Ze(M.label)},className:"text-sm text-secondary hover:text-positive-400 transition-colors disabled:opacity-40","aria-label":`Set ${M.label} as default location`,children:"Set default"}),!J()&&e.jsx("button",{type:"button",disabled:T,onClick:()=>{we(M.label)},className:"text-sm text-secondary hover:text-negative-400 transition-colors disabled:opacity-40","aria-label":`Remove location ${M.label}`,children:"Remove"})]})})]},M.label))})]}):e.jsx("p",{className:"text-muted text-xs mb-2",children:"No locations configured"}),J()?null:$?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:$e,type:"text",value:ye,onChange:M=>ge(M.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:$e,type:"text",value:z,onChange:M=>ee(M.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:$e,type:"text",value:ie,onChange:M=>W(M.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:$e,type:"text",value:B,onChange:M=>R(M.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:$e,type:"text",value:se,onChange:M=>le(M.target.value),placeholder:"America/New_York"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(P,{type:"button",size:"sm",disabled:T||!E,onClick:Me(ue),children:T?"Adding...":"Add location"}),e.jsx(P,{type:"button",size:"sm",variant:"outline",disabled:T,onClick:()=>{H(!1),w(null)},children:"Cancel"})]})]}):e.jsx(P,{type:"button",size:"sm",variant:"outline",onClick:()=>H(!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(P,{type:"button",variant:"outline",size:"sm",disabled:de!==null,onClick:Me(()=>_e("csv")),children:de==="csv"?"Preparing CSV...":"Download CSV"}),e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:de!==null,onClick:Me(()=>_e("json")),children:de==="json"?"Preparing JSON...":"Download JSON"})]})]}),Ae&&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:Ae})]})]})]})}function cn(t){return{...t??{}}}function zp(t,s){const n=Object.entries(t).sort(([i],[r])=>i.localeCompare(r)),a=Object.entries(s).sort(([i],[r])=>i.localeCompare(r));return n.length===a.length&&n.every(([i,r],o)=>{const m=a[o];return m?.[0]===i&&m[1]===r})}function Qp({project:t,onSave:s}){const n=Ie({queryKey:["settings"],queryFn:Sr,staleTime:6e4}),[a,i]=l.useState(t.providers.length===0),[r,o]=l.useState(t.providers),[m,c]=l.useState(()=>cn(t.providerModels)),[h,p]=l.useState({providers:t.providers,providerModels:cn(t.providerModels)}),[u,v]=l.useState(!1),[j,b]=l.useState(!1),[g,f]=l.useState(null),[k,O]=l.useState(null),q=l.useRef(null),A=n.data?.providerCatalog??[],d=l.useMemo(()=>new Set((n.data?.providers??[]).filter($=>$.configured).map($=>$.name)),[n.data]),y=l.useMemo(()=>{const $=new Map(A.map(H=>[H.name,H]));for(const H of Object.keys(m))$.has(H)||$.set(H,{name:H,displayName:H,mode:"api",modelConfigurable:!0,defaultModel:"",knownModels:[],modelValidationPattern:{source:".",flags:""},modelValidationHint:"Validate this custom model ID with the server."});return[...$.values()].sort((H,ye)=>H.displayName.localeCompare(ye.displayName))},[A,m]),S=!zp(m,h.providerModels);l.useEffect(()=>{if(u||j)return;const $={providers:t.providers,providerModels:cn(t.providerModels)};p($),i($.providers.length===0),o($.providers),c($.providerModels)},[t]);function V(){b(!0),i(!1),r.length===0&&o([...d])}function K($,H,ye=!1){b(!0),c(ge=>{const z={...ge};return H==="__inherit__"?delete z[$]:H==="__custom__"?z[$]=ye?"":z[$]??"":z[$]=H,z}),H==="__custom__"&&queueMicrotask(()=>q.current?.focus())}function w($,H){b(!0),o(ye=>H?[...new Set([...ye,$])]:ye.filter(ge=>ge!==$))}function T(){b(!1),i(h.providers.length===0),o(h.providers),c(cn(h.providerModels)),f(null),O(null)}async function F(){if(!(n.isError||n.isLoading||!a&&r.length===0)){v(!0),f(null),O(null);try{const $=Object.fromEntries(Object.entries(m).filter(([ye,ge])=>ge.trim()!==""&&(a||r.includes(ye)))),H={providers:a?[]:r,providerModels:$};await s(H),p({providers:[...H.providers],providerModels:cn(H.providerModels)}),b(!1),O("Engine settings saved. They apply on the next sweep.")}catch($){f(Va($))}finally{v(!1)}}}return J()?null:n.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…"})}):n.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(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{n.refetch()},children:"Retry"})]}):A.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(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{n.refetch()},children:"Retry"})]}):d.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(as,{to:"/settings",className:"text-link",children:"global Settings"})," before choosing project engines."]})]}):e.jsxs("section",{className:"project-engine-settings","aria-busy":u,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:u,className:"project-engine-fieldset",children:[e.jsx("legend",{children:"Provider mode"}),e.jsxs("label",{children:[e.jsx("input",{type:"radio",checked:a,onChange:()=>{b(!0),i(!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:!a,onChange:V})," Choose engines"]}),!a&&e.jsx("div",{className:"project-engine-list",children:y.map($=>{const H=r.includes($.name),ye=d.has($.name),ge=H&&!ye,z=m[$.name],ee=$.knownModels.some(W=>W.id===z),ie=z===void 0?"__inherit__":ee?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:H,disabled:!ye&&!H,onChange:W=>w($.name,W.target.checked)})," ",e.jsx("span",{children:$.displayName}),ge&&e.jsx("span",{className:"text-xs text-caution-400",children:"Not configured, skipped"})]}),H&&($.modelConfigurable?e.jsxs("div",{className:"project-engine-model",children:[e.jsx("label",{htmlFor:`project-model-${$.name}`,children:"Model"}),e.jsxs("select",{id:`project-model-${$.name}`,value:ie,onChange:W=>K($.name,W.target.value,ee),children:[e.jsxs("option",{value:"__inherit__",children:["Use instance setting: ",$.defaultModel||"default"]}),$.knownModels.map(W=>e.jsx("option",{value:W.id,children:W.displayName},W.id)),e.jsx("option",{value:"__custom__",children:"Custom model ID…"})]}),ie==="__custom__"&&e.jsx("input",{ref:q,"aria-label":`${$.displayName} custom model ID`,value:z??"",onChange:W=>{b(!0),c(B=>({...B,[$.name]:W.target.value}))},"aria-describedby":`project-model-hint-${$.name}`}),e.jsxs("p",{id:`project-model-hint-${$.name}`,className:"project-engine-help",children:[z?"Project override":"Inherited from instance settings",". ",$.modelValidationHint]})]}):e.jsx("p",{className:"project-engine-help",children:"Model is detected/fixed for this browser engine."}))]},$.name)})})]}),!a&&r.length===0&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"Choose at least one configured engine."}),g&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:g}),k&&e.jsx("p",{role:"status",className:"text-sm text-positive-400",children:k}),S&&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(P,{type:"button",onClick:()=>{F()},disabled:u||!a&&r.length===0,children:u?"Saving engines…":"Save engines"}),e.jsx(P,{type:"button",variant:"outline",onClick:T,disabled:u,children:"Cancel"})]})]})}const Hp=[{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"}],fr=["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 Wp({projectName:t}){const[s,n]=l.useState("loading"),[a,i]=l.useState(!1),[r,o]=l.useState("daily"),[m,c]=l.useState(6),[h,p]=l.useState(""),[u,v]=l.useState("UTC"),[j,b]=l.useState(!1),[g,f]=l.useState(""),[k,O]=l.useState(!1),[q,A]=l.useState(!1),[d,y]=l.useState(null);l.useEffect(()=>{sd(t).then(n).catch(()=>n(null))},[t]);const S=()=>{if(s&&s!=="loading"){const T=ad(s.preset??null,s.cronExpr);o(T.freq),c(T.hour),p(T.customCron);const F=fr.includes(s.timezone);v(F?s.timezone:"Other"),b(!F),f(F?"":s.timezone)}else o("daily"),c(6),p(""),v("UTC"),b(!1),f("");y(null),i(!0)},V=async()=>{O(!0),y(null);try{const F={timezone:j?g.trim()||"UTC":u};r==="custom"?F.cron=h.trim():F.preset=rd(r,m);const $=await pi(t,F);n($),i(!1),Se({title:"Schedule saved",detail:la($.preset??null,$.cronExpr,$.timezone),tone:"positive",dedupeKey:`schedule:${t}`,dedupeMode:"replace"})}catch(T){y(T instanceof Error?T.message:"Failed to save schedule")}finally{O(!1)}},K=async()=>{if(!(!s||s==="loading")){O(!0),y(null);try{const T={timezone:s.timezone,enabled:!s.enabled};s.preset?T.preset=s.preset:T.cron=s.cronExpr;const F=await pi(t,T);n(F),Se({title:F.enabled?"Schedule resumed":"Schedule paused",detail:la(F.preset??null,F.cronExpr,F.timezone),tone:"positive",dedupeKey:`schedule:toggle:${t}`,dedupeMode:"replace"})}catch(T){y(T instanceof Error?T.message:"Failed to update schedule")}finally{O(!1)}}},w=async()=>{A(!0),y(null);try{await id(t),n(null),i(!1),Se({title:"Schedule removed",detail:`${t} will no longer run automatically.`,tone:"positive",dedupeKey:`schedule:remove:${t}`,dedupeMode:"drop"})}catch(T){y(T instanceof Error?T.message:"Failed to remove schedule")}finally{A(!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"})]}),!J()&&s!=="loading"&&!a&&e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:S,children:s?"Edit schedule":"+ Set schedule"})]}),s==="loading"&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),s!=="loading"&&!a&&s===null&&e.jsx(pe,{className:"surface-card compact-card",children:e.jsx("p",{className:"supporting-copy",children:"No schedule configured. Set one to automatically trigger visibility sweeps."})}),s!=="loading"&&!a&&s!==null&&e.jsxs(pe,{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:[e.jsx("p",{className:"text-sm font-medium text-strong",children:la(s.preset??null,s.cronExpr,s.timezone)}),e.jsxs("p",{className:"text-xs text-muted",children:["Cron: ",e.jsx("span",{className:"font-mono",children:s.cronExpr})]}),s.nextRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Next run: ",new Date(s.nextRunAt).toLocaleString()]}),s.lastRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Last run: ",new Date(s.lastRunAt).toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(oe,{tone:s.enabled?"positive":"neutral",children:s.enabled?"Active":"Paused"}),!J()&&e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:k,onClick:Me(K),children:s.enabled?"Pause":"Resume"}),!J()&&e.jsx(P,{type:"button",variant:"ghost",size:"sm",disabled:q,onClick:Me(w),children:q?"Removing...":"Remove"})]})]}),d&&e.jsx("p",{className:"text-negative-400 text-sm mt-2",children:d})]}),!J()&&a&&e.jsxs("div",{className:"rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-3",children:[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:r,onChange:T=>o(T.target.value),children:Hp.map(T=>e.jsx("option",{value:T.value,children:T.label},T.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:m,disabled:r==="twice-daily"||r==="custom",onChange:T=>c(parseInt(T.target.value)),children:Array.from({length:24},(T,F)=>e.jsx("option",{value:F,children:nd(F)},F))})]})]}),r==="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:h,onChange:T=>p(T.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:j?"Other":u,onChange:T=>{T.target.value==="Other"?(b(!0),v("Other")):(b(!1),v(T.target.value))},children:[fr.map(T=>e.jsx("option",{value:T,children:T},T)),e.jsxs("option",{value:"Other",children:["Other (enter manually)","…"]})]}),j&&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:g,onChange:T=>f(T.target.value)})]}),d&&e.jsx("p",{className:"text-negative-400 text-sm",children:d}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{i(!1),y(null)},children:"Cancel"}),e.jsx(P,{type:"button",size:"sm",disabled:k||r==="custom"&&!h.trim(),onClick:Me(V),children:k?"Saving...":"Save schedule"})]})]})]})}const Yp=[{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 Xp({projectName:t}){const[s,n]=l.useState("loading"),[a,i]=l.useState(!1),[r,o]=l.useState(""),[m,c]=l.useState(["citation.lost","citation.gained"]),[h,p]=l.useState(!1),[u,v]=l.useState(null),[j,b]=l.useState({}),[g,f]=l.useState(new Set);l.useEffect(()=>{od(t).then(n).catch(()=>n([]))},[t]);const k=d=>{c(y=>y.includes(d)?y.filter(S=>S!==d):[...y,d])},O=async()=>{if(!(!r.trim()||m.length===0)){p(!0),v(null);try{const d=await ld(t,{channel:"webhook",url:r.trim(),events:m});n(y=>y==="loading"?[d]:[...y,d]),o(""),c(["citation.lost","citation.gained"]),i(!1),Se({title:"Webhook added",detail:`Notifications will be sent to ${d.url}.`,tone:"positive",dedupeKey:`notification:add:${t}`,dedupeMode:"drop"})}catch(d){v(d instanceof Error?d.message:"Failed to add webhook")}finally{p(!1)}}},q=async d=>{if(!g.has(d)){f(y=>new Set(y).add(d));try{await dd(t,d),n(y=>y==="loading"?y:y.filter(S=>S.id!==d)),Se({title:"Webhook removed",detail:`${t} no longer sends notifications to this endpoint.`,tone:"positive",dedupeKey:`notification:remove:${t}:${d}`,dedupeMode:"drop"})}catch(y){v(y instanceof Error?y.message:"Failed to remove webhook")}finally{f(y=>{const S=new Set(y);return S.delete(d),S})}}},A=async d=>{b(y=>({...y,[d]:{state:"testing"}}));try{const y=await cd(t,d);b(S=>({...S,[d]:{state:y.ok?"ok":"fail",status:y.status}})),y.ok&&Se({title:"Test notification sent",detail:`Webhook returned status ${y.status}.`,tone:"positive",dedupeKey:`notification:test:${t}:${d}`,dedupeMode:"replace"})}catch{b(y=>({...y,[d]:{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"})]}),!J()&&s!=="loading"&&e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{i(!a),v(null)},children:a?"Cancel":"+ Add webhook"})]}),!J()&&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:r,onChange:d=>o(d.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:Yp.map(d=>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:m.includes(d.value),onChange:()=>k(d.value)}),e.jsx("span",{className:"text-sm text-neutral",children:d.label})]},d.value))})]}),u&&e.jsx("p",{className:"text-negative-400 text-sm",children:u}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(P,{type:"button",variant:"outline",size:"sm",onClick:()=>{i(!1),v(null)},children:"Cancel"}),e.jsx(P,{type:"button",size:"sm",disabled:h||!r.trim()||m.length===0,onClick:Me(O),children:h?"Adding...":"Add webhook"})]})]}),s==="loading"&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),s!=="loading"&&s.length===0&&!a&&e.jsx(pe,{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(d=>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:d.urlHost,children:d.urlDisplay??d.url})}),e.jsx("td",{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:d.events.map(y=>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:y.replace("."," ")},y))})}),e.jsx("td",{children:e.jsx(oe,{tone:d.enabled?"positive":"neutral",children:d.enabled?"Active":"Paused"})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[j[d.id]&&(()=>{const y=j[d.id],S=y.state==="testing"?"Sending…":y.state==="ok"?`Delivered${y.status?` (${y.status})`:""}`:`Failed${y.status?` (${y.status})`:""}`;return e.jsx(oe,{tone:y.state==="ok"?"positive":y.state==="fail"?"negative":"neutral",children:S})})(),!J()&&e.jsx(P,{variant:"ghost",size:"sm",type:"button",disabled:j[d.id]?.state==="testing",onClick:()=>{A(d.id)},children:"Test"}),!J()&&e.jsx(P,{variant:"ghost",size:"sm",type:"button",disabled:g.has(d.id),onClick:()=>{q(d.id)},children:g.has(d.id)?"Removing…":"Remove"})]})})]},d.id))})]}),u&&e.jsx("p",{className:"text-negative-400 text-sm mt-2",children:u})]})]})}const br=2e3,vr=3e5;function Jp(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 Zp({projectName:t,refreshNonce:s}){const n=Cs(),[a,i]=l.useState(null),[r,o]=l.useState([]),[m,c]=l.useState(null),[h,p]=l.useState([]),[u,v]=l.useState([]),[j,b]=l.useState(null),[g,f]=l.useState(""),[k,O]=l.useState(""),[q,A]=l.useState(""),[d,y]=l.useState(!0),[S,V]=l.useState(!1),[K,w]=l.useState(null),[T,F]=l.useState("performance");l.useEffect(()=>{$()},[t,s]);async function $(){y(!0),w(null);try{const R=await n.fetchQuery({...Tr({client:U,path:{name:t}}),staleTime:$t});if(i(R),R.connected){const[se,le,de,X]=await Promise.all([n.fetchQuery({...Ld({client:U,path:{name:t}}),staleTime:$t}).catch(()=>null),n.fetchQuery({...Dd({client:U,path:{name:t}}),staleTime:$t}).catch(()=>[]),n.fetchQuery({...Ed({client:U,path:{name:t}}),staleTime:$t}).catch(()=>[]),R.siteUrl?Promise.resolve([]):n.fetchQuery({...qd({client:U,path:{name:t}}),staleTime:$t}).then(Ae=>Ae.sites).catch(()=>[])]);c(se),p(le),v(de),o(X)}else c(null),p([]),v([]),o([])}catch(R){w(R instanceof Error?R.message:"Failed to load Bing data")}finally{y(!1)}}async function H(){if(k.trim()){w(null);try{const R=await Od(t,k.trim());await ft(n,"bing"),O(""),R.availableSites.length>0&&o(R.availableSites),await $()}catch(R){w(R instanceof Error?R.message:"Failed to connect")}}}async function ye(){try{await Gd(t),await ft(n,"bing"),i(null),o([]),c(null),p([]),v([]),b(null),A(""),w(null)}catch(R){w(R instanceof Error?R.message:"Failed to disconnect")}}async function ge(){if(q)try{await Fd(t,q),await ft(n,"bing"),await $()}catch(R){w(R instanceof Error?R.message:"Failed to set site")}}async function z(){if(g.trim())try{const R=await _d(t,g.trim());await ft(n,"bing"),b(R),p(se=>[R,...se])}catch(R){w(R instanceof Error?R.message:"Inspection failed")}}async function ee(R){V(!0),w(null);try{const se=await fi(t,{urls:[R]}),{succeeded:le,failed:de,total:X}=se.summary;Se({title:"Bing submission requested",detail:de===0?`${le} URL submitted to Bing.`:`${le}/${X} submitted successfully, ${de} failed.`,tone:de===0?"positive":"caution",dedupeKey:`bing:indexing:${t}:${R}`,dedupeMode:"replace"})}catch(se){const le=se instanceof Error?se.message:"Submission failed";w(le),Se({title:"Bing submission failed",detail:le,tone:"negative",dedupeKey:`bing:indexing:${t}:${R}`,dedupeMode:"replace"})}finally{V(!1)}}async function ie(){V(!0),w(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 R=await fi(t,{allUnindexed:!0}),{succeeded:se,failed:le,total:de}=R.summary;Se({title:"Bing submissions requested",detail:le===0?`${se}/${de} URL${de!==1?"s":""} submitted to Bing.`:`${se}/${de} submitted successfully, ${le} failed.`,tone:le===0?"positive":"caution",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}catch(R){const se=R instanceof Error?R.message:"Batch submission failed";w(se),Se({title:"Bing submissions failed",detail:se,tone:"negative",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}finally{V(!1)}}if(d)return e.jsx(pe,{className:"surface-card",children:e.jsx("div",{className:"text-sm text-secondary",children:"Loading Bing data..."})});if(!a?.connected)return J()?e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(oe,{tone:"caution",children:"Not connected"})]}),e.jsx("p",{className:"text-sm text-neutral",children:"Bing Webmaster Tools is not connected for this project."})]}):e.jsxs(pe,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(oe,{tone:"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:k,onChange:R=>O(R.target.value),onKeyDown:R=>{R.key==="Enter"&&H()}}),e.jsx(Ye,{size:"sm",disabled:!k.trim(),onClick:Me(H),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"})]})]}),K&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:K})]});if(!a.siteUrl)return e.jsxs(pe,{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(oe,{tone:"positive",children:"Connected"}),!J()&&e.jsx(Ye,{size:"sm",variant:"ghost",onClick:Me(ye),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?qt(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"}),r.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:q,onChange:R=>A(R.target.value),children:[e.jsx("option",{value:"",children:"Select a site..."}),r.map(R=>e.jsxs("option",{value:R.url,children:[R.url,R.verified?" (verified)":""]},R.url))]}),!J()&&e.jsx(Ye,{size:"sm",disabled:!q,onClick:Me(ge),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."})]})]}),K&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:K})]});const W=[{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"}],B=W.find(R=>R.key===T)??W[0];return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(pe,{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(oe,{tone:"positive",children:"Connected"}),!J()&&e.jsx(Ye,{size:"sm",variant:"ghost",onClick:Me(ye),children:"Disconnect"})]})]}),K&&e.jsx("p",{className:"mb-3 text-xs text-negative-400",children:K}),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?qt(a.updatedAt):"—"})]})]})]})]}),e.jsxs(pe,{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:B.eyebrow}),e.jsx("h3",{children:B.title})]}),e.jsx("p",{className:"text-xs text-muted",children:m?.lastInspectedAt?`Last inspected ${qt(m.lastInspectedAt)}`:"No inspection history yet"})]}),e.jsx("div",{className:"flex gap-1 border-b border-base",children:W.map(R=>e.jsx("button",{className:`px-3 py-1.5 text-xs font-medium border-b-2 transition-colors ${T===R.key?"border-mono-200 text-strong":"border-transparent text-muted hover:text-neutral"}`,onClick:()=>F(R.key),children:R.label},R.key))}),T==="coverage"&&m&&e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(Rn,{label:"Indexed",value:m.summary.indexed,tone:"positive"}),e.jsx(Rn,{label:"Not in index",value:m.summary.notIndexed+(m.summary.unknown??0),tone:"negative"}),e.jsx(Rn,{label:"Status unknown",value:m.summary.unknown??0,tone:"neutral"}),e.jsx(Rn,{label:"Coverage",value:`${m.summary.percentage}%`,tone:"neutral"})]}),m.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 (",m.notIndexed.length,")"]}),!J()&&e.jsx(Ye,{size:"sm",variant:"ghost",disabled:S,onClick:Me(ie),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"}),!J()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:m.notIndexed.map(R=>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:R.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:R.httpCode??"—"}),!J()&&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:()=>{ee(R.url)},children:"Submit"})})]},R.id))})]})})]}),(m.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 (",(m.unknown??[]).length,")"]}),!J()&&e.jsx(Ye,{size:"sm",variant:"ghost",disabled:S,onClick:Me(ie),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"}),!J()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:(m.unknown??[]).map(R=>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:R.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:R.lastCrawledDate?qt(R.lastCrawledDate):"—"}),!J()&&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:()=>{ee(R.url)},children:"Submit"})})]},R.id))})]})})]}),m.indexed.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"mb-2 text-xs font-medium text-secondary",children:["Indexed (",m.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:m.indexed.map(R=>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:R.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:R.lastCrawledDate?qt(R.lastCrawledDate):"—"})]},R.id))})]})})]})]}),T==="coverage"&&!m&&e.jsx("p",{className:"mt-4 text-xs text-muted",children:"No coverage data yet. Inspect URLs to build coverage data."}),T==="inspections"&&e.jsxs("div",{className:"mt-4 space-y-3",children:[!J()&&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:g,onChange:R=>f(R.target.value),onKeyDown:R=>{R.key==="Enter"&&z()}}),e.jsx(Ye,{size:"sm",disabled:!g.trim(),onClick:Me(z),children:"Inspect"})]}),j&&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:j.url}),e.jsxs("div",{className:"text-secondary",children:["In Index: ",e.jsx("span",{className:j.inIndex?"text-positive-400":"text-negative-400",children:j.inIndex?"Yes":"No"})," · ","HTTP: ",j.httpCode??"—"," · ","Crawled: ",j.lastCrawledDate??"—"]})]}),h.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:h.map(R=>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:R.url}),e.jsx("td",{className:"py-1.5 px-3",children:e.jsx(oe,{tone:R.inIndex?"positive":"negative",children:R.inIndex?"Yes":"No"})}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:R.httpCode??"—"}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:qt(R.inspectedAt)})]},R.id))})]})})]}),T==="performance"&&e.jsx("div",{className:"mt-4",children:u.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:Pn[Ls.Clicks]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-16",children:Pn[Ls.Impressions]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:Pn[Ls.CTR]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:Pn[Ls.Position]})]})}),e.jsx("tbody",{children:u.map((R,se)=>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:R.query}),e.jsx("td",{className:"py-1.5 px-3 text-right text-strong",children:R.clicks}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:R.impressions}),e.jsxs("td",{className:"py-1.5 px-3 text-right text-secondary",children:[(Number.isFinite(R.ctr)?R.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:R.averagePosition.toFixed(1)})]},se))})]})})})]})]})}function eg({projectName:t}){const s=Cs(),[n,a]=l.useState("google"),[i,r]=l.useState(!0),[o,m]=l.useState("idle"),[c,h]=l.useState(null),p=l.useRef(null),[u,v]=l.useState(null),[j,b]=l.useState(null),[g,f]=l.useState(0);async function k(q=!1){q||r(!0),h(null);try{const[A,d]=await Promise.all([s.fetchQuery({...Ba({client:U,path:{name:t}}),staleTime:$t}).catch(()=>[]),s.fetchQuery({...Tr({client:U,path:{name:t}}),staleTime:$t}).catch(()=>null)]),y=A.find(S=>S.connectionType==="gsc")??null;v(y),b(d)}catch(A){h(A instanceof Error?A.message:"Failed to load search engine connections")}finally{r(!1)}}async function O(){if(o!=="idle")return;p.current?.abort();const q=new AbortController;p.current=q;const A=q.signal;m("syncing"),h(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 d=[],y=[];try{async function S(){if(!u)return;const w=await Td(t);if(!w?.id)return;const T=Date.now()+vr;for(;Date.now()<T;){if(A.aborted||(await new Promise($=>setTimeout($,br)),A.aborted))return;const F=await Ta(w.id).catch(()=>null);if(!F)break;if(["completed","failed","cancelled"].includes(F.status)){F.status!=="completed"&&d.push(`Google sync ${F.status}`);return}}y.push("Google sync is still running — search data will appear shortly")}async function V(){if(!j?.connected)return;const w=await Md(t).catch(()=>null);if(!w?.id){d.push("Bing sweep could not be started");return}const T=Date.now()+vr;for(;Date.now()<T;){if(A.aborted||(await new Promise($=>setTimeout($,br)),A.aborted))return;const F=await Ta(w.id).catch(()=>null);if(!F)break;if(["completed","failed","cancelled","partial"].includes(F.status)){F.status==="failed"?d.push("Bing sweep failed"):F.status==="partial"&&y.push("Bing sweep finished with some pages unverified");return}}y.push("Bing sweep is still running — coverage will update shortly")}const K=await Promise.allSettled([S(),V()]);for(const w of K)w.status==="rejected"&&d.push(w.reason instanceof Error?w.reason.message:"Sync failed");if(await Promise.all([ft(s,"gsc"),ft(s,"bing")]),A.aborted)return;if(m("reloading"),await k(!0),f(w=>w+1),d.length>0){const w=`Partial refresh: ${[...d,...y].join("; ")}`;h(w),Se({title:"Search coverage partially refreshed",detail:w,tone:"caution",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}else y.length>0?Se({title:"Search coverage refresh incomplete",detail:y.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(!A.aborted){const V=S instanceof Error?S.message:"Refresh failed";h(V),Se({title:"Search coverage refresh failed",detail:V,tone:"negative",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}}finally{A.aborted||m("idle")}}return l.useEffect(()=>(k(),()=>{p.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(([q,A])=>e.jsx("button",{type:"button",role:"tab","aria-selected":n===q,className:`project-subnav-link ${n===q?"project-subnav-link-active":""}`,onClick:()=>a(q),children:A},q))}),!J()&&e.jsxs(Ye,{type:"button",variant:"outline",size:"sm","aria-label":"Refresh search data",disabled:i||o!=="idle",onClick:()=>{O()},children:[e.jsx(Qn,{className:`h-3.5 w-3.5 ${o!=="idle"?"animate-spin":""}`,"aria-hidden":"true"}),i?"Loading…":o==="syncing"?"Refreshing search data…":o==="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(om,{projectName:t,refreshNonce:g}),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(Zp,{projectName:t,refreshNonce:g})]})]})}function Zn({label:t,summary:s,displayValue:n,tooltip:a}){const i=s.value.trim()!==""&&Number.isFinite(Number(s.value)),r=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(Je,{text:a||s.tooltip||""})]}),e.jsx("p",{className:`aeo-hero-row-value ${jr[s.tone]}`,children:n??e.jsxs(e.Fragment,{children:[s.value,i?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:`${r}%`}})}),e.jsx("p",{className:"aeo-hero-row-detail",children:s.delta})]})}function tg({model:t,sweepRunning:s}){const n=t.citationMovement,a=t.mentionMovement,i=t.movementComparison,r=t.recentRuns.find(v=>v.kind===Os["answer-visibility"]),o=v=>v.tone==="positive"?"improved":v.tone==="negative"?"declined":v.gained>0||v.lost>0?"mixed":"steady",m=o(a),c=o(n),h=(()=>{if(s)return"A fresh sweep is running now";if(!i.hasPreviousRun)return"Baseline captured. The next sweep will show change.";if(i.querySetChanged)return"Tracking scope changed since the previous sweep";if(m===c)return m==="steady"?"Answer mentions and citation coverage held steady":m==="mixed"?"Answer mention and citation movement was mixed":`Answer mentions and citation coverage ${m}`;const v=m==="mixed"?"Answer mention movement was mixed":m==="steady"?"Answer mentions held steady":`Answer mentions ${m}`,j=c==="mixed"?"citation movement was mixed":c==="steady"?"citation coverage held steady":`citation coverage ${c}`;return`${v}; ${j}`})(),p=[i.addedQueryCount>0&&`${i.addedQueryCount} ${i.addedQueryCount===1?"query":"queries"} added`,i.removedQueryCount>0&&`${i.removedQueryCount} ${i.removedQueryCount===1?"query":"queries"} removed`].filter(Boolean).join(", "),u=`${i.comparableQueryCount} comparable ${i.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(Je,{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:h})]}),e.jsx("p",{className:"overview-brief-updated",children:r?`Updated ${r.startedAt}`:"No completed sweep"})]}),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(Zn,{label:"Mentioned",summary:t.mentionSummary}),e.jsx(Zn,{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"}),i.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"}),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.jsxs("div",{className:"overview-signal-change-row",children:[e.jsx("span",{className:"overview-signal-change-label",children:"Cited"}),n.gained===0&&n.lost===0?e.jsx("span",{className:"text-secondary",children:"No change"}):e.jsxs("span",{className:"flex gap-3 tabular-nums",children:[n.gained>0&&e.jsxs("span",{className:"text-positive-400",children:["+",n.gained]}),n.lost>0&&e.jsxs("span",{className:"text-negative-400",children:["-",n.lost]})]})]})]}),e.jsx("p",{className:`overview-brief-panel-copy ${i.querySetChanged?"text-caution-400/80":""}`,children:i.querySetChanged?`${p||"Query set changed"} · ${u}.`:`${u}.`})]}):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:"Run another sweep to measure mention and citation movement."})]})]})]})]})}function $a({id:t,eyebrow:s,title:n,meta:a,defaultOpen:i=!1,children:r}){return e.jsxs("details",{id:t,className:"overview-disclosure page-section-divider scroll-mt-24",open:i||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(Wn,{className:"overview-disclosure-icon",size:16,"aria-hidden":"true"})]})]}),e.jsx("div",{className:"overview-disclosure-body",children:r})]})}function sg({insights:t,suggestedQueries:s,projectName:n}){const{openEvidence:a}=Nr(),i=$r(),[r,o]=l.useState(new Set);if(t.length===0&&s.rows.length===0)return null;const m=f=>{o(k=>{const O=new Set(k);return O.delete(f),O})},c=f=>{o(k=>new Set(k).add(f)),i.mutate({projectName:n,queries:[f]},{onSuccess:()=>{Se({tone:"positive",title:`Tracking "${f}"`}),m(f)},onError:k=>{Se({tone:"negative",title:`Could not track "${f}"`,detail:String(k)}),m(f)}})},h=f=>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:f.title}),f.detail?e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-secondary",children:f.detail}):null]}),e.jsx(oe,{tone:f.tone,children:f.actionLabel})]}),f.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 · ",f.affectedPhrases.length," affected ",f.affectedPhrases.length===1?"query":"queries"]}),e.jsx("ul",{className:"mt-2 divide-y divide-subtle border-y border-subtle",children:f.affectedPhrases.map((k,O)=>e.jsxs("li",{className:"flex flex-wrap items-center gap-2 py-2",children:[e.jsx(Ma,{state:k.citationState}),e.jsx("span",{className:"min-w-0 flex-1 text-sm text-strong",children:k.query}),k.provider?e.jsx(Js,{provider:k.provider}):null,!J()&&k.evidenceId?e.jsx(P,{type:"button",variant:"ghost",size:"sm",onClick:()=>{a(k.evidenceId)},children:"View evidence"}):null]},k.evidenceId||`${f.id}-${O}`))})]}):null]},f.id),p=f=>{const k=r.has(f.query);return 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:f.query}),e.jsx("p",{className:"mt-0.5 text-sm text-secondary",children:f.reason})]}),J()?null:e.jsx(P,{type:"button",variant:"outline",size:"sm",disabled:k,"aria-label":`Track query "${f.query}"`,onClick:()=>c(f.query),children:k?"Tracking…":"Track"})]},f.query)},u=t.slice(0,1),v=s.rows.slice(0,1),j=t.slice(1),b=s.rows.slice(1),g=j.length+b.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:[u.map(h),v.map(p)]}),g>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:[g," more ",g===1?"signal":"signals"]}),e.jsxs("div",{className:"mt-2 divide-y divide-default border-y border-default",children:[j.map(h),b.map(p)]})]}):null]})}function bg(t){const{projectName:s}=Eo({from:"/projects/$projectName"}),a=ud()?.dashboard.projects.find(v=>v.project.name===s||v.project.id===s)?.project.name??null,i=Ie({...md({client:U}),enabled:!a}),r=a??i.data?.find(v=>v.name===s||v.id===s)?.name??null,{commandCenter:o,isLoading:m,latestVisibilityRevision:c,refetch:h}=hd(r),p=!a&&i.isLoading||m;return!r&&!a&&i.isSuccess&&!m?e.jsx("div",{className:"page-container",children:e.jsxs(pe,{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(P,{asChild:!0,children:e.jsx(as,{to:"/",children:"Return to overview"})})]})}):!o||p?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(v=>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"})]},v))}),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(v=>e.jsx("div",{className:"skeleton-text-sm w-full"},v))})]})]}):e.jsx(ag,{model:o,refetch:h,latestVisibilityRevision:c,...t})}function ng({items:t,activeTab:s}){const[n,a]=l.useState(!1),i=l.useRef(null);if(l.useEffect(()=>{if(!n)return;const o=c=>{i.current&&!i.current.contains(c.target)&&a(!1)},m=c=>{c.key==="Escape"&&a(!1)};return document.addEventListener("pointerdown",o),document.addEventListener("keydown",m),()=>{document.removeEventListener("pointerdown",o),document.removeEventListener("keydown",m)}},[n]),t.length===0)return null;const r=t.some(o=>o.key===s);return e.jsxs("div",{className:"project-subnav-more",ref:i,children:[e.jsxs("button",{type:"button",className:`project-subnav-link project-subnav-more-trigger ${r?"project-subnav-link-active":""}`,"aria-haspopup":"menu","aria-expanded":n,onClick:()=>a(o=>!o),children:["More",e.jsx(Wn,{className:"h-3.5 w-3.5","aria-hidden":"true"})]}),n?e.jsx("div",{className:"project-subnav-menu",role:"menu",children:t.map(o=>e.jsx(as,{to:o.href,role:"menuitem",className:`project-subnav-menu-item ${o.key===s?"project-subnav-menu-item-active":""}`,"aria-current":o.key===s?"page":void 0,onClick:()=>a(!1),children:o.label},o.key))}):null]})}function ag({tab:t,model:s,refetch:n,latestVisibilityRevision:a}){const i=qo(),r=Cs(),{canWrite:o}=Ir(),m=l.useMemo(()=>{const C=xd();return C?pd(C.projectTabs):void 0},[]),c=gd(t,m),h=l.useMemo(()=>s.competitors.map(C=>C.domain),[s.competitors]),[p,u]=l.useState(!1),[v,j]=l.useState(!1),b=$r(),g=Oo({strict:!1}),f=g.manageQueries===!0,k=l.useCallback(()=>{i({to:".",replace:!0,search:C=>({...C,siteHealthRunId:void 0})})},[i]),[O,q]=l.useState(f),[A,d]=l.useState(""),[y,S]=l.useState(!1),[V,K]=l.useState(null),[w,T]=l.useState(!1),[F,$]=l.useState(""),[H,ye]=l.useState(!1),[ge,z]=l.useState(void 0),[ee,ie]=l.useState(!1),[W,B]=l.useState(null),[R,se]=l.useState(null),[le,de]=l.useState(!1),X=Nu(g),[Ae,_]=l.useState(void 0),[ae,Ne]=l.useState(void 0),Le=l.useCallback(C=>{_(C.search),C.sort&&Ne(C.sort),i({to:".",search:be=>({...be,...Su(C)}),replace:!1})},[i]),[Fe,Pe]=l.useState(!1),Qe=s?.visibilityEvidence??[],ue=s?.project.name??"",we=s?.project.displayName||s?.project.name||ue,Ze=fd(),_e=Ie({...bd({client:U,path:{name:ue}}),enabled:c==="portfolio"&&!!ue,staleTime:0,refetchOnMount:"always"}),He=Ie({...vd({client:U,path:{name:ue}}),enabled:!J()&&!!ue,retry:!1}),$e=Ie({...yd({client:U,path:{name:ue}}),enabled:!J()&&(c==="portfolio"||c==="overview"||c==="settings")&&!!ue,staleTime:0,refetchOnMount:"always"}),Ce=Ie({...jd({client:U,path:{name:ue}}),enabled:!J()&&(c==="portfolio"||c==="overview"||c==="settings")&&!!ue,staleTime:0,refetchOnMount:"always"}),E=He.data,M=E?.enabled&&E.nextRunAt?`Next AI sweep ${new Date(E.nextRunAt).toLocaleString()}`:null,L=$e.data?.active??null,je=$e.data!==void 0,qe=new Set(L&&Number(L.plan.schemaVersion)===2?L.plan.groups?.map(C=>C.stableKey)??[]:[]),Be={...X.scope==="group"&&!!X.groupKey&&je&&!qe.has(X.groupKey)?{scope:"all",queryClass:X.queryClass}:X,...Ae?{search:Ae}:{}},mt=L===null?null:Number(L.plan.schemaVersion),ot=L?.revision??0,De=je?`${ue}:${ot}`:null,Oe=l.useRef(null);l.useEffect(()=>{const C=Oe.current;De!==null&&(Oe.current=De),wu(C,De)&&(Le({scope:"all",queryClass:"all"}),Pe(!1))},[De,Le]);const xt={client:U,path:{name:ue},query:{scope:Be.scope,...Be.groupKey?{groupKey:Be.groupKey}:{},queryClass:Be.queryClass,...Be.search?{search:Be.search}:{},...ae?{sort:ae}:{},limit:50}},We=Go({...Nd(xt),enabled:c==="overview"&&!!ue&&mt===2,initialPageParam:xt,getNextPageParam:(C,be)=>{if(!C.properties.nextCursor)return;const ve=be[0]?.measurement.displayedRunId;return{path:xt.path,query:{...xt.query,cursor:C.properties.nextCursor,...ve?{runId:ve}:{}}}},placeholderData:yr,staleTime:0,refetchOnMount:"always"}),Ve=We.data?.pages[0]?.measurement.displayedRunId,Te=Ie({...wd({client:U,path:{name:ue},query:{revision:ot,...Ve?{runId:Ve}:{}}}),enabled:c==="overview"&&!!ue&&L!==null&&(mt===1||Fe&&Ve!==void 0),staleTime:0,refetchOnMount:"always"}),jt=$e.data!==void 0,Tt=_e.data!==void 0,Ue=$e.isPending&&!jt,Ge=$e.isError&&!jt,bt=_e.isPending&&!Tt,Ke=_e.isError&&!Tt,Nt=Te.data!==void 0,kt=fp({activePlanSchemaVersion:Ce.data?.activeSchemaVersion??mt,hasDraft:Ce.data?.draft!==null&&Ce.data?.draft!==void 0}),vt=Ce.data===void 0&&$e.data===void 0&&($e.isLoading||Ce.isLoading),At=Ce.data!==void 0?"success":Ce.isError?"error":"pending",lt=l.useMemo(()=>{const C=We.data?.pages;return C?!ru(C):!1},[We.data]),G=l.useMemo(()=>{const C=We.data?.pages,be=C?.[0],ve=C?.at(-1);if(!(!be||!ve||lt))return{...be,properties:{...be.properties,items:C.flatMap(I=>I.properties.items),nextCursor:ve.properties.nextCursor}}},[lt,We.data]),ke=l.useMemo(()=>{if(L)return L.plan.schemaVersion===1?Te.data?Cp(L,Te.data):void 0:G?ou({overview:G,activePlan:L,sort:ae,report:Te.data,reportState:G.measurement.displayedRunId===void 0?"ready":Te.isFetching&&Te.data===void 0?"loading":Te.isError&&Te.data===void 0?"error":Te.data?"ready":"loading"}):void 0},[L,Te.data,Te.isError,Te.isFetching,G]),fe=mt===2?lt?"error":We.isPending?"loading":We.isError&&ke===void 0?"error":"ready":Te.isPending&&!Nt?"loading":Te.isError&&!Nt?"error":"ready",he=(s?.recentRuns??[]).some(C=>C.kind===Os["answer-visibility"]&&(C.status===gi.running||C.status===gi.queued)),Mt=l.useMemo(()=>(s?.project.locations??[]).map(C=>C.label),[s?.project.locations]),ct=l.useMemo(()=>new Set(Qe.map(C=>C.location??"")),[Qe]),Pt=ct.has(""),Lt=l.useMemo(()=>[...new Set(Qe.map(C=>C.query))].sort((C,be)=>C.localeCompare(be)),[Qe]),Wt=l.useMemo(()=>{const C=[...ct].filter(Boolean);return C.length>1?C:Mt},[ct,Mt]);l.useEffect(()=>{if(ge===void 0||ge===""||!ue){se(null),de(!1);return}de(!0),Sd(ue,ge,20).then(C=>{se(C),de(!1)}).catch(()=>{se(null),de(!1)})},[ge,ue]);const Dt=l.useMemo(()=>{if(!R)return null;const C=new Map;for(const be of R){for(const[ve,I]of Object.entries(be.providerRuns??{}))C.set(`${be.query}::${ve}`,I.map(Q=>({runId:Q.runId,citationState:Q.citationState,createdAt:Q.createdAt,answerMentioned:Q.answerMentioned,visibilityState:Q.visibilityState,visibilityTransition:Q.visibilityTransition,mentionState:Q.mentionState,mentionTransition:Q.mentionTransition})));(!be.providerRuns||Object.keys(be.providerRuns).length===0)&&C.set(`${be.query}::`,be.runs.map(ve=>({runId:ve.runId,citationState:ve.citationState,createdAt:ve.createdAt,answerMentioned:ve.answerMentioned,visibilityState:ve.visibilityState,visibilityTransition:ve.visibilityTransition,mentionState:ve.mentionState,mentionTransition:ve.mentionTransition})))}return C},[R]),is=l.useMemo(()=>{let C=ge!==void 0?Qe.filter(be=>ge===""?!be.location:be.location===ge):Qe;if(W){const be=W.toLowerCase();C=C.filter(ve=>ve.competitorDomains.some(I=>I.toLowerCase()===be))}return Dt?C.map(be=>{const ve=Dt.get(`${be.query}::${be.provider}`)??Dt.get(`${be.query}::`);return ve?{...be,runHistory:ve}:be}):C},[Qe,ge,W,Dt]);async function nt(){try{await Ze.mutateAsync({projectName:ue,projectLabel:we,sourceAction:"project-run"}),n()}catch{}}async function ms(){j(!0);try{await $d(ue),Se({title:"Project deleted",detail:`${we} was removed.`,tone:"positive",dedupeKey:`project:delete:${ue}`,dedupeMode:"drop"}),i({to:"/"}),n()}catch(C){console.error("Failed to delete project:",C)}finally{j(!1)}}async function wt(){const C=A.split(`
|
|
8
|
+
`).map(be=>be.trim()).filter(Boolean);if(C.length!==0){S(!0);try{await Pd(ue,C),n(),d("")}finally{S(!1)}}}async function hs(C){K(C);try{await Ad(ue,[C]),n()}catch(be){Se({title:"Could not remove query",detail:be instanceof Error?be.message:`Failed to remove "${C}"`,tone:"negative",dedupeKey:"query:remove",dedupeMode:"replace"})}finally{K(null)}}async function Ot(){const C=F.trim();if(C){ye(!0);try{await Cd(ue,[C]),n(),$(""),T(!1)}finally{ye(!1)}}}async function Yt(C){const be=s.competitors.find(ve=>ve.domain===C);if(!be){Se({title:"Could not remove competitor",detail:`Could not find ${C} in the tracked competitor list`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"});return}try{await kd(ue,be.id),n()}catch(ve){Se({title:"Could not remove competitor",detail:ve instanceof Error?ve.message:`Failed to remove ${be.domain}`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"})}}async function Bt(C,be){const ve=await Rd(C,be);return await r.invalidateQueries({queryKey:Rr({client:U})}),r.setQueryData(Id({client:U,path:{name:C}}),ve),Jp(r,ve),ve}const et=`/projects/${encodeURIComponent(s.project.name)}`,xs=[{key:"overview",label:"AI Visibility",href:et},{key:"search-console",label:"Search Engines",href:`${et}/search-console`},{key:"activity",label:"Activity",href:`${et}/activity`},{key:"technical-aeo",label:"Site Health",href:`${et}/technical-aeo`},{key:"conversions",label:"Conversions",href:`${et}/conversions`},{key:"local",label:"Local Presence",href:`${et}/local`},{key:"discovery",label:"Query Discovery",href:`${et}/discovery`},{key:"backlinks",label:"Backlinks",href:`${et}/backlinks`}],Gt=[{key:"report",label:"Report",href:`${et}/report`},{key:"history",label:"Change History",href:`${et}/history`}],St=xs.filter(C=>ca(C.key,m)),ps=Gt.filter(C=>ca(C.key,m)),dt=ca("settings",m)?{key:"settings",label:"Settings",href:`${et}/settings`}:null;function Zt(C,be=!1){const ve=document.getElementById(C);if(!ve)return;be&&ve instanceof HTMLDetailsElement&&(ve.open=!0);const I=window.matchMedia("(prefers-reduced-motion: reduce)").matches;window.requestAnimationFrame(()=>{ve.scrollIntoView({behavior:I?"auto":"smooth",block:"start"}),(ve instanceof HTMLDetailsElement?ve.querySelector("summary"):ve)?.focus({preventScroll:!0})})}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]}),!J()&&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(C=>e.jsx("span",{className:"tag",children:C},C))]})]}),e.jsxs("div",{className:"page-header-right",children:[e.jsx("p",{className:"text-sm text-muted",children:s.dateRangeLabel}),!J()&&e.jsxs("div",{className:"flex items-center gap-3",children:[M?e.jsx("p",{className:"text-sm text-secondary",children:M}):null,e.jsx(Ye,{type:"button",variant:"outline",disabled:Ze.isPending||he,onClick:Me(nt),children:Ze.isPending?"Starting…":he?"AI sweep running…":"Run AI sweep"})]})]})]}),e.jsxs("nav",{className:"project-subnav","aria-label":"Project sections",children:[St.map(C=>e.jsx(as,{to:C.href,className:`project-subnav-link ${C.key===c?"project-subnav-link-active":""}`,"aria-current":C.key===c?"page":void 0,children:C.label},C.key)),e.jsxs("div",{className:"project-subnav-trailing",children:[e.jsx(ng,{items:ps,activeTab:c}),dt&&e.jsx(as,{to:dt.href,className:`project-subnav-link ${c==="settings"?"project-subnav-link-active":""}`,"aria-current":c==="settings"?"page":void 0,children:dt.label},dt.key)]})]}),c==="portfolio"&&!J()?e.jsx(Jx,{projectName:ue,canEdit:o,queries:_e.data??[],isQueryLoading:bt,isQueryError:Ke,onRetryQueries:()=>{_e.refetch()},publishedPlan:L,onCreateQueries:async C=>(await b.mutateAsync({projectName:ue,queries:[...C]}),(await _e.refetch({throwOnError:!0})).data??[]),onManageProjectQueries:()=>{i({to:"/projects/$projectName",params:{projectName:ue},search:{manageQueries:!0}})},onPublished:()=>{Promise.all([Ce.refetch(),$e.refetch()]).finally(()=>{i({to:"/projects/$projectName",params:{projectName:ue}})})}},ue):c==="overview"?vt?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:[Ge?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(P,{type:"button",size:"sm",variant:"outline",onClick:()=>{$e.refetch()},children:"Retry setup check"})]}):null,e.jsx(bp,{mode:kt,canEdit:o&&!J()&&!Ue&&!Ge,simpleOverview:e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"page-section-divider",children:e.jsx(ph,{projectName:s.project.name,competitorDomains:h,analyticsRevision:a})}),e.jsx(tg,{model:s,sweepRunning:he}),e.jsx(sg,{insights:s.insights,suggestedQueries:s.suggestedQueries,projectName:s.project.name}),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:"Competitive"}),e.jsx("h2",{children:"Where competitors are winning"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("p",{className:"supporting-copy",children:[s.competitors.length," tracked"]}),!J()&&e.jsx(Ye,{type:"button",variant:"outline",size:"sm",onClick:()=>T(!w),children:w?"Cancel":"+ Add competitor"})]})]}),e.jsxs("div",{className:"aeo-hero competitive-summary",children:[e.jsx(Ru,{summary:s.mentionShareSummary,projectLabel:s.project.displayName||s.project.name,competitorDomains:h},s.project.name),e.jsx("div",{className:"competitive-gaps",children:e.jsxs("div",{className:"aeo-hero-rows",children:[e.jsx(Zn,{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(Zn,{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."})]})})]}),w&&e.jsxs("div",{className:"mt-4 mb-3 flex gap-2 rounded-lg border border-base bg-bg-elevated/40 p-3",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:"competitor.com",value:F,onChange:C=>$(C.target.value),onKeyDown:C=>{C.key==="Enter"&&Ot()}}),e.jsx(Ye,{type:"button",size:"sm",disabled:!F.trim()||H,onClick:Me(Ot),children:H?"Adding...":"Add"})]}),s.competitors.length>0&&e.jsxs("details",{className:"inline-disclosure mt-4",children:[e.jsx("summary",{children:"Review tracked competitors"}),e.jsx("div",{className:"mt-3",children:e.jsx(Gu,{competitors:s.competitors,onSelectCompetitor:C=>{B(C),Zt("evidence-section",!0)},onRemoveCompetitor:J()?void 0:C=>{Yt(C)},activeFilter:W})})]})]}),e.jsxs($a,{id:"evidence-section",eyebrow:"Tracked coverage",title:"Query evidence",meta:`${s.queryCounts.total} ${s.queryCounts.total===1?"query":"queries"}`,defaultOpen:J(),children:[!J()&&e.jsx("div",{className:"mb-3 flex items-center justify-end",children:e.jsx(Ye,{type:"button",variant:"outline",size:"sm",onClick:()=>q(!O),children:O?"Done":"Manage queries"})}),!J()&&O&&e.jsxs("div",{className:"mb-3 rounded-lg border border-base bg-bg-elevated/40 p-3",children:[Lt.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:Lt.map(C=>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:C,children:C}),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 ${C}`,title:`Stop tracking "${C}"`,disabled:V!==null,onClick:()=>{hs(C)},children:V===C?"Removing…":"Remove"})]},C))}):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:A,onChange:C=>d(C.target.value)}),e.jsxs("div",{className:"mt-2 flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-muted",children:[A.split(`
|
|
9
|
+
`).filter(C=>C.trim()).length," to add"]}),e.jsx(Ye,{type:"button",size:"sm",disabled:!A.trim()||y,onClick:Me(wt),children:y?"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 ${ge===void 0?"filter-chip-active":""}`,type:"button","aria-pressed":ge===void 0,onClick:()=>{z(void 0)},children:"All locations"}),s.project.locations.map(C=>e.jsx("button",{className:`filter-chip ${ge===C.label?"filter-chip-active":""}`,type:"button","aria-pressed":ge===C.label,onClick:()=>{z(C.label),ie(!1)},children:C.label},C.label)),Pt&&e.jsx("button",{className:`filter-chip ${ge===""?"filter-chip-active":""}`,type:"button","aria-pressed":ge==="",onClick:()=>{z(""),ie(!1)},children:"No location"}),Wt.length>1&&ge===void 0&&e.jsx("button",{className:`filter-chip filter-chip-compare ${ee?"filter-chip-active":""}`,type:"button","aria-pressed":ee,onClick:()=>ie(C=>!C),title:"Side-by-side location comparison",children:"Compare"})]}),W&&e.jsxs("div",{className:"mb-3 flex items-center gap-2 rounded-md border border-negative-900/40 bg-negative-950/20 px-3 py-2",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-wide text-negative-400",children:"Competitor filter"}),e.jsxs("span",{className:"text-sm text-strong",children:["Showing queries where ",e.jsx("span",{className:"font-semibold",children:W})," surfaced"]}),e.jsx("button",{type:"button",className:"ml-auto text-xs text-secondary hover:text-strong",onClick:()=>B(null),children:"Clear filter ×"})]}),e.jsx(Du,{evidence:is,compareLocations:ee})]}),e.jsxs($a,{eyebrow:"Analysis",title:"Citation and engine diagnostics",meta:"Deep dive",defaultOpen:J(),children:[e.jsx(Lm,{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(Je,{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(C=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"flex flex-col items-start gap-0.5",children:[e.jsx(Js,{provider:C.provider}),C.model&&e.jsx("span",{className:"text-[11px] font-mono text-muted",children:C.model})]})}),e.jsx("td",{children:e.jsxs("span",{className:"font-semibold text-strong",children:[C.score,"%"]})}),e.jsxs("td",{className:"text-muted",children:[C.cited," of ",C.total]})]},`${C.provider}::${C.model??"unknown"}`))})]})})]})]}),!J()&&e.jsx($a,{eyebrow:"Run history",title:"Recent execution history",meta:`${s.recentRuns.length} recent`,children:e.jsx("div",{className:"run-list",children:s.recentRuns.map(C=>e.jsx(Ud,{run:C},C.id))})})]}),report:ke,reportState:fe,onOpenSetup:J()?void 0:()=>{i({to:"/projects/$projectName/portfolio",params:{projectName:ue}})},onRetryReport:()=>{mt===2?Promise.all([We.refetch(),Te.refetch()]):Te.refetch()},onViewChange:C=>{Le({scope:C.scope,...C.groupKey?{groupKey:C.groupKey}:{},queryClass:C.queryClass,...C.search?.trim()?{search:C.search.trim()}:{}})},onLoadMore:C=>{C===G?.properties.nextCursor&&We.fetchNextPage()},onPropertyExpand:()=>{Fe&&Te.isError&&Te.refetch(),Pe(!0)},onRetryEvidence:()=>{Te.refetch()},renderPropertyLink:mt===2&&!J()?({id:C,name:be})=>e.jsx(as,{to:"/projects/$projectName/properties/$targetKey",params:{projectName:ue,targetKey:C},className:"text-link hover:underline",children:be}):void 0,isViewLoading:We.isPlaceholderData,isLoadingMore:We.isFetchingNextPage,isLoadMoreError:We.isFetchNextPageError,viewSearch:Be.search??""},`${ue}:${ot}`)]}):c==="settings"?e.jsxs(e.Fragment,{children:[e.jsx(Kp,{project:{...s.project,displayName:s.project.displayName??s.project.name,defaultLocation:s.project.defaultLocation??null},onUpdateProject:async(C,be)=>{await Bt(C,be)},onRefresh:()=>{n()}}),e.jsx(Qp,{project:s.project,onSave:async C=>{await Bt(s.project.name,C)}}),o&&!J()?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."}),At==="pending"?e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading setup…"}):At==="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(P,{type:"button",size:"sm",variant:"outline",onClick:()=>{Ce.refetch()},children:"Retry"})]}):e.jsx(P,{type:"button",variant:"outline",onClick:()=>{i({to:"/projects/$projectName/portfolio",params:{projectName:ue}})},children:Co(kt.setupAction)})]}):null,e.jsx(Wp,{projectName:s.project.name}),e.jsx(Xp,{projectName:s.project.name}),o&&!J()?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."}),p?e.jsxs(pe,{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(P,{type:"button",variant:"destructive",disabled:v,onClick:Me(ms),children:v?"Deleting...":"Yes, delete project"}),e.jsx(P,{type:"button",variant:"outline",disabled:v,onClick:()=>u(!1),children:"Cancel"})]})]}):e.jsxs(Ye,{type:"button",variant:"outline",onClick:()=>u(!0),children:[e.jsx(Jd,{className:"h-4 w-4 text-secondary"}),"Delete project"]})]}):null]}):c==="report"?e.jsx(Rp,{projectName:s.project.name}):c==="discovery"?e.jsx(Sh,{projectName:ue}):c==="technical-aeo"?e.jsx(Bd,{projectName:s.project.name,projectId:s.project.id,initialRunId:g.siteHealthRunId,onReleaseInitialRun:k}):c==="conversions"?e.jsxs(e.Fragment,{children:[e.jsx(xx,{projectName:s.project.name},`${s.project.id}:performance`),e.jsx(ex,{projectId:s.project.id,projectName:s.project.name},s.project.id)]}):c==="history"?e.jsx(Ih,{projectName:s.project.name}):c==="activity"?e.jsx(Hu,{projectName:s.project.name}):c==="backlinks"?e.jsx(Mm,{projectName:s.project.name}):c==="local"?e.jsx(cm,{projectName:s.project.name,projectId:s.project.id}):c==="search-console"?e.jsx(eg,{projectName:s.project.name}):null]})}export{bg as ProjectPage,Jp as patchProjectDashboardCache};
|